Appearance
Server APIs (flat on the facade)
Called directly on SensorBioSDK.<method>(…). One-shot reads are suspend fun … : SB_… (pull-to-refresh / single fetch). The cache-backed reads additionally expose an …Updates(…): Flow<SB_…> sibling (iOS-parity …Updates → AsyncThrowingStream): a stale-while-revalidate stream that emits the last-known cached value immediately, then the authoritative value (fresh server value, or the final/stale cache per the cache policy — final-past served from disk, today always fetched, forceRemote bypass, stale-on-failure fallback). collect { … } one of these from a ViewModel instead of pairing a cache peek with a fetch. The suspend cachedX(…) peeks were removed in favour of the streams.
| Domain | Methods (flat on SensorBioSDK) |
|---|---|
| Dashboard | fetchDashboardData(date: Instant, tzOffset, forceRemote), dashboardUpdates(date: Instant, tzOffset, forceRemote): Flow<SB_DashboardData> (the one read a dashboard makes per day — see "One read per day" below), clearDashboardData(date: Instant) (metricsList also carries the SDK's own TEMPERATURE_DASH_METRIC and STRESS_INDEX_DASH_METRIC tiles — see below and §5.9.1) |
| Skin temperature | getSkinTemperature(date: Instant) -> SB_SkinTemperature? (local-first read — aggregates the local temperature_data rows for the day into min/max/average + ascending points, all Celsius, with no network when the day has points on device; a day with none falls back to the server, backfills the points locally as already-uploaded rows and re-reads — §5.13. Never throws; null when the day has no points anywhere or the fallback fails. The day is the HR / HRV / RR reads' — midnight to midnight plus every sleep that ended on it — and each point carries an SB_HRPointType ASLEEP / AWAKE tag (SB-1433). App applies °C/°F for display.) |
| Skin temperature trending | fetchDailyTemperature(date: Instant, forceRemote: Boolean = false) -> SB_DailyTemperatureTrending, fetchRangeTemperature(date: Instant, granularity: SB_ViewGranularity, forceRemote: Boolean = false) -> SB_TemperatureRangeTrending (server reads, disk-cached like the other trending reads; Celsius. Range takes WEEK / MONTH / YEAR only — §5.13.) |
| SpO2 | getSpO2(date: Instant) -> SB_SpO2? (SB-1433 — on-device read: aggregates the valid, non-zero SpO2 slots of the local ppg_data_results rows for the day into min/max/average + ascending points, in percent, each tagged SB_HRPointType ASLEEP / AWAKE (same day window as the HR / HRV / RR reads); no network; null when the day has no valid readings. Day only — fetchRangeSpO2 is the server week/month/year read.) |
| Local-first dashboard | getDashboardData(date: Instant) -> SB_DashboardData (SB-2422 — the same payload as fetchDashboardData, assembled on the device: rings from the local sleep / recovery / activity scores, tiles from the get…Points reads, plus the skin temperature and stress index tiles fetchDashboardData adds (§5.9.1); the respiratory-rate and SpO2 tiles as the server's take them — the day's longest sleep, or the whole day when it has no sleep, with SpO2 falling back to getSpO2's day mean. The resting HR, HRV, respiratory-rate and SpO2 tiles carry IMPROVEMENT_VS_BASELINE footers from getBiometricBaselines (§5.8.1) when the metric has a baseline; the rest are VALUE_NOT_SET. Never throws; a part it can't read is absent. No insights or sleep recommendation.) |
| Biometric baselines | getBiometricBaselines(date: Instant) -> SB_BiometricBaselines (the day's resting HR / HRV / respiratory rate / SpO2 against their 30-day baselines, computed on the device — see §5.8.1) |
| Continuous stress index | getStressIndex(date: Instant) -> SB_StressIndexDay?, fetchStressIndex(date: Instant) -> SB_StressIndexDay? (SB-2229 — on-device and server reads of a day's stress index — see §5.9.1) |
| Device data export | getDevicePackets(handler: suspend (SB_DevicePacketBatch) -> Unit) -> Int (SB-2630 — offline mode only: parses the stored raw device packets to CSV on the device and hands them over a page at a time, deleting each page once handler returns — see Device data export) |
| Local-first HR points | getHRPoints(date: Instant) -> SB_HRDataPoints (local-first read — see §5.2) |
| Local-first HRV points | getHRVPoints(date: Instant) -> SB_HRVDataPoints (local-first read — see §5.3) |
| Local-first RR points | getRRPoints(date: Instant) -> SB_RRDataPoints (local-first read — see §5.4) |
| Local-first steps | getStepsPoints(date: Instant) -> SB_StepsDataPoints (local-first read — see §5.5) |
| Local-first calories | getCaloriesPoints(date: Instant) -> SB_CaloriesDataPoints (local-first read — see §5.6) |
| Local-first sleep | getSleepDetail(date: Instant) -> SB_SleepDetailDay? (local-first read — same shape as the server fetchSleepDetail, rebuilt from the on-device sleep_sessions row; see §5.7) |
| Local-first sleep graphs | getSleepHR(sessionEndTimestamp: Long), getSleepHRV(…), getSleepRR(…) — each -> List<SB_TimeValuePoint> (the session's HR / HRV / RR timeseries for the sleep biometric graphs; local-first with server-detail fallback; see §5.7) |
| Local-first sleep disturbances | getSleepArmDisturbances(sessionEndTimestamp: Long) -> List<SB_SleepDisturbancePoint> (the session's arm-restlessness severity timeline, bucketed from on-device activity_packets; colour-free SB_SleepDisturbanceLevel per epoch; fully local, no fallback; see §5.7) |
| Trending | fetchRangeHR/fetchDailyHR, fetchRangeHRV/fetchDailyHRV, fetchRangeRR/fetchDailyRR, fetchRangeSpO2/fetchDailySpO2, fetchCalories, fetchSteps, fetchDailyActivityDetail, fetchRangeRecovery/fetchDailyRecovery (all take date: Instant; forceRemote optional). All four daily biometric reads return the same SB_BiometricDailyTrending — see §5.10. Stale-then-fresh Flow siblings: rangeHRUpdates/dailyHRUpdates, rangeHRVUpdates/dailyHRVUpdates, rangeRRUpdates/dailyRRUpdates, rangeSpO2Updates/dailySpO2Updates, caloriesUpdates, stepsUpdates, dailyActivityDetailUpdates, rangeRecoveryUpdates/dailyRecoveryUpdates. (fetchDailyRecovery/dailyRecoveryUpdates are computed on-device where possible — see §5.8; fetchDailyActivityDetail/dailyActivityDetailUpdates likewise for DAY — see §5.9) |
| Sleep | fetchSleepDetail(endDate: Instant, endTimestamp, forceRemote?), fetchSleepAggregation(date: Instant, …, forceRemote?) (+ sleepDetailUpdates(endDate: Instant, endTimestamp, forceRemote?): Flow<SB_SleepDetailDay> / sleepAggregationUpdates(date: Instant, …, forceRemote?): Flow<SB_SleepDetailAggregated> stale-then-fresh streams), fetchSleepSessions(date: Instant), deleteSleepSession(endTimestamp, date: Instant), modifySleepSession(onset: Instant, wakeUp: Instant, endTimestamp, date: Instant) -> String, addSleepSession(onset: Instant, wakeUp: Instant) (writes throw SB_SleepWriteError) |
| Workouts | fetchWorkoutDetail(workoutTime: Instant) (falls back to the locally-built report — §5.11), modifyWorkout(action, date: Instant, timestamp: Instant, …), fetchWorkoutSummary(date: Instant, granularity: SB_SummaryGranularity, workoutName, workoutTime: Instant), fetchWorkoutTimeline(…, direction: SB_PageFetchDirection) -> SB_WorkoutTimelineResult, workoutTimelineUpdates() -> Flow<SB_WorkoutTimelineResult> (stale→fresh first page — §5.12), fetchWorkoutRecordingInfo |
| In-flight submissions | reconcileSubmissions(entries: List<SB_WorkoutEntry>) (flip matched in-flight cards → processed; call after each fetchWorkoutTimeline with result.items.flatMap { it.entries }; no network), retrySubmission(startTimestamp) (re-drive a FAILED submission) — observe via inflightSubmissions (§3.1) |
| Local-first reports | localRecordingEntries() -> List<SB_LocalRecordingEntry> (suspend; real timeline rows for recordings the server hasn't returned — §5.11), localWorkoutDetail(startTimestamp), localMeditationGraph(startTimestamp), localSpotCheckDetails(startTimestamp) (all suspend; the stored report, or null) |
| Activities | fetchActivityList(force: Boolean = false) -> SB_ActivityRecordingList, fetchTrainedActivities() |
| Spot-check | fetchSpotCheckDetails(recordingId) (one-shot suspend read; throws on RPC error) |
| Recording meta | fetchRecordingMetaInfo(type) -> List<SB_RecordingSessionMetaItem>, deleteRecordingMeta(id, name, type) |
| Insights | fetchNewInsights, submitInsightsFeedback, fetchPopulationInsightsMetricList, fetchPopulationInsights |
| Meditation | fetchMeditationGraph(date: Instant, sessionTimestamp) (falls back to the locally-built report — §5.11) |
| Surveys | submitBriefSurvey(survey) (suspend; returns once the answers are durable — the SDK owns when they go on the wire, see below) |
| Goals | fetchGoals(); updateGoals(steps, calories, sleep) (suspend → SB_UpdateGoalsOutcome) |
| Stats | fetchDailyStats(startDate, days, includeBiometrics, includeSleep, includeSteps) |
| Agreements | shouldRequestAgreement, acceptAgreements(tosVersion, healthDataVersion), acceptCurrentAgreements (suspend) |
| Account | updateUserProfile(SB_UserProfileUpdate), changePassword(currentPassword, newPassword), requestPasswordReset, checkEmailAvailability, validateAccountRequirements(SB_ValidateAccountRequirementsRequest) -> SB_ValidateAccountRequirementsResult, refreshUser, hydrateSession, generateTemporaryAuthToken() -> String?, registerApp(deviceId) |
| Recording submit | createActivitySession(activityName, startEpochMs, durationSecs) (suspend; manual after-the-fact log) |
| Session | registerUser(userId, email?, sex?, birthdayYear?, birthdayMonth?, birthdayDay?, heightCm?, weightKg?, imperialUnits, activationCode?) -> SB_RegisterUserOutcome (SDK-key register-or-login; org creds come from sdkCredentials — see §5.1; this is the SDK's only registration path), signOut(), persistUser, deleteAccount, clearSession, clearPrefsOnLogout (signOut/clearSession cancel only the SDK's own WorkManager jobs; the host app's WorkManager work is left running; SB-2402) (signed-in identity is observable — see §3.1 session/userProfileFlow) |
One read per day ⚠️ behavior change
dashboardUpdates is the only read a dashboard needs for a day: every value it emits is a whole SB_DashboardData — the server's payload plus the tiles the SDK adds from the device (skin temperature below, stress index §5.9.1) — so a dashboard renders each value as it arrives and makes no getSkinTemperature or stress-gating read of its own. fetchDashboardData returns the same payload once.
- A past day it has already assembled is one cached entry, served from the device's storage without a network call; the flow emits it and completes. The entry is replaced when data lands on the day — a sync or backfill of its HR / HRV / RR, activity, steps, sleeps, skin temperature or stress points — and on
forceRemote = true, which emits the entry and then refetches. It is only kept once the server's payload for the day is final (fetched after the day ended). - Otherwise it emits the last cached payload first (its device tiles read from the device only, so the first paint never waits on the network), then the fresh value, as before.
- Offline mode: both reads return the day assembled on the device (
getDashboardData) instead of throwingSB_OfflineModeException.
Skin temperature tile. The SDK appends a TEMPERATURE_DASH_METRIC tile: the day's mean skin temperature, as getSkinTemperature's average — valueFloat in Celsius, value that rounded, title "SKIN TEMPERATURE", valueUnit "°C", footer VALUE_NOT_SET. It is absent for a day with no temperature reading. It is read from the device (falling back to the server when the device has nothing for the day), alongside the server's request, and never fails the read; the cached first paint reads the device only.
Offline mode (SB-2422)
An organization can turn on offline mode in its white-label settings when it does not want Sensor Bio holding its users' data. The SDK picks the setting up on its own, and while it is on:
- Nothing is uploaded. Metrics from the band are still decoded and stored exactly as before, pending, but no upload work is enqueued: biometrics, activity, steps, temperature, sleep, recording submissions, surveys, workout edits, algorithm results, battery and last-sync telemetry. Upload jobs that carry a request file are kept on disk and held. When the organization turns offline mode off, the held jobs are re-enqueued and every upload type is flushed, so the backlog uploads.
- Raw device data packets are kept on the device instead of uploaded, for your app to collect as CSV with
getDevicePackets(see Device data export below). Raw sensor logging follows the organization's setting in offline mode too (rawDataEnabled). With it off, what is kept is the summary data the band always syncs (steps, events, activity, skin temperature, BBI, PPG results, …); with it on, the raw waveforms (PPG, accelerometer, gyroscope, ECG) are kept alongside it, which multiplies what accumulates untilgetDevicePacketscollects it. The band is still acked. - Server reads fail. Every
fetch…method and every…Updatesflow throwsSB_OfflineModeException, even when a cached copy exists — except the configuration reads still allowed below (fetchGoals), and the dashboard (fetchDashboardData/dashboardUpdates), which returns the day assembled on the device (getDashboardData). The on-deviceget…reads keep working, and never fall back to the server;getDashboardDatabuilds the dashboard from them. Writes that go to the server (addSleepSession,updateGoals, profile updates, …) fail the same way. - Still allowed: sign-in and sign-up, token refresh, sign-out, account deletion, password change, agreements, the white-label settings fetch itself, reading goals, the enabled-algorithm list, and device linking / locked devices.
kotlin
class SB_OfflineModeException : Exception("Unavailable in offline mode")Device data export (SB-2630) ⚠️ interface change
In offline mode the band's raw device data stays on the phone. getDevicePackets parses it on the device into CSV — the same rows, byte for byte, that the web device-data download produces — and hands it to your app a page at a time. Where the CSV goes (a file, your own server, another app) is up to you. iOS parity: getDevicePackets(_:) (SB-2629).
kotlin
suspend fun getDevicePackets(handler: suspend (SB_DevicePacketBatch) -> Unit): Int // pages delivered
data class SB_DevicePacketBatch(
val serialNumber: String, // the band the data came from
val csv: Map<SB_DeviceDataStream, String>, // data rows per stream, each ending "\n", no header line
val isEndOfStream: Boolean, // this band's stream ended (offline mode turned off, or the band was removed)
)
enum class SB_DeviceDataStream(val streamName: String) {
PPG("ppg"), IMU("imu"), GYRO("gyro"), ECG("ecg"), EVENTS("events"), STEPS("steps"), ACTIVITY("activity"),
SKIN_TEMPERATURE("skin_temperature"), BATTERY("battery"), AFE_SETTINGS("afe_settings"), WORN("worn"),
MOTION("motion"), CONTINUOUS_HR("continuous_hr"), SLEEP_WAKE("sleep_wake"), BBI("bbi"), BOOKENDS("bookends"),
PPG_RESULTS("ppg_results");
val csvHeader: String // the stream's CSV header line, no trailing "\n"
}kotlin
sensorBio.getDevicePackets { batch ->
for ((stream, rows) in batch.csv) {
val file = File(folderFor(batch.serialNumber), "${stream.streamName}.csv")
appendCreatingWithHeader(file, header = stream.csvHeader, rows = rows) // throw if the write fails
}
}- Nothing is deleted until your handler returns. The SDK deletes a page's data only after
handlerreturns without throwing. If it throws — or the app is killed mid-page — the call stops (and rethrows your exception), and that page comes back on the next call. Make the handler's write durable (flush andfd.sync()) before it returns. - Call it whenever you like. With nothing stored it returns
0without callinghandler. Calls don't overlap: a second call waits for the first to finish. - Pages, not one blob. Each call delivers everything stored, one page and one band at a time (a page is about 1 MB of raw data, typically 4–14 MB of CSV).
csvhas no header lines, so pages append straight onto one file per stream: writestream.csvHeaderonce, when you create the file. A stream with no rows in a page has no entry. - The rows. The first column of every stream is
ts(ns), nanoseconds since the Unix epoch. Rows of a stream arrive in the order the band recorded them, which is almost always — but not strictly — time order; sort onts(ns)if you need it. Different streams are not in step with each other.PPGalways carries all five channel columns (an absent channel is an empty field). - The newest samples arrive with the next sync. Each sensor's last second or two of samples is held until the band's next sync, when its timing becomes known. Nothing is lost; it is in a later page.
- Storage is yours to manage. Data is kept only until it is delivered, but in offline mode it accumulates until you call. A day of continuous high-rate sensor capture can be tens of MB of raw data (hundreds of MB of CSV), so call it regularly — after each sync (
syncCompleted), say. - Outside offline mode the data is uploaded instead, and the call returns
0. The one exception is the first call after offline mode is turned off: it delivers each band's final page, withisEndOfStream == true. Whatever was not yet delivered when offline mode turned off is uploaded. - Sign-out deletes undelivered data with every other on-device record.
- Removing the band (
removeDeviceFromPairedDevices) ends its stream. The next call delivers what the band left — the data stored before the removal, then the samples held back for its next sync — and ends with a page whoseisEndOfStream == true. A band added afterwards, even the same one, starts a new stream. - A new stream starts at the beginning of a sync. Stored data from the middle of a sync whose start is gone — uploaded before offline mode was turned on — can't be parsed reliably, so it is dropped rather than delivered.
- Cost. Parsing is CPU-bound — on a desktop core, roughly 0.5–1 s per MB of raw sensor data — and runs on a background thread, where
handleris called too. Avoid starting a large backlog from a time-limited background job.
Server reads land in the database (SB-2422, all orgs). Separately from offline mode, every daily server read now also saves what it returns into the tables the get… reads use — not just the response cache — filling only what the phone is missing, any day including today: HR / HRV / RR per point, steps / calories per hour (only hours with no band rows), and sleep per night including its stage timeline. Band data is never overwritten or marked uploaded. A day viewed online is therefore readable — and scorable — on the device later, offline mode included.
Sleep-write errors (SB-2424, SB-2427)
addSleepSession and modifySleepSession throw SB_SleepWriteError:
kotlin
sealed class SB_SleepWriteError(message: String) : Exception(message) {
object InsufficientData : SB_SleepWriteError(…) // not enough band data in the window
object NeverAsleep : SB_SleepWriteError(…) // band data, but none of it scored as sleep
object TimeInFuture : SB_SleepWriteError(…) // onset or wake-up is in the future
object WakeUpNotAfterOnset : SB_SleepWriteError(…) // wake-up is not after onset
object InvalidTimes : SB_SleepWriteError(…) // onset or wake-up is missing (modify: or not ordered)
object SessionNotFound : SB_SleepWriteError(…) // modify: no session at the given end coordinates
class ModifyFailed(val serverMessage: String) : SB_SleepWriteError(serverMessage) // modify: unrecognized code
}addSleepSession names each refusal separately. Before that it threw InsufficientData for all of them, and it still does for a refusal code the SDK doesn't recognize, so an existing catch (e: SB_SleepWriteError.InsufficientData) keeps working. A when over SB_SleepWriteError must cover the new subclasses. Same cases as iOS (SB-2423).
modifySleepSession maps the server's refusal codes the same way (SB-2427): not enough data → InsufficientData, invalid times → InvalidTimes, no such session → SessionNotFound. ModifyFailed is now only the fallback for a code the SDK doesn't recognize; before SB-2427 it was thrown for every refusal, so a catch (e: SB_SleepWriteError.ModifyFailed) alone no longer sees the known codes. serverMessage is the server's unlocalized text — log it, don't show it. The String returned on success is the server's unlocalized status text too; show your own copy. None of the subclasses carry user-facing text: map each to your own localized string. Same cases as iOS (SB-2426).
Brief surveys (SB-2177)
submitBriefSurvey keeps its signature; what it does underneath changed, and the change is meant to be invisible. There is one way to submit a survey and this is it.
It no longer waits for the network. The answers are written to the SDK's store first and the call returns as soon as they are durable. Dismiss your sheet immediately — do not gate a spinner on it, and do not disable the way off the screen. (iOS did exactly that until SB-2177, awaiting the RPC with Submit and Skip disabled; a 30s deadline plus retries and a token refresh add up to minutes of a screen the user cannot leave.)
The SDK decides when it goes on the wire, and "now" is often wrong. A survey carries its recording's start timestamp — a sleep's end timestamp — as its only link to that record. Post-recording reports are built on the device and appear the instant a recording finalizes, so a user can answer within seconds, while the recording itself is still being uploaded. Sent then, the server has nothing to attach the survey to: it answers with an empty id, the survey is orphaned, and nothing on screen says so. The SDK holds the survey until the record is known to have landed, sends it then, retries on failure, and survives backgrounding and relaunch.
The answers are readable before they are sent. Every read that produces a survey merges in what this device holds — fetchWorkoutDetail, fetchMeditationGraph, fetchSleepDetail / sleepDetailUpdates, and the localWorkoutDetail / localMeditationGraph replays — so there is nothing to refetch and nothing to stamp onto your model. A survey that has not landed wins over the server's copy; once it lands the server's wins, so a survey edited elsewhere is not shadowed by this device forever.
You no longer need the returned id. It is the id the survey will be submitted under: the server's once one is known (an edit), empty before that. The SDK keeps the id on its own row and stamps it onto every later submit, so passing survey.id = null every time is now correct and cannot duplicate.
Workout modifications (SB-2217)
modifyWorkout(action = UPDATE, …) keeps its signature; what it does underneath changed, in the same way and for the same reason as submitBriefSurvey above. REMOVE and IGNORE are unchanged.
The SDK decides when it goes on the wire. ModifyWorkoutRequest addresses a workout by its start timestamp and nothing else, so it can only be applied to a workout the server already has. Post-recording reports and timeline rows are built on the device and appear the instant a recording finalizes (§5.11), so a user can edit a session's duration or calories within seconds of finishing it — while the recording itself is still uploading. Sent then, the server answers NOT_FOUND and the edit is simply refused. The SDK now records the edit first, holds it until the recording is known to have landed, sends it then, retries on failure, and survives backgrounding and relaunch.
The outcome means something narrower than it did. For a workout the server already has — every workout it returned in the first place — the call is the same synchronous one it always was and the server's verdict comes back unchanged. Otherwise it returns Ok once the edit is durable. A retryable failure also returns Ok, because the row survives and will be retried. A non-Ok outcome now means the server rejected the values themselves, so it is worth showing the user; it no longer means "this activity is too new to edit".
The new values are readable before they are sent. Every read that produces a workout applies a pending edit — fetchWorkoutDetail, localWorkoutDetail, and the synthesized rows from localRecordingEntries — covering the end timestamp, the calorie/distance metrics, and the header tiles that render them. There is nothing to refetch and nothing to stamp onto your model; a plain re-read after saving is enough. A pending edit wins over the server's copy; once it lands the server's wins, so an edit made on the web dashboard is not shadowed by this device forever.
A second edit before the first lands rewrites one row, merged key by key, rather than queueing a second modification — so a form that shows only duration cannot silently discard a queued calorie change.
REMOVE works on a workout that hasn't uploaded, too. There is no server row to delete, so the SDK discards the submission instead — the timeline row, the stored report, and any queued edit or survey for it all go with it, and a submit still on the job queue notices the recording is gone and declines to send it. A submit that was already on the wire when the delete arrived is caught on its way back and undone server-side, so a deleted activity cannot reappear on a later fetch. Whether a delete is local or remote is bookkeeping only the SDK can see, so it is no longer something to ask about: call modifyWorkout(REMOVE, …) for any row. §5.11 used to tell you to hide delete on a locally-rendered row; that instruction is withdrawn, and if you implemented it you can take it out.
| Server writes | reprocessSleep (suspend; user-tapped, throws on failure), updateUserDeviceInfo, uploadUserPhoto (→ URL), deleteUserPhoto |
locationis a full-replace field.SB_UserProfileUpdate.locationandSB_UserProfile.locationname the same value — the user's location (city / country). It maps to a wire field historically namedzipcode.updateUserProfilereplaces the whole profile, so read the current value fromuserProfileFlow.value?.locationand pass it back in on every update; sending""(ornull) overwrites the stored value on the server.
5.1 SDK registration (registerUser)
For third-party apps embedding the SDK, registerUser is a register-or-login entry point for users your app has already authenticated by its own means (your login, SSO, OAuth — the SDK doesn't care which). These users have no Sensor Bio email/password. On success the SDK persists the returned session and publishes session / userProfileFlow. It is the only registration path in the distributed SDK — there is no email/password entry point.
Your backend mints a single-use token first. Your organization SDK Key (sbsk_…) is long-lived, org-wide, and identical for every one of your users — it must never ship inside your app or reach a device. Your backend exchanges it for a single-use, minutes-long sdk_token (sbst_…) and hands that to the app:
POST https://api.sensorbio.com/sdk/v1/token
Authorization: SDKKey sbsk_...
Content-Type: application/json
{} # body optional; omit for the 5-minute default TTLjson
{
"sdk_token": "sbst_...",
"organization_id": "uuid",
"sdk_key_id": "uuid",
"expires_at": "2026-09-08T12:34:56Z",
"expires_in_seconds": 300
}sdk_token and organization_id are the only two fields your backend has to return to your app. Staging is https://staging.api.sensorbio.com. A token is good for exactly one register-or-login and expires within minutes: mint a fresh one every time, and never cache or reuse one — a spent token fails inside registerUser as an authentication error, which is confusing to debug because the failure surfaces far from its cause. Revoking an SDK Key in the dashboard signs out every user currently signed in through it, on every device, as well as preventing new sign-ins.
Building that endpoint: §6 covers it in full — the contract to serve your app, Node and Go implementations, every error the exchange returns and what to do about it, TTL choice, and how to rotate a key without signing your users out. The example app in this repo mocks that backend in-process so the SDK can be run without one; it is marked as a stand-in everywhere, because it holds an SDK Key on a device, which is the one thing the exchange exists to prevent.
sdkCredentials— setSensorBioSDK.sdkCredentials = SB_SDKCredentials(organizationId = …, sdkToken = …)immediately before eachregisterUser, from the exchange response:organizationIdis theorganization_idit returned,sdkTokenthe single-usesbst_…token. It is held in memory only, never persisted, andregisterUserspends the token and clears it.registerUserreads this — it takes neither the org id nor the token as a parameter (iOS parity) — and fails withFAILED_PRECONDITIONifsdkCredentialsis unset. Your long-lived SDK Key (sbsk_…) never goes here and never reaches the device.userId— your own stable identifier for the end-user (client_sdk_user_id). The first call for a givenuserIdregisters; subsequent calls log in. It is also recorded as the user's username (visible in the web dashboard).email(optional) — a contact email. Omitted if null/blank; when supplied it is recorded on the backend as the user's contact email (never used as the login identity).sex/birthdayYear+birthdayMonth+birthdayDay/heightCm/weightKg/imperialUnits(optional) — demographics. Any omitted value is filled with a dummy before the request is sent: the platform requires height/weight/sex/birthday to compute higher-level metrics (recovery, calories, sleep scoring, …), so a user with none would break downstream processing. Pass real values when you have them (a partial birthday — not all of year/month/day — is treated as omitted).activationCode(optional) — redeems a device-subscription activation code during a first registration.
Every failure resolves to a typed SB_RegisterUserOutcome — it does not throw on a register error. Failed carries a typed SB_ServiceErrorCode (e.g. INVALID_ARGUMENT for missing metadata, PERMISSION_DENIED for an inactive SDK key), and no raw gRPC message string ever crosses the boundary.
kotlin
// Set immediately before registering, from your backend's token exchange. The token is single use
// and this call spends it; the organization id is remembered across launches.
SensorBioSDK.sdkCredentials = SB_SDKCredentials(organizationId = orgId, sdkToken = sdkToken)
when (val outcome = SensorBioSDK.registerUser(userId = userId)) {
is SB_RegisterUserOutcome.Success -> routeToHome(outcome.session)
SB_RegisterUserOutcome.ClientSdkUserIdAlreadyInUse -> showError("This user id is already in use.")
SB_RegisterUserOutcome.DeviceSubscriptionRequired,
SB_RegisterUserOutcome.OrgBillingPeriodInactive -> showError("No active subscription — contact your administrator.")
is SB_RegisterUserOutcome.Failed -> showError("Something went wrong. (${outcome.code.name})")
else -> showError("Could not register: $outcome")
}When a session ends
If a session dies beyond recovery — refresh token past its 60-day inactivity window, revoked, or the SDK Key it was signed under revoked — the SDK signs out and surfaces the failure. Treat it like any other sign-out: mint fresh credentials, set SensorBioSDK.sdkCredentials, and call registerUser again with the same userId. Because registerUser is register-or-login on client_sdk_user_id, that returns the same user to the same data.
The SDK deliberately does not do this for you. Rebuilding a session needs a freshly minted single-use token; the SDK cannot mint one, and an earlier version that kept a host lambda around to mint from is exactly what required your SDK Key to be on the device (SB-2095).
The SDK does remember your client_sdk_user_id so you can name the user on the way back in. It is an identifier, not a credential — worthless without a fresh token — and signOut() erases it.
signOut() returns once the user's local data is gone. It awaits the SDK's on-device data wipe, so the next user to sign in can never read the previous user's records. If that wipe fails, the SDK retries it before the database is next read: at the next launch, or before the next sign-in. Nothing is required from your app.
What is transparent to your app, and what is not:
| Event | Handled by | Your app sees |
|---|---|---|
| Access token expires | SDK refreshes and replays the call | Nothing |
| Refresh token rotates | SDK | Nothing |
| Refresh chain dies (60-day inactivity, revoked, SDK Key revoked) | You | The SDK signs out; route back to your register screen with fresh credentials |
kotlin
sealed class SB_RegisterUserOutcome {
data class Success(val session: SB_Session) : SB_RegisterUserOutcome()
object InvalidClientSdkUserId : SB_RegisterUserOutcome()
object ClientSdkUserIdAlreadyInUse : SB_RegisterUserOutcome()
object InvalidHeight : SB_RegisterUserOutcome()
object InvalidWeight : SB_RegisterUserOutcome()
object InvalidBirthday : SB_RegisterUserOutcome()
object InvalidEmail : SB_RegisterUserOutcome()
object InvalidAccessCode : SB_RegisterUserOutcome()
object AccessCodeAlreadyInUse : SB_RegisterUserOutcome()
object DeviceSerialNumberRequired : SB_RegisterUserOutcome()
object DeviceSerialNumberMismatch : SB_RegisterUserOutcome()
object DeviceSubscriptionRequired : SB_RegisterUserOutcome()
object OrgBillingPeriodInactive : SB_RegisterUserOutcome()
data class Failed(val code: SB_ServiceErrorCode) : SB_RegisterUserOutcome()
}SDK users authenticate with the new-auth
session_auth_tokenonly — there is no legacyauth_token/ web-app cookie for them. The SDK stores the session's access + refresh tokens and refreshes them automatically, so subsequent authenticated calls (andsignOut()) behave exactly as for a normal sign-in.
Read-cache policy (date-keyed reads — dashboard, trending, sleep, activity, etc.): a three-case disk cache, mirroring iOS cachedRead.
- Today — always fetched fresh while online; the successful response is cached, and a fetch failure falls back to the last cached payload (so a cold offline open shows stale today rather than a blank/error).
- Past date, final cache — served straight from disk with no network. A cache entry is final only once it was written on a calendar day strictly after the date it holds.
- Past date, provisional (or missing) cache — an entry captured while that date was still "today" is provisional (the day kept accumulating data afterwards — a late device sync, a sleep the server scores hours later), so the first view of the day after it has passed refetches once to finalize it; on failure it falls back to the provisional snapshot. This is the SB-1112 fix.
forceRemote = true (pull-to-refresh) bypasses every cache shortcut and always fetches live, falling back to cache only on failure.
5.2 Local-first HR points
getHRPoints(date) returns a day's HR samples local-first: it reads the day's on-device HR with no API round-trip when that data is already synced locally. Each point is tagged AWAKE / ASLEEP from the device's sleep sessions. Only when the day predates local sync (no local HR for the window) does it fall back to the API — one daily-HR fetch + one sleep fetch — backfill the HR + sleep locally, and rebuild, so a subsequent call for the same day is served entirely from the device. The first feature of the reusable offlinefirst surface (iOS-parity getHRPoints(date:)).
The day a sample belongs to, and whether it counts as asleep, follow the server's daily-trending contract exactly (SB-1997). A day is local midnight→midnight plus the full [onset, wakeUp] span of every sleep filed under that day — and a sleep is filed under the day it ends, not the day it began. So for a 10pm–7am night:
- asking for the wake day returns samples starting at 10pm the previous evening, all tagged
ASLEEP; - asking for the day that night started returns midnight→midnight only, and its 10pm–midnight block is tagged
AWAKE, because the sleep covering it belongs to the next day.
A point is ASLEEP iff it falls inside one of that day's own sleeps — not merely inside any sleep. Callers that plot these points must let the x-axis start before midnight, since the first sample routinely does.
The three resting figures (restingHR / restingHRV / restingRR) follow the server's other rule: each is derived from the day's longest sleep alone, by that metric's own algorithm — not by averaging the day's ASLEEP samples. A day with a nap therefore has one set of sleeps driving the point tags and a single, narrower window driving the headline number.
kotlin
suspend fun getHRPoints(date: Instant): SB_HRDataPoints
data class SB_HRDataPoints(val points: List<SB_HRDataPoint>, val restingHR: Int?) {
// Computed on the fly from `points`; each is null when `points` is empty
val averageHR: Int? // mean value of all points
val restingHR: Int? // STORED, not computed: server-parity CalculateRestingBPM over the day's
// LONGEST sleep (mean of its 5 lowest outlier-free samples). Not a mean
// of the ASLEEP points, which reads several bpm high.
val lowestHR: Int? // min value
val highestHR: Int? // max value
}
data class SB_HRDataPoint(
val epoch: Long, // ms
val value: Int, // bpm, rounded from the stored Float
val type: SB_HRPointType,
)
enum class SB_HRPointType { AWAKE, ASLEEP }getHRPoints throws only on the server-backfill path (e.g. when signed out / the daily-HR or sleep fetch fails); the pure-local path never touches the network.
5.3 Local-first HRV points
getHRVPoints(date) is the HRV sibling of getHRPoints — same local-first contract: it reads the day's on-device HRV (local midnight→midnight in the device time zone) with no API round-trip when that data is already synced locally, tags each point AWAKE / ASLEEP from the device's sleep sessions, and falls back to the API (one daily-HRV fetch + one sleep fetch) only when the day predates local sync — then backfills and rebuilds so a later call is served entirely from the device. HRV shares the same single ppg_data_results row as HR (distinct columns), so the backfill updates only the HRV slot and never clobbers HR.
kotlin
suspend fun getHRVPoints(date: Instant): SB_HRVDataPoints
data class SB_HRVDataPoints(val points: List<SB_HRVDataPoint>) {
// Computed on the fly from `points`; each is null when its input set is empty.
// Mirrors the HRV day view (rMSSD + daily-average / lowest / highest): `restingHRV`
// (mean of ASLEEP/nocturnal points) is the offline proxy for the server's sleep-derived rMSSD.
val averageHRV: Int? // mean value of all points (daily average)
val restingHRV: Int? // STORED: server-parity CalculateRestingHRV over the day's LONGEST
// sleep — the residual-filtered regression line read off at wake-up
val lowestHRV: Int? // min value
val highestHRV: Int? // max value
}
data class SB_HRVDataPoint(
val epoch: Long, // ms
val value: Int, // rMSSD in ms, rounded from the stored Float
val type: SB_HRPointType, // AWAKE / ASLEEP — reused from getHRPoints
)getHRVPoints throws only on the server-backfill path (e.g. when signed out / the daily-HRV or sleep fetch fails); the pure-local path never touches the network.
5.4 Local-first RR points
getRRPoints(date) is the RR (respiratory / breathing rate) sibling of getHRPoints / getHRVPoints — same local-first contract: it reads the day's on-device RR (local midnight→midnight in the device time zone) with no API round-trip when that data is already synced locally, tags each point AWAKE / ASLEEP from the device's sleep sessions, and falls back to the API (one daily-BRPM fetch + one sleep fetch) only when the day predates local sync — then backfills and rebuilds so a later call is served entirely from the device. RR shares the same single ppg_data_results row as HR/HRV (distinct columns), so the backfill updates only the RR slot and never clobbers HR/HRV.
kotlin
suspend fun getRRPoints(date: Instant): SB_RRDataPoints
data class SB_RRDataPoints(val points: List<SB_RRDataPoint>) {
// Computed on the fly from `points`; each is null when its input set is empty.
// Mirrors the RR day view (brpm + daily-average / lowest / highest): `restingRR` is the
// server's sleep-derived brpm.
// Unlike HR/HRV these are Float — RR is inherently fractional (matches the API path's brpm).
val averageRR: Float? // mean value of all points (daily average)
val restingRR: Float? // STORED: the day's LONGEST sleep's own Brpm, to one decimal — the
// median of its captures less resting-HR and HRV outliers, which is
// the server's uncertainty-weighted mean for captures uploaded (as
// the SDK uploads them) with no uncertainty
val lowestRR: Float? // min value
val highestRR: Float? // max value
}
data class SB_RRDataPoint(
val epoch: Long, // ms
val value: Float, // breaths per minute (brpm) — raw stored Float, unrounded
val type: SB_HRPointType, // AWAKE / ASLEEP — reused from getHRPoints
)getRRPoints throws only on the server-backfill path (e.g. when signed out / the daily-BRPM or sleep fetch fails); the pure-local path never touches the network.
5.5 Local-first steps
getStepsPoints(date) is the steps sibling of getHRPoints / getHRVPoints / getRRPoints — same local-first contract: it reads the day's on-device steps (local midnight→midnight in the device time zone) with no API round-trip when that data is already synced locally, and falls back to the API (one daily-steps fetch) only when the day predates local sync — then backfills and rebuilds so a later call is served entirely from the device.
Steps differ from the vitals in three deliberate ways:
- Different store, no shared-row / slot model. Steps live in their own
engine_result_requeststable (one row per interval, with step / distance / calories / active-seconds columns), not the vitals'ppg_data_results. The backfill is a plain keyed upsert (REPLACEon the ms-epochtime), markeduploaded = trueso it never re-uploads. - No awake/asleep tag, no min/avg/max. A step total is a count, not a distribution, so there is no
SB_HRPointTypeand no lowest/average/highest — the aggregates are day totals. - Totals are non-null (default
0). A day with the band worn but idle legitimately totals0steps, so the totals never go null. Usepoints.isEmpty()to tell "no data for this day" from a genuine zero.
totalActiveSeconds is the day's active duration (SB-1662). On device it is the real per-minute active_seconds from the band; SB-1662 also fixed the store path (StepsDataManager), which previously hard-coded a flat 60 s/minute — throwing the band's duration signal away both locally and on the uploaded packet (iOS already stored the real value). On a server-backfilled day the duration comes from the server TOTAL_DURATION metric; distance and calories are recomputed from (steps, activeSeconds) via the same in-SDK formula the live store uses (the server's DISTANCE metric is in the user's display unit, not metres).
kotlin
suspend fun getStepsPoints(date: Instant): SB_StepsDataPoints
data class SB_StepsDataPoints(val points: List<SB_StepsDataPoint>) {
// Computed on the fly from `points`; day totals (non-null, default 0 — a worn-but-idle day is a genuine 0).
val totalSteps: Int // total steps
val totalDistanceMeters: Float // total distance, metres
val totalCalories: Float // total active (step) calories, kcal
val totalActiveSeconds: Int // total active duration, seconds
val hourlyBuckets: List<SB_StepsHourBucket> // points summed into local hour-of-day buckets (present hours only)
}
data class SB_StepsDataPoint(
val epoch: Long, // ms
val steps: Int,
val distanceMeters: Float, // metres
val calories: Float, // kcal
val activeSeconds: Int, // active duration in the interval, seconds
)
data class SB_StepsHourBucket(
val hour: Int, // 0..23 local hour of day
val steps: Int,
val distanceMeters: Float,
val calories: Float,
val activeSeconds: Int,
)getStepsPoints throws only on the server-backfill path (e.g. when signed out / the daily-steps fetch fails); the pure-local path never touches the network. (iOS has no getStepsPoints yet — Android leads, as with HRV/RR.)
5.6 Local-first calories
getCaloriesPoints(date) is the calorie sibling of getStepsPoints (§5.5) — same local-first contract, reading the same engine_result_requests rows — and a faithful local recreation of the backend's five-metric calorie graph (Resting, Workout, Active, Steps, Total). No API round-trip when the day is already synced locally; otherwise a steps + calories fetch, a backfill, and a rebuild.
The model mirrors the server (physicalstats.getCalorieVal) exactly. Each interval's totalStepCalories is the active calories the band measured, split into a step and a workout part:
stepCalories = max(0, totalStepCalories − workoutStepCalories)workoutCalories = max(0, workoutCalories)activeCalories = max(0, stepCalories + workoutCalories)— the floor is per point, as the server'sgetCalorieValapplies it. Inside a workout the workout part is recomputed from HR (CalculateRestingBPM's siblingcomputeWorkoutCaloriesPerMinute), not the band's step calories relabelled, and the model leaves a below-resting minute negative. SototalActiveCaloriesis not necessarilytotalStepCalories + totalWorkoutCalories— each is floored on its own, exactly as the server's tiles are.
so Active is unaffected by workouts — only the Workout↔Steps split moves. On device the band never reports the split; it is reconstructed from the day's activities for locally-synced days (a minute inside an activity counts as workout, exactly as the server reclassifies it), and from the server calories graph for backfilled days (the unified backfill persists the server's per-hour split into the rows' workout columns). Locally-synced non-workout minutes also apply the backend's per-minute step-calorie cap (round(steps/10) when the stored value exceeds steps/10) so the local Active total matches the server's. Resting is a day-level value from the user's BMR (BMR × elapsed/86400 today, full BMR for a past day), and Total = Active + Resting. Active / Total / Resting are exact regardless of the workout split.
Activity-complete (SB-2017). The calculation always runs on device. The SDK reaches the network only for inputs it does not hold, never for a server-computed calorie figure — which is why the number is reproducible offline once the inputs are cached. Activity windows used to come only from recordings made on this device since the last sign-out (upload_activity, whose one writer is the recording flow and which clearAllTables() empties on sign-out), so a workout recorded on another phone — or before a logout or reinstall — was invisible and its calories silently read as 0. Two inputs are now fetched and cached on demand:
- The day's activity list — fetched once from the server and cached in
cached_activity_day, then merged with the local recordings (the local copy wins where both describe the same activity, since only it knows the pauses). A completed past day's cached list is final; today's is refreshed at most every 15 minutes, and a recording made on this device appears immediately without any refresh. - The HR those activities need — when an activity window holds no on-device HR at all (the normal case for a workout recorded elsewhere), the day's HR is pulled into
ppg_data_resultsthrough the same backfill the HR read uses.
The derived per-minute attribution is kept in its own table (workout_minute_attribution) and joined against the activity rows at read time. The band's packets are never rewritten: sensor data is not overwritten with a derived value, which is also what keeps a server-authored split distinguishable from a computed one. The attribution is re-derived from its inputs on every read, so it can never serve a stale answer.
Two known divergences from the server on an activity that was not recorded on this device, both of them limits of what the phone can ask for rather than defects in the model:
- HR density. The server scores workout minutes from a per-second trace (
activity_biometrics) that this app uploads but that has no read endpoint. The densest HR the phone can fetch back is the ~2-minute PPG trace behind the daily BPM graph, so a minute with no sample in it is left unscored rather than filled in from a neighbour — a synthesized sample would be a number nobody measured. A remote activity can therefore read low, in proportion to how much of its HR is missing. Adding a read endpoint for the per-second trace is what would close this. - Pauses.
WorkoutDetailcarries apause_segmentsfield that the server never populates for a workout, so a remote activity's pauses are not knowable and its HR is fed to the model unfiltered. A paused remote activity therefore reads slightly high. An activity recorded on this device has its pauses exactly, and an activity with no pause has nothing to exclude.
The ring / progress tracks Active calories toward goals.calories (server parity). Totals are non-null (default 0, a worn-but-idle day is a genuine 0); no awake/asleep tag and no min/avg/max.
kotlin
suspend fun getCaloriesPoints(date: Instant): SB_CaloriesDataPoints
data class SB_CaloriesDataPoints(
val points: List<SB_CaloriesDataPoint>,
val restingCalories: Float, // day BMR calories (BMR×elapsed today, full BMR past days); 0 if no BMR
) {
// Computed on the fly (non-null, default 0). Server metric identities: active = step + workout; total = active + resting.
val totalStepCalories: Float // "Steps" tile, kcal
val totalWorkoutCalories: Float // "Workout" tile, kcal
val totalActiveCalories: Float // "Active" tile (drives the ring), kcal
val totalCalories: Float // "Total" tile = active + resting, kcal
val hourlyBuckets: List<SB_CaloriesHourBucket> // active/step/workout summed into local hour buckets (present hours only)
}
data class SB_CaloriesDataPoint(
val epoch: Long, // ms
val stepCalories: Float, // kcal
val workoutCalories: Float, // kcal
) { val activeCalories: Float } // = max(0, stepCalories + workoutCalories), floored per point
data class SB_CaloriesHourBucket(
val hour: Int, // 0..23 local hour of day
val stepCalories: Float, // kcal
val workoutCalories: Float, // kcal
) { val activeCalories: Float } // = max(0, stepCalories + workoutCalories), floored per pointgetCaloriesPoints throws only on the server-backfill path (e.g. when signed out / the fetch fails); the pure-local path never touches the network. (iOS has no getCaloriesPoints yet — Android leads, as with steps/HRV/RR.)
5.7 Local-first sleep detail
getSleepDetail(date) is the sleep member of the family — same local-first contract, but sleep is stored on-device as sessions (the sleep_sessions rows) rather than a per-epoch timeseries, so instead of a bespoke points container it returns the same SB_SleepDetailDay the server fetchSleepDetail returns. The sleep-detail screen renders it unchanged. The day's longest session (most time asleep) is surfaced. A session is attributed to the day it wakes up — it may start the previous evening (or be a nap fully inside the day), but a session that starts in the day and wakes the next belongs to the next day (so an overnight sleep isn't double-counted on both days). Two paths:
- On-device day (a device-recorded session with stages exists): the detail is rebuilt entirely from the local row — no API round-trip — with all the server-parity math below.
- Old day (no on-device sleep — it predates local sync): a server-backed read, like the vitals do — it fetches the day's server sleep, persists every session's window locally via
persistServerSleep(marked uploaded; there may be several sleeps in a day, and the windows let the vitals reads tag against them), and returns the main session's full serverSB_SleepDetailDay(server stages / score / factors / penalties / biometrics / disturbances). So old days show the real sleep rather than an empty shell.
null when neither the device nor the server has sleep for the day.
A night the band recorded in pieces is one session (SB-2437). The band often ends a sleep on a wake and starts another when the user settles again; the server joins those into one sleep, and so do the local reads, with the server's rules: sleeps that overlap or sit less than 60 minutes apart are merged when they end on the same date (in the sleep's own offset), and when a date's first sleep starts before 01:00 the previous date's last sleep can join it too (so a night split across midnight is one night, filed under the morning). The merged night keeps the first piece's start and onset and the last piece's wake-up; its SB_SleepItem.end is the last piece's end + 1 s, as on the server. Each gap between pieces counts as awake — in Total Awake, Awakenings, the score and the stage timeline — but, as on the server, not in the stage percentages. The resting HR / HRV, graphs and arm disturbances are read over the whole night, gaps included. This applies to every on-device sleep read — getSleepDetail, getSleepSessions, the graph and disturbance reads, getDashboardData, the local recovery score and the daily resting HR / HRV — and matters most in offline mode, where nothing reaches the server to be merged there. The sleep_sessions rows are not changed: each piece is still uploaded on its own and the server does its own merge. A sessionEndTimestamp that is one piece's wake-up resolves to the night containing it.
The returned SB_SleepDetailDay is populated with what the device stores, recomputed to match server-first exactly (the server re-derives its stage metrics after upload, so the entity's own stored totals — summed over the full stage list — would not match):
- stage metrics — the per-epoch stages are clamped to
[sleepOnset, wakeUp]and re-counted (serverUpdateSleepDerivedMetricsUsingTimestampedStages), so the leading sleep-latency awake and any trailing awake are excluded. Each stage's minutes are the epoch count divided by the device's epochs-per-minute with integer truncation (serverint32(count / multiplier)), matching the server to the minute. This drives the four legend percentages (largest-remainder rounding), the per-stage duration tiles,sleepTimeSec= (light + deep + rem) × 60, and the in-window arousal count. The stage-timelineintervalsare likewise the in-window epochs; sleepOnset/wakeUpTime/timezone;- biometrics from the on-device
ppg_data_resultsover the sleep window, each reproduced the server's way:restingHr(header —CalculateRestingBPM: mean of the 5 lowest lower-fence-outlier-free BPM), the Average HR tile (median of the same outlier-free BPM) and the Nocturnal HRV tile (CalculateRestingHRV: the residual-outlier-free OLS HRV-vs-time line evaluated at the last epoch). Each is0/omitted when there is too little data — the server's "too little": fewer than 5 samples, or for HRV fewer than 3 non-zero samples to fit (or more than 3,600). Resting HR and HRV are computed in the shared C library (SB_restingHR/SB_restingHRVin mobile_edge_algorithms), the same code on both platforms, checked against the server's own Go: resting HR matches it exactly, resting HRV to float32 precision (the server fits its line by a QR decomposition, the C by centred least squares); metrics— the locally-derivable tiles, in the server's tile order with the server's labels: Total Time in Bed (= wakeUp − onset + 1 min), Total Awake, Light, Deep, REM Sleep (DURATION), Nocturnal HRV (ms), Average HR (bpm), Awakenings (count), Sleep Latency (= onset − start), then the two editableTimeTztiles Sleep Onset + Wake up Time.SleepMetricsGridhides any tile whose value is≤ 0and full-widths the first survivor;- the sleep score + contributing factors + penalties (
sleepScore/scoreFactors/scorePenalty), computed locally to match the server'sCalculateSleepMainScore:score = max(1, goalAchieved×efficiency×100 − penalties). Factors = Total Sleep (vs the user's sleep goal fromGetGoal, default 7h), Deep (or Deep And REM), Efficiency; penalties (points > 0 only) = Awakenings, Restlessness (from the arm disturbances), Latency, and Elevated Avg Heart Rate. Every input is on-device. The HR penalty's 30-day resting-HR baseline is computed on the device from each of the prior 30 nights' sleep and HR, the same way as tonight's resting HR. A night this device never recorded (before its history began, or recorded on another phone) is filled first: the read pulls that day's sleep and HR from the server — raw data only, never the server's resting HR or score — stores them, and computes the night's resting HR from them. Each missing day is pulled once per signed-in session, and later reads of the same nights are local. So the first sleep-detail read on a new device may make up to 30 days' worth of server reads (about four per day: the sleep list, the sleep detail, and the day's HR and HRV, which the recovery score also uses); in offline mode nothing is pulled, and the baseline uses the nights the device has. The HR penalty is omitted when no prior night has a resting HR (server parity; e.g. a new account). If the night itself has no resting HR, no score is produced and the header falls back to the empty "--" ring.
Everything else the server owns and the local row does not hold is left empty/null and simply doesn't render: bedtime recommendations, accounting, the HR / HRV / RR / SpO2 biometric graphs (the per-epoch charts — distinct from the single-value HRV/HR tiles above), positions, apnea / breathing and survey. A server-backfilled row (a day that predated local sync) has no stages, so the timeline + stage tiles are empty while the header + window still render.
kotlin
suspend fun getSleepDetail(date: Instant): SB_SleepDetailDay? // null when no local sleep for the day
// The session's biometric-graph timeseries (HR / HRV / RR) for the sleep-detail charts. The
// session is identified by its wake-up epoch (SB_SleepDetailDay.wakeUpTime from getSleepDetail).
suspend fun getSleepHR(sessionEndTimestamp: Long): List<SB_TimeValuePoint>
suspend fun getSleepHRV(sessionEndTimestamp: Long): List<SB_TimeValuePoint>
suspend fun getSleepRR(sessionEndTimestamp: Long): List<SB_TimeValuePoint>getSleepHR / getSleepHRV / getSleepRR return the session's per-epoch metric over its [onset, wakeUp] window, time-ordered with real-epoch timestamps (the convention the sleep biometric chart bucketing expects), with each metric's server-parity outlier handling applied (HR lower-fence only; HRV two-sided residual; RR unfiltered, rounded to 1 dp). Local-first: read from the on-device ppg_data_results; if the day predates local sync (no on-device PPG) each falls back to the server sleep detail's matching graph — hence suspend. Empty when neither source has data. A host wraps each list in a graph (points + mean average) to feed the same biometric chart the server path draws; there is no local SpO2 (that card stays hidden).
getSleepArmDisturbances returns the session's arm-restlessness severity timeline for the disturbance chart — fully local, bucketed from the on-device activity_packets motion value over [onset, wakeUp] with the server's fixed thresholds (≤250000 NONE / ≤750000 MILD / ≤1250000 MODERATE / else SEVERE), first + last forced NONE. It returns a colour-free SB_SleepDisturbanceLevel per epoch (NONE/MILD/MODERATE/SEVERE) — the SDK deliberately does not return colours, so the host owns the palette (and its theming). NONE points are included so the host can compute the level distribution; the host typically drops them from the drawn series (server parity). No server fallback — the arm series is only ever local; empty when the session has no activity packets on device. (Leg / snoring disturbance graphs are dead on the server, so only the arm series is exposed.)
kotlin
suspend fun getSleepArmDisturbances(sessionEndTimestamp: Long): List<SB_SleepDisturbancePoint>
enum class SB_SleepDisturbanceLevel { NONE, MILD, MODERATE, SEVERE }
data class SB_SleepDisturbancePoint(val timestamp: Long, val timezone: Int, val level: SB_SleepDisturbanceLevel)getSleepDetail throws only on the server-backfill path (e.g. when signed out / the fetch fails); the pure-local path never touches the network. (Pairs with the iOS local-first sleep ticket.)
5.8 Local-first recovery score
fetchDailyRecovery(date) / dailyRecoveryUpdates(date) keep their signatures and their SB_DailyRecoveryTrending return, but the score behind them is now computed on-device whenever the night is on the device (SB-1681). Unlike §5.2–5.7 this is not a new entry point — it is the same trending read with a local source, so no caller changes.
The daily recovery score ranks tonight against the user's own recent nights (server GenerateRecoveryScore):
score = round(100 · (0.4·fracHRV + 0.4·fracBPM + 0.1·sleepGoalAchieved + 0.1·sleepEfficiency))- fracHRV / fracBPM — the share of the prior 30 days' nights whose resting HRV was no higher than tonight's / whose resting BPM was no lower. Each night's resting values are derived from that night's on-device
ppg_data_resultswith the same server-parity math the sleep detail uses (CalculateRestingBPM— mean of the 5 lowest outlier-free BPM;CalculateRestingHRV— the residual-outlier-free OLS HRV-vs-time line at the last epoch); - sleepGoalAchieved —
min(1, totalSleep / goal)against the user's sleep goal (an unset goal scores full credit); - sleepEfficiency —
totalSleep / (totalSleep + excessAwake + excessLatency), where awake time up to 5% of total sleep and latency up to 20 minutes are free. Both sleep terms read the same clamped stage minutes the sleep detail reports.
The returned graph carries the ring score + stage (REST_UP <30 · GO_EASY <50 · MEDIUM <60 · READY <75 · EXCELLENT ≥75) and its message, the night's resting HR and total sleep, the vs-average trend (variationPercentage, measured against the mean of the last 30 days' locally-computed scores), and the four contributing factors in the server's order — Nocturnal HRV, Resting HR, Sleep Efficiency, Total Sleep Duration — each with its percentile and its weighted point contribution.
Missing nights are backfilled, not skipped. The score reads 61 nights: tonight and the 60 before it (each of the 30 days in the trend average ranks against its own 30 priors). Any prior night this device can't supply all of the inputs for — it was never recorded here (before the device's history began, or on another phone), or its window is here without its HR, its HRV or its stage minutes (the partial day a fresh login leaves behind) — would otherwise drop out of the ranking or the average, or shrink a denominator, moving the score without any signal. Such a night is filled first: the read pulls that day's sleep list and the longest sleep's detail, HR and HRV from the server — raw data only, never the server's resting values or score — stores them, and computes the night's resting HR and HRV from them, the same way as a band night's. Tonight itself is filled only when its window is already on the device; a day with no on-device night is not made scorable from the server. Each missing day is pulled once per signed-in session, shared with §5.7's sleep-score backfill, and later reads are local — so the first recovery read on a new device may make up to 60 days' worth of server reads (about four per day). In offline mode nothing is pulled and the score uses the nights the device has. A result computed while a night could not be filled (a failed read) is returned but not cached, so the next read tries that night again. The same read also fills a night whose HRV series is short of its HR series (fewer than half as many points: part of the night's HRV was never pulled), and once more a server night stored before the SDK kept the server's own stage totals. A server night is stored with the totals the server scores it with — asleep minutes from the detail's sleepTimeSec, the light / deep / REM split, total awake and latency from the detail's tiles — not totals summed from its stage intervals, which fall short of them.
The maths runs in the shared C library (SB_recoveryScore in mobile_edge_algorithms, reached through JNI), the same code iOS runs, checked bit for bit against the server's own recovery code.
The read falls back to the server for a day the device cannot score the server's way:
- no on-device sleep for the day, or a night with no stage minutes;
- the night has no resting BPM or HRV;
- fewer than four prior nights with sleep / resting BPM / resting HRV — the server's 5-nights-including-tonight gate. This window matters: the backend blends a population baseline to serve a real score on days 1–4, and that baseline is not on the device, so those days deliberately stay server-served rather than showing nothing.
SB_DailyRecoveryTrending.isLocallyComputed reports which source actually served the day, so a host can distinguish a genuine local score from a fallback. preferLocal = false (on both fetchDailyRecovery and dailyRecoveryUpdates) skips the on-device computation and reads the server's score — the comparison hatch behind the app's debug source toggle; the default true keeps every existing caller local-first. dailyRecoveryUpdates has no stale peek: the local computation is fast enough to be the first emission, so the stream never paints a stale server score first.
forceRemote applies to the fallback fetch only — it does not bypass the local computation, matching the rest of the offline-first family. Factor titles and stage messages are the SDK's own English strings (the server's are localized server-side), the same trade-off §5.7's sleep score makes.
5.8.1 Biometric baselines ⚠️ interface change
kotlin
suspend fun getBiometricBaselines(date: Instant): SB_BiometricBaselines
data class SB_BiometricBaselines(
val restingHR: SB_BiometricBaseline? = null, // null: no baseline (see below)
val restingHRV: SB_BiometricBaseline? = null,
val respiratoryRate: SB_BiometricBaseline? = null,
val spo2: SB_BiometricBaseline? = null,
)
data class SB_BiometricBaseline(
val baseline: Float, // whole number; respiratory rate to one decimal
val value: Float? = null, // the day's value as its dashboard tile shows it
val improvementVsBaseline: Float? = null, // value − baseline, positive = better; null without a value
)A day's resting HR, HRV, respiratory rate and SpO2 against their 30-day baselines, computed on the device the way the server's dashboard computes them:
- Baseline: the median of the metric over the 30 days before
date(the day itself is not one of them), counting only days that have a sleep and a reading. Fewer than 5 such days and that metric isnull. The per-day values are the longest sleep's resting HR / HRV (asgetHRPoints/getHRVPointscomputerestingHR/restingHRV) and the whole day's respiratory rate / SpO2 (the median of all of that day's captures, asleep or not). value: resting HR and HRV of the day's longest sleep, rounded; respiratory rate (one decimal) and SpO2 (whole number) of that sleep, or of the whole day when it has no sleep.nullwhen the day has none.improvementVsBaseline: the server'simprovement_vs_baseline—value − baselinerounded at the second decimal the server's way, signed so a positive number is an improvement (a resting HR or respiratory rate below its baseline is positive).
Each prior day's respiratory-rate and SpO2 points are first merged from the server (once per session, for every day — a day the band also synced to another phone is only partly on this one), and a day the device is otherwise missing — before this phone's history, or recorded elsewhere — is filled from the server's raw points (the sleep, and that day's HR, HRV, respiratory rate and SpO2), so the first read after a fresh install can take a while; later reads are cached until one of those 30 days changes. Under offline mode nothing is fetched and the baselines come from what the device holds. The server's own baselines are never read. Never throws.
getDashboardData puts these in its tile footers (footerCase = IMPROVEMENT_VS_BASELINE, improvementVsBaseline the value) when the metric has a baseline and the day a value. fetchDailySpO2 now also stores the day's points on the device, as the HR / HRV / RR daily reads already did, so a server day is readable by the baselines afterwards; getSpO2 itself still reads the device only.
5.9 Local-first activity detail
fetchDailyActivityDetail(date, granularity) / dailyActivityDetailUpdates(date, granularity) keep their signatures and their SB_ActivityDetail return, but a DAY view is now rebuilt on-device from the day's activity rows (SB-1683) — score, baseline comparison and all four metrics. Like §5.8 this is not a new entry point, so no caller changes.
The daily activity score is a pure function of one day (server GenerateActivityScore) — no history, no statistical aggregation, no calibration:
score = round(100 · (0.8·min(1, activeCals/caloriesGoal) + 0.2·min(1, activeHours/12)))- activeCals — the day's active calories,
max(0, Σ totalStepCalories + Σ workoutCalories − Σ workoutStepCalories)over the day's per-minute rows, as §5.6's calories read builds them — including the backend's per-minuteround(steps/10)step-calorie cap (which the server applies in its DB row scan, and skips for workout minutes). The minutes are summed signed and only the day's total is floored, as the server's score does, so a workout minute the HR model scores below resting takes calories off the day. That makes it §5.6's Active total except on such days, where it is lower: Active floors each minute, as the server's calorie graph does; - activeHours — local hours with more than 250 steps, off the same hourly buckets §5.5's steps read exposes;
- caloriesGoal —
remoteGlobals.goals.calories, with the server's 500 default substituted for an unset goal. The score and the baseline comparison are computed in the shared C library (SB_activityScore/SB_activityBaselinein mobile_edge_algorithms), the same code on both platforms, checked bit for bit against the server's own Go.
The ring's fill is not the score: the server publishes progressPercentage relative to a rolling baseline, and SB_ActivityScore.diffVsBaseline alongside it. Both are reproduced locally — the baseline is the same score recomputed for each of the prior 30 days and averaged, and is published only once 5 prior days exist, matching the server's gate (below that the server omits progressPercentage too, and a host falls back to the raw score). progressPercentage is 100 at or above the baseline, and the shortfall as a percentage below it. A prior day this device has no activity rows for — before its history began, or recorded on another phone — is filled first: the read pulls that day's steps and calories from the server (raw data only, the same reads the scored day's own backfill uses), stores them, and scores the day from them, so the average covers the same days as the server's. Each missing day is pulled at most once per signed-in session, six at a time, so the first read on a new device may make up to 30 days' worth of server reads (two per day); later reads are local. A day the server has nothing for either does not contribute, which is how the server treats a date with no stored score. In offline mode nothing is pulled and the baseline uses the days the device has. A result computed while a day could not be filled (a failed read) is returned but not cached, so the next read tries that day again.
The four metrics — Calories, Duration, Distance, Steps, in the server's order — carry their day total in avgValue and hourly timeDatapoints in the API's wall-clock-encoded-as-UTC convention. DISTANCE is emitted in the user's display unit (km, or miles for an imperial profile, rounded to two decimals), as the API sends it; every other metric is SI. name / unit / barChartTitle are left empty — those are localized server-side, and the SDK owns no strings, so a host that shows them supplies its own.
The read falls back to the server when the day has no activity rows on device even after a backfill attempt, and always for WEEK / MONTH / YEAR — those periods average the server's stored daily scores and aggregate from its rollup tables, which the device does not reproduce.
SB_ActivityDetail.isLocallyComputed reports which source actually served the day. preferLocal = false (on both entry points) reads the server's payload instead — the comparison hatch behind the app's debug source toggle; the default true keeps every existing caller local-first. As in §5.8, the DAY stream has no stale peek on the local path (the range tabs keep theirs), and forceRemote applies to the fallback fetch only.
Org custom / white-label activity scoring stays server-computed.
HR zones on a stored workout (SB-2231)
SB_HRMData.exerciseZoneList — the time-in-zone breakdown and the chart's zone lines — is always the server's, on every read path, including when the HR Zone algorithm is enabled.
The server scores the zones at ingest and stores them, and SubmitFinishedRecordingSession has no field to send zones up, so the device has no say in the stored copy. That is deliberate rather than a gap: a report's zones are a fact about when the workout happened. Recomputing them at read time against the wearer's current resting heart rate would make a stored report change every time it was opened, and change differently after a birthday.
So the algorithm affects the live recording chart, where "now" is the right anchor, and not a stored report. To move a stored report's zones, the algorithm's result has to be uploaded and stored — at which point the report shows them because the server holds them, not because the device recomputed them.
One exception, and only one: the report built on device the instant a recording stops, before the server has ingested it (§5.11). There is no server-scored list yet, and that screen has to continue the boundaries the user just spent the workout watching, so it uses the algorithm's, evaluated at the session's own start. Once the recording is ingested the timeline serves the server's copy as usual.
That means the same workout reads differently in the two places until the algorithm's result is uploaded: the just-finished report shows the device's zones, the timeline shows the server's. That is a known consequence of the device having no way to tell the server which zones it used, not a bug, and it closes when the upload lands.
The zone breakdown the SDK uploads (SB-2231)
When the HR Zone algorithm is enabled, a finished activity — not a meditation, not a spot check — has its zone breakdown computed on device and uploaded as the algorithm's stored result, before the activity itself is submitted. Nothing in the host's API changes: the SDK owns computing, queueing, uploading and retrying it, and a host neither triggers nor observes it.
Two things a host can observe, both about timing:
- A recording's submit can be held back for up to 90 seconds while its result uploads. The result has to reach the server ahead of the activity, so the submit waits on it exactly as it already waits on the recording's biometrics. During that window the recording stays in
inflightSubmissionsatPENDING_UPLOAD, which is what it does today whenever an upload is outstanding — so a host that already renders those cards needs no change. - The wait is capped. After 90 seconds the submit goes ahead without the result, and the result is uploaded on a later pass. A payload the server refuses outright (a
valueJsonthat does not match the algorithm's registered schema) is marked dead rather than retried, so a schema mismatch costs one recording's 90 seconds rather than every recording's.
A recording the user deletes before it reaches the server takes its queued result with it: the result describes an activity that is never going to exist server-side.
The uploaded payload's zone boundaries are the reserve-formula ones described in §3.1, and its per-zone durations are shares of the recording's active time — paused spans excluded, because the zone times come from HR samples and those already exclude them. The five shares therefore do not sum to 100: zone 1 opens at 50% of heart-rate reserve and any time spent below that belongs to no zone. iOS uploads the identical shape (SB-2230), which is the point — a result uploaded by one platform is read back by the other.
One further difference on the locally-built report: it carries all five zones, including ones with no time in them (displayValue "0 min", progressValue 0). The server drops empty zones. The list also drives the report chart's limit lines and y-axis, so dropping them left a gentle walk with no zone lines at all and an axis collapsed to the HR range, while the live chart for the same workout had shown five. A host that renders the breakdown as a list will now show five rows rather than only the zones reached.
Which zone a row is: SB_HRZone (SB-2355) ⚠️ interface change
The SDK identifies a heart-rate zone with an enum and no display text. What a zone is called, and its localization, is the host's job.
kotlin
enum class SB_HRZone { BASELINE, ZONE_1, ZONE_2, ZONE_3, ZONE_4, ZONE_5 }
// SB_HRZone.SCORED == listOf(ZONE_1, ZONE_2, ZONE_3, ZONE_4, ZONE_5)- Reports:
SB_HRMExerciseZone.zone: SB_HRZone?says which zone a time-in-zone row is. The below-zone-1 row isBASELINE.zoneis null only when the server sent no zone number and a zone name this SDK doesn't recognize. That row is kept so the times still add up, but it isn't any zone and shouldn't be labelled or colored as one. - Building a row:
SB_HRMExerciseZone(zone = …, hexadecimalColor = …, …). - Deprecated, kept for one release:
SB_HREffortZoneandSB_HRMExerciseZone.description. These carry the server's English names ("Warm up", "Fat Burn", …). Don't display them. Switch tozoneand your own strings. - Stored reports written by an earlier SDK keep working:
zoneis read from the stored name, so no migration is needed.
The SDK reads the zone from HRMExerciseZone.zone in data.proto (SB-2543). When the server leaves that unset (HR_ZONE_UNSPECIFIED, as servers that predate it do), the SDK falls back to the English name in the deprecated HRMExerciseZone.description. Either way the SDK maps it to SB_HRZone once, and nothing after that reads the string. iOS has the same type (SB_HRZone, .baseline / .zone1….zone5).
Below-warm-up time and the bar colours (SB-2356) ⚠️ behaviour change
Every workout detail the SDK hands out — fetchWorkoutDetail, localWorkoutDetail and activityReport, whichever source built it — has its exerciseZoneList finished for display the same way. This only affects a list that has zones in it: an empty list stays empty.
- A last row,
zone == SB_HRZone.BASELINE(named"Below warm up"before SB-2355), holds the time spent under the first zone's floor, so the card adds up to the whole workout. It is worked out fromSB_HRMData.dataPointsagainst the list's own lowest floor, using the same gap-to-previous rule the zones use. It also holds the workout time with no HR reading at all, before the first sample and after the last one (SB-2404), so the rows add up toendTimestamp - timestamp, the Session figure. That matters most for an auto-detected activity, where HR can start minutes after the activity does. ItsyAxisLimitChartValueis0because it has no floor of its own. That is also how to tell it apart from a zone: skip it when you draw chart limit lines or work out the y-axis range, or you get a line at 0 bpm. hexadecimalColoris the bar colour, not the zone's floor colour. The HR chart pins each zone's colour to that zone's floor and blends upward, so each band looks like the next zone up. The bars now use that same colour:BASELINE#979797,ZONE_1#00a7dc,ZONE_2#00ad67,ZONE_3#fd8635, andZONE_4andZONE_5both#ee3e41. A host that colours a chart gradient from this field should switch to its own floor colours (#979797/#00a7dc/#00ad67/#fd8635/#ee3e41fromZONE_1upward). Otherwise every band moves up one colour.progressValueis rescaled against the longest row, including Below warm up. On an easy walk that row is full length and the zones are short. The zone rows'displayValueand boundaries keep their scored values; only the bar length and colour change.
The zone boundaries and the five times the HR Zone algorithm uploads are unchanged.
5.9.1 Continuous stress index (SB-2229) ⚠️ interface change
The SDK calculates a continuous stress index on the device when the org has the continuous_stress_index algorithm enabled (execution_location = mobile_sdk): one point per PPG block (every 5 minutes by default), from the 10 minutes of beats ending there, uploaded by the SDK itself. The value has no unit; higher means more stress. Two new things reach the host: a dashboard tile and two day reads. Both were src/internal before this change and are now in the customer AAR.
Dashboard tile. SB_DashboardMetricType.STRESS_INDEX_DASH_METRIC is new. The server's DashboardMetricType has no stress value and GetDashboard has no stress field, so the SDK adds the tile itself, last in SB_DashboardData.metricsList, on every dashboard read: fetchDashboardData, dashboardUpdates (both emissions) and the offline getDashboardData.
kotlin
val stress = data.metricsList.firstOrNull { it.metricType == SB_DashboardMetricType.STRESS_INDEX_DASH_METRIC }
// null = the org doesn't run the stress index (hide the row); else stress.valueFloat is the day's
// latest reading, 0 for a day with no readings (show "--")valueFloatis the day's latest reading (SB_StressIndexDay.latest.value);valueis it rounded,titleis"STRESS INDEX",valueUnitis empty, and the rest is defaulted (no average, footer or baseline).- The tile is the row's gate. It is present exactly while the algorithm runs for the org (or is forced in Developer Tools) — the same gate that runs the calculator — and valued 0 for a day with no readings. ⚠️ Earlier versions left the tile out for a day with no readings.
- Source. Any day, on
fetchDashboardDataand the authoritativedashboardUpdatesemission:fetchStressIndex, falling back togetStressIndexwhen it throws or returns null (the server only has a point once the phone has uploaded it). Past days are fetched too, so a day the device has no points for — every day, right after a logout → login — still gets its tile (SB-2550). Offline mode (getDashboardData):getStressIndexonly. The stress read runs alongside the dashboard read, and its failure never fails the dashboard: the tile carries 0. - Cache. The tile is never stored in the dashboard response cache, which keeps the server's payload only; the SDK adds it after that read, on every emission. The
dashboardUpdatescache pre-paint carries the tile fromgetStressIndex(on device, no network), so it shows the device's current value rather than a stale or missing tile, and the authoritative emission then carries the server's value. A past day's assembled entry (see "One read per day") holds the tile, and is replaced when stress points land on the day.
Day reads. Both return the same SB_StressIndexDay, null for a day with no readings.
kotlin
suspend fun getStressIndex(date: Instant): SB_StressIndexDay? // on device; never a network call, never throws
suspend fun fetchStressIndex(date: Instant): SB_StressIndexDay? // the server's day (GetStressIndex); throws the gRPC error
data class SB_StressIndexDay(
val latest: Point, // newest reading, the dashboard value
val min: Double,
val max: Double,
val sleepAverage: Double?, // mean of ASLEEP points; null if none
val daytimeAverage: Double?, // mean of AWAKE points; null if none
val points: List<Point>, // oldest first; never empty
) {
data class Point(val epoch: Long /* unix ms */, val value: Double, val type: SB_HRPointType)
}points are tagged ASLEEP / AWAKE against the same day window and sleeps as getHRPoints(date), and the five values are calculated by the SDK from the non-zero points (SB-2417), whichever read produced them: the server's own stats are not used. Zeros are never readings (bioedge declining to score a window) and never appear. getStressIndex uses the HR day: midnight to midnight plus the full span of every sleep that ended on it. fetchStressIndex uses the calendar day in each point's own offset, so it leaves out last night's pre-midnight points. Every fetched point is written to the local store as UPLOADED, so it is never sent back up and a later getStressIndex of that day has it; a point already stored keeps its value. When the device has no sleep filed under the day (a past day right after a logout → login, say), fetchStressIndex fetches and stores the day's sleeps first, so its points are tagged ASLEEP / AWAKE against them rather than all AWAKE; a failed sleep fetch never fails the stress fetch (SB-2550). fetchStressIndex throws when signed out or when the call fails. Fall back to getStressIndex when it throws or returns null. Fetch an earlier day too rather than reading only getStressIndex: after a logout → login the device has no points for it until something fetches them. The dashboard tile already does this.
5.10 One daily shape for all four biometrics (SB-1738) ⚠️ breaking
All four daily biometric reads now return the same SB_BiometricDailyTrending; the per-metric SB_HRDailyTrending / SB_HRVDailyTrending / SB_RRDailyTrending / SB_SpO2DailyTrending and their four graph types are gone. The metric is identified by the call you made, not by the type. Range reads keep their per-metric types — those graphs genuinely differ.
kotlin
suspend fun fetchDailyHR(date: Instant, forceRemote: Boolean = false): SB_BiometricDailyTrending
suspend fun fetchDailyHRV(date: Instant, forceRemote: Boolean = false): SB_BiometricDailyTrending
suspend fun fetchDailyRR(date: Instant, forceRemote: Boolean = false): SB_BiometricDailyTrending
suspend fun fetchDailySpO2(date: Instant, forceRemote: Boolean = false): SB_BiometricDailyTrending
// …and the four `daily*Updates` Flow siblings, likewise.
data class SB_BiometricDailyTrending(
val graph: SB_BiometricDailyGraph? = null, // null when the day has no processed data
)
data class SB_BiometricDailyGraph(
val resting: Float = 0f, // HR: resting HR · HRV: RMSSD · RR/SpO2: nocturnal average
val average: Float = 0f, // whole-day mean, sleep included
val lowest: Float = 0f,
val highest: Float = 0f,
val baseline: Float = 0f, // 30-day median, server-computed
val points: List<SB_BiometricPoint> = emptyList(), // ascending by timestamp
val linearFit: SB_TimeValueStraightLine? = null, // recovery-rate fit; HRV-only today
)
data class SB_BiometricPoint(
val timestamp: Long, // absolute ms epoch
val value: Float,
val valueType: SB_BiometricValueType, // sleep / awake / outlier / abnormal-rhythm
)Migrating:
| was | now |
|---|---|
graph.restingBpm / .rMssd / .brpm / .spo2 | graph.resting |
graph.rawAvg / .rawLowest / .rawHighest / .rawBaseline | graph.average / .lowest / .highest / .baseline |
graph.heartRateTimeseriesPoints | graph.points |
graph.rawSleepPoints + graph.rawDatetimePoints (and the …HrvPoints pair) | graph.points, split by valueType (SLEEP / AWAKE) |
graph.tzOffset, point.timezone | removed — timestamp is an absolute ms epoch; render it in the viewer's own zone |
graph.startTimestamp | removed — derive the axis start as min(localMidnight, floorToHour(points.first())) |
graph.improvementVsBaseline | removed — compute resting - baseline, sign-flipped where lower is better (HR, RR); 0 when baseline <= 0 |
graph.improvementCorrelatesDirectlyWithChange | removed — it only ever said "higher is better", which is a property of the metric, not the response |
SB_HeartRateValueType / SB_HRVValueType | SB_BiometricValueType (HR's case list; HRV's HRV_OUTLIER maps to SLEEP_OUTLIER) |
SB_HeartRateTimeValuePoint / SB_HRVTimeValuePoint | SB_BiometricPoint |
line.lineColor (SB_LineColor) | line.rating (SB_ImprovementRating) — pick your own colours |
The daily HR response's hasHeartHealthLicense / abnormalRhythmInfoCard / aeCard / peCard / arterialHealthScore | removed — unread on the daily read; the range read (SB_HRRangeTrending) still carries its own card set |
SB_TimeValuePoint also loses timezone, so every graph that carries those points (sleep biometrics, workout, activity, meditation, spot check) now hands back (timestamp, value) only.
Range graphs lose improvementVsBaseline and improvementCorrelatesDirectlyWithChange too, spell Avg out (averageBpm / average / averageBrpm / averageSpo2, rolling7DayAverage), and SB_HRVRangeGraph.rawBaseline is dropped as a duplicate of baseline.
Two traps worth knowing about. HRV / RR / SpO2 points are tagged by array provenance, never by a raw value or ordinal: SB_BiometricValueType's case list mirrors the heart-rate proto, where AWAKE is ordinal 0, while the HRV proto numbers BASIC as 0 — an ordinal bridge would compile clean and silently relabel every HRV sleep sample as awake. And the merged array is sorted by timestamp: the server builds its sleep and awake arrays independently, so a plain concatenation yields a sleep block followed by an awake block — fine for a scatter set, wrong for HRV's linearFit overlay.
Cached responses from an older build fail to decode once, are deleted, and refetch — no migration step and no cache-version bump needed.
5.11 Local-first recording reports (SB-1953/1955/1957)
Every recording type derives its report on the phone at finalize (§3.2) and keeps it, stored against its submission row under the recording's start timestamp — the same correlator reconcileSubmissions matches server entries on. Three reads follow from that.
The detail reads fall back on their own. fetchWorkoutDetail(workoutTime) and fetchMeditationGraph(date, sessionTimestamp) return the stored local report when the server has no answer — a NOT_FOUND for a workout minutes old and not yet ingested, or any failure at all when offline. The server stays the authority whenever it has an answer, so a host needs no branch. There is no equivalent fallback inside fetchSpotCheckDetails(id), because it is addressed by a server-assigned id that does not exist until the submit lands: there is no key to fall back from. Reach for localSpotCheckDetails(startTimestamp) directly while a row's workoutId is empty.
localRecordingEntries() returns real timeline rows, not status placeholders. By the time a recording is in this list the phone has a complete report for it, so rendering a passive "Processing…" card is the app declining to show data it holds. Each entry carries a real SB_WorkoutEntry — the same shape the timeline read returns — so it renders through the host's existing row view and routes through its existing detail screens.
Four merge rules, and each one is a bug if dropped:
| rule | why |
|---|---|
| Page 1 only | these are minutes old and belong in today's group; a cursor page encodes a server-side query that must not be second-guessed |
| Dedup on the start timestamp at second granularity | reconcileSubmissions drops a row once its server entry appears, but there is a window where the entry has arrived and the submission hasn't flipped. Seconds rather than milliseconds because the spot-check server domain drops the sub-second remainder — exact-millisecond matching can never match a spot check |
| Not while searching or filtering | a synthesized row has not been through the server's query |
Group by SB_LocalRecordingEntry.dateInt | supplied from the session's own timezone offset; re-deriving the day host-side is how a just-finished recording lands under yesterday's header |
Edit and delete these rows exactly like any other — modifyWorkout handles both cases itself (SB-2217, above), so there is nothing to gate on. A submission with no stored report (a manually-logged session, or a row finalized before reports were persisted) is absent from this list and still appears in inflightSubmissions.
iOS divergence. iOS's
SB_LocalRecordingEntrycarries a fourth field,scoredNoResult, for a spot check the server accepted but scored nothing for. Android has no such state: a spot check the SDK cannot score is never submitted (SB_RecordingError.NotEnoughDatathrows out ofrecordDetailedBiometrics), so no queue row exists for it.
5.11.1 Firmware-detected activities (SB-2074)
The band's firmware can decide by itself that an activity has started — from accelerometer motion, from cadence, or from both agreeing — switch the PPG into continuous mode to capture it, and stop when it thinks the activity is over. On the next sync that arrives as a single activity bookend with a non-negative payload, and the SDK stores it.
Only for organizations with the auto_activity_detection algorithm enabled in the Algo Store (SB-2164). For any other organization the SDK drops detection bookends when they arrive, whatever the band's firmware sends, and detectedActivities stays empty. The check happens when a bookend arrives, so detections already stored stay answerable if the algorithm is later disabled. User-started recordings are unaffected.
Nothing is uploaded on its own. A detection is an offer: the SDK holds it in the durable detected_activity table and publishes it, and the user either confirms it (which submits it as a real activity) or dismisses it.
kotlin
// READY detections, oldest first. StateFlow — collect from a ViewModel.
val detectedActivities: StateFlow<List<SB_DetectedActivityInfo>>
// Confirm one under `activityName`: submits it as a real general-cardio session and retires the
// detection. False when the detection is unknown or already answered.
suspend fun confirmDetectedActivity(startTsMillis: Long, activityName: String): Boolean
// Dismiss one. Marked ignored on-device and never published again, including when its bookend
// re-syncs (which it will). Nothing is uploaded.
suspend fun dismissDetectedActivity(startTsMillis: Long): BooleanSB_DetectedActivityInfo carries startTsMillis (its identity — pass it back to either call), endTsMillis, durationMillis, the tzOffsetMinutes in force when it was ingested, an SB_DetectedActivitySource (MOTION / CADENCE / MOTION_AND_CADENCE), and createdAt (when the bookend synced, not when the activity happened). Render the activity's time from tzOffsetMinutes, not the phone's current zone, so one confirmed after travelling still reads at the wall-clock time it happened.
Everything published is answerable now — that is the whole contract. There is no status on the type and no state machine for a host to reproduce, because a detection is only published once:
- the band has synced past the activity's end, and
- the passive uploads covering its window have all landed (PPG-metrics results, raw activity packets, engine/step packets), and
- it is still today's, and
- it does not overlap a recording the user made themselves — the detection algorithm keeps running during a manual recording, so the same minutes can arrive twice, and the user's own recording wins.
A detection failing any of those is simply absent. Ones from an earlier day are retired automatically (there is nowhere left to answer them) the moment the calendar day changes, and the flow re-emits without them — a host showing the card on "today" needs no date filter of its own. Ones already answered are retired too.
Both of the first two conditions matter, and the first is not redundant: every "is it all uploaded?" count is zero for a window holding no rows, and a window the band has not sent yet holds none — so without the sync-frontier check a detection would be published the instant its bookend arrived, which is when its data is least likely to have reached the server.
That gate is what makes confirmDetectedActivity a submit-now rather than a submit-eventually, and it is why the confirmed activity is indistinguishable from one the user recorded: same upload_activity row, same upload + submit drain, same locally-built report, same inflightSubmissions / localRecordingEntries() surfaces described in §5.11. A host already rendering those needs no extra work for the tail of this flow — only the card that asks the question.
The session is stamped used_hrm=true, like every recorded activity (meditation and manually-logged activities carry no used_hrm), because there genuinely are biometrics behind the window: the band turned the PPG on for it. The per-second continuous HR it captured uploads as part of that submit, attributed to the workout — which is exactly why it is not one of the uploads the readiness gate waits on. Uploading it early to satisfy the gate would send it with no workout to attribute it to and cost the activity its HR graph.
activityName decides whether steps and distance belong on the report, so prefer a name from your activity catalogue over free text.
Detection is a device-side behaviour: bookends only arrive when the organisation has auto-detect of activities switched on — the active-mode
auto_detect_enabledsetting in the advanced sensor configuration, off unless an administrator turns it on. Where it is off, these calls are inert and the flow stays empty. A change reaches the band on the next connect after the app picks the new configuration up, so expect the first detection to follow a reconnect rather than the save.
5.12 Cached timeline first page (SB-1959)
workoutTimelineUpdates() is a stale→fresh Flow over the timeline's first page: it emits the last-known page from disk immediately — so the screen paints real rows on a cold launch instead of a skeleton, and shows something at all when offline — then the authoritative fetch. It can therefore deliver page 1 twice, so a host must assign rather than append when applying it.
Only the plain page-1 read is cached: no cursor, no search term, no explicit date, DOWN. A cursor encodes the query server-side and is ephemeral; a searched or filtered read is a query whose answer must come from the server. Both go through fetchWorkoutTimeline and are never cached.
The cached copy is delivered with its cursor stripped. A restored cursor would page the user into a window the server no longer recognises, which is worse than having none — with it empty the host simply has no cursor until the authoritative page lands a moment later, and its infinite-scroll loader is already gated on having one.
5.13 Skin temperature — local-first day + server trending
getSkinTemperature(date) is now local-first, with the same contract as getHRPoints (§5.2) but keeping its nullable, non-throwing signature. It reads the day's on-device temperature with no API round-trip when the day has points locally. Only a day with none falls back to the server: one daily-temperature fetch (the fetchDailyTemperature RPC) plus a best-effort sleep fetch so the points can be tagged ASLEEP / AWAKE. It backfills the returned points into the local store and re-reads, so a later call for that day is served entirely from the device. Backfilled rows are written as already uploaded, so the passive uploader never sends them back to the server. A band reading already stored at the same epoch is never overwritten. It returns null, rather than throwing, when the fallback fails (signed out, offline) and when offline mode is on and the device has nothing.
kotlin
suspend fun getSkinTemperature(date: Instant): SB_SkinTemperature?
suspend fun fetchDailyTemperature(date: Instant, forceRemote: Boolean = false): SB_DailyTemperatureTrending
suspend fun fetchRangeTemperature(
date: Instant,
granularity: SB_ViewGranularity, // WEEK / MONTH / YEAR — the server rejects DAY and the call throws
forceRemote: Boolean = false,
): SB_TemperatureRangeTrending
data class SB_DailyTemperatureTrending(
val points: List<SB_SkinTemperature.Point>, // ascending; epoch ms; ASLEEP for the server's SLEEPING label
val startTimestamp: Long, // local midnight of the date, ms
val endTimestamp: Long, // next local midnight, clamped to now, ms
val tzOffset: Int, // minutes
val average: Float, // 0 when there are no points
val lowest: Float,
val highest: Float,
val latest: Float,
val baseline: Float?, // 30-day whole-day baseline; null until established
val vsBaseline: Float?, // average − baseline; null when baseline is
val sleepAverage: Float?,
val awakeAverage: Float?,
)
data class SB_TemperatureRangeTrending(
val sleep: SB_TemperatureTrendingGraph, // nightly sleep-time temperature, one value per date
val daily: SB_TemperatureTrendingGraph, // whole-day average, one value per date
)
data class SB_TemperatureTrendingGraph(
val graph: SB_WMYGraph,
val average: Float,
val baseline: Float?, // null unless established (see below)
val improvementVsBaseline: Float?,
val improvementCorrelatesDirectlyWithChange: Boolean, // false for temperature: a rise is not an improvement
val changeVsPriorPeriod: Float?, // vs the previous 7 / 30 / 365 days
)All values are Celsius; the app applies °C/°F for display. The server sends a sentinel range baseline (-5) until enough dates exist. The SDK only exposes baseline when improvementVsBaseline is present and the baseline is positive, so a non-null baseline can always be drawn. fetchDailyTemperature sends the device zone's UTC offset at date, which sets the day's boundaries, and fills the local temperature store from every response, the same way the HR / HRV / RR daily reads fill theirs. Both fetch… reads throw the gRPC error when the call fails.