Appearance
The SensorBioSDK facade
SensorBioSDK is a Kotlin object (the single entry point). It exposes observable state, one-shot event streams, recording control, device & BLE control (§3.4), and the flat server-API methods (§5).
3.1 Observable state — StateFlow (collect from a ViewModel)
| Flow | Element | Meaning |
|---|---|---|
pairedDevice | SB_PairedDeviceState? | the single paired device's slim identity (macAddress/name/type); null when none paired |
haveDevice | StateFlow<Boolean> | a device is paired (derived from pairedDevice) |
pairingState | SB_PairingState? | where the open pairing transaction stands; null when none is open (§3.4 Pairing) |
updateRequired | StateFlow<Boolean> | a firmware update is required (current firmware outside the min/max window); SDK-owned decision. Never true for a device emulator (serial EMULATR…) on firmware 99.99.99 |
updateSuggested | StateFlow<Boolean> | a firmware update is suggested (newer baseline exists, not mandatory). Never true for a device emulator on firmware 99.99.99 |
latestFirmwareVersion | StateFlow<String?> | the version the host would flash to; null when no device/firmware or upgrades disabled |
deviceSyncing | StateFlow<Boolean> | a device sync is in progress |
percentSynced | StateFlow<Int> | connected device's sync progress 0–100 (100 = up to date); resets to 100 on disconnect |
recordingState | SB_RecordingState | recording FSM (Idle / Recording(elapsed,target) / Finalizing(phase)) |
canFinalize | Boolean | whether the active recording may be finished early |
isRecordingPaused | StateFlow<Boolean> | whether the active recording is paused (drives the Pause/Resume button); false off-session |
recordingHRSeries | StateFlow<List<SB_TimeValuePoint>> | the recording's HR, complete — live samples merged with the rows synced from the band, anchored at the recording's start, paused spans excluded, ascending. Bind a chart to this rather than accumulating hr: hr is a live BLE passthrough, so a chart fed from it has a hole the width of any disconnect. Current or most recent recording; reset by the next recording's start, not by finalize |
recordingPauseSegments | StateFlow<List<SB_TimeSegment>> | the recording's completed pause windows, in recordingHRSeries' timebase. Band these on the chart — since the series back-fills, a gap that isn't listed here is missing data, not a pause. Completed windows only; a pause in progress appears on resume (isRecordingPaused covers the live state) |
lastSyncedTemp | SB_LiveMetric? | latest skin-temp reading from sync as a dashboard live-metric (value/unit in the user's °C/°F units); null until first |
exerciseZoneAttributes | SB_ExerciseZoneAttributes? | HR effort-zone config; null when unconfigured, auto-clears on logout. Normally the server's, or computed on device when your org runs the HR Zone algorithm — see below |
buttonTaps | StateFlow<Int?> | latest device button-tap count. Pairing no longer needs this — the SDK consumes it internally to detect the confirmation press (§3.4 Pairing); null until first tap |
connected | StateFlow<Boolean> | BLE connection is up |
bluetoothAvailable | StateFlow<Boolean> | phone BLE availability |
charging | StateFlow<Boolean> | device is on its charger |
batteryLevel | StateFlow<Int?> | device battery 0–100; null until first |
lastSyncStartEpoch / lastSyncEndEpoch | StateFlow<Long?> | bulk-sync window endpoints (epoch ms); null until first sync |
lastSyncd | StateFlow<Long?> | wall-clock epoch (ms) of the last completed sync; survives disconnect; null until first |
networkStatus | StateFlow<SB_NetworkStatus> | phone reachability (UNREACHABLE/WIFI/CELLULAR/OTHER) |
haveUnuploadedPackets | StateFlow<Boolean> | synced packets buffered on disk awaiting upload |
inflightSubmissions | StateFlow<List<SB_RecordingSubmissionInfo>> | finished recordings the server hasn't ingested yet (newest first); host pins them atop the timeline as Uploading…/Processing…/Couldn't-sync cards. Reconcile with reconcileSubmissions(...) after each timeline fetch. A submit the server rejects (a non-OK response code — INVALID_TIMESTAMPS / MISSING_METADATA / INVALID_METADATA) goes straight to FAILED with the reason on lastErrorMessage, never UPLOADED; a rejected spot check also emits biometricRecordResult with error set (SB-1851) |
webAppCookie | StateFlow<String?> | web-dashboard auth cookie from the login response; set on sign-in, cleared on sign-out, persisted |
userProfileFlow | StateFlow<SB_UserProfile?> | reactive signed-in profile; emits on sign-in / profile / photo / goals / globals refresh / sign-out |
userAppSettings | StateFlow<SB_UserAppSettings> | reactive app-settings (units/preferences); never null — holds the defaults until the server globals load (and again after sign-out), manual refresh via refreshUserAppSettings() |
session | StateFlow<SB_Session?> | reactive auth-session identity, derived from the profile; null when signed out |
organization | StateFlow<SB_OrganizationMembership?> | reactive org membership; null when signed out |
featureFlags | StateFlow<List<String>> | reactive feature flags; set at login + globals refresh, cleared on sign-out |
forceUserToUpdatePassword / forceUserToUpdateProfile | StateFlow<Boolean> | forced-on-login flags; set at login, cleared on sign-out |
An absent birthday is null, not a sentinel.
SB_UserProfile.birthdayisSB_CalendarDate?— null when the server has no birthday for the user — andSB_UserProfile.ageisInt?for the same reason. Neither is ever the zero calendar date. Before SB-1837 both platforms represented "no birthday" as that zero date, which no type check could distinguish from a real one: iOS computed an age around 2025 from it (a max HR of roughly -912), and Android threwIllegalFieldValueExceptionout ofage,BMRandCFF. Host code that has to produce a number should substituteSB_UserProfile.DEFAULT_AGE_YEARS, which is what the SDK's own internal compute uses and is the same on both platforms.
A body metric of zero means "unset", and
BMRnow reports that. Profile scalars arrive from the server as proto3 floats, where "not set" is0— there is no null — soSB_UserProfile.weightKG/heightCMare0f, nevernull, for a user who never entered one. A plain null check does not catch that. As of SB-2004SB_UserProfile.BMRreturnsnullwhen weight or height is zero (or non-finite), not just when it is absent; previously it returned a BMR computed from 0 kg, which fed wrong resting calories downstream. Host code readingweightKG/heightCMdirectly should apply the same> 0test — the value being present is not the same as it being real. iOS has the matching behaviour in itscurrentUserBMR(SB-2002).
Where
exerciseZoneAttributescomes from. Normally the server's:maxHr,rhrandzoneWeightsare whatever the last successful goals fetch returned. If your organization has the HR Zone algorithm enabled in the Algo Store, the SDK computes them on device instead, this flow publishes those values, andSB_ExerciseZoneAttributes.deviceComputedistrue.The device-computed form follows the published How Heart Rate Zones Work methodology:
maxHris always estimated from the user's age and sex — a max stored onSB_UserProfile(maxHr/computedMaxHr) is deliberately not consulted, because estimating is what the algorithm is, and preferring the stored value makes it reproduce the server's own zones.rhris the user's own resting heart rate — today's if last night was scored, otherwise the mean of the last 30 days, otherwise a nominal 65 bpm — andzoneWeightsare[0.5, 0.6, 0.7, 0.8, 0.9]. Zone n therefore opens atrhr + weight[n] × (maxHr − rhr).If you derive your own max HR, stand it down when
deviceComputedistrue. A host that prefers a user-entered maximum over the SDK's — reasonable when the SDK's is a population estimate — reproduces the server's zones exactly if it applies that override here, which silently undoes the algorithm.This drives the live recording zone bands. It does not retro-score stored workouts — see HR zones on a stored workout in §5.9. The shape of the value does not change, so no consumer needs updating; the numbers do. Zone boundaries become personal to the wearer and move as their resting heart rate does, which means they are not comparable between two users.
When the algorithm is enabled the SDK also uploads a per-workout zone breakdown as the algorithm's stored result, which briefly gates the recording's submit — see The zone breakdown the SDK uploads in §5.9.
3.2 Event streams — SharedFlow (one-shot)
| Flow | Payload | Purpose |
|---|---|---|
deviceReset | SB_DeviceResetResult(id, successful) | device-reset outcome: the device id and whether the band confirmed the reset |
analyticsEvents | SB_AnalyticsEvent | SDK telemetry events (name + string properties) for the host to forward to its analytics provider; the full, iOS-identical event set is in §3.2.3 |
latestBookend | SB_LatestBookend(startTs, endTs) | activity window (epoch ms) resolved by a sync from the band's activity bookends (spot-check confirm) |
deviceLinkFailed | SB_DeviceLinkFailure | a device-link (serial-enforcement) rejection; host alerts "wrong device" / retry |
firmwareProgress | Float | raw firmware-flash progress percent (0–100); pairs with the suspend updateFirmware() (§3.4) |
syncCompleted | SB_SyncResult? | a device sync drained; non-null on detailed completion, null on short-circuit. Fires once per sync, after the final batch — never between intermediate batches |
biometricRecordResult | SB_BiometricRecordResult | spot-check submit outcome (recording id on success / error on terminal failure) |
spotCheckReport | SB_SpotCheckDetails | the spot check's report, built from local data at finalize — before the submit and without waiting on it (see below) |
activityReport | SB_WorkoutDetail | a finished activity's report, built from local data at finalize — before the submit and without waiting on it (see below) |
meditationReport | SB_MeditationGraph | a finished meditation's report, built from local data at finalize (see below) |
biometricRecordProcessed | Unit | spot-check data synced + submit dispatched; host resets post-biometric UI |
hr / hrv / rr / snr / bbi / ppg | SB_HeartRateSample / SB_HrvSample / SB_RespiratoryRateSample / SB_SnrSample / SB_BbiSample / SB_PpgSample | high-frequency per-sample biometric streams during a live/manual session (buffered + DROP_OLDEST) |
ecg | SB_EcgSample | ECG waveform samples (V3 hardware) |
spo2 | SB_Spo2Sample | standalone live SpO2 stream (declared for parity; surfaced via synced trending) |
sleepStored | Unit | a sleep session was decoded + stored on-device |
sleepUploaded | Unit | a sleep session finished uploading; host refreshes affected UI (e.g. dashboard) |
sleepDetected | SB_DetectedSleep | a valid auto-detected on-device sleep session was finalized (start/end epoch ms); host prompts the post-sleep survey |
deviceConnected | Unit | raw BLE link came up (signal only; read identity from the facade) |
deviceFullyConfigured | Unit | the device finished full configuration and is usable (rising edge of isFullyConfigured) |
deviceDisconnected | String | the device disconnected; payload = macAddress |
hrSyncFinishedForActivity | Unit | a recorded activity's HR/data finished syncing+uploading |
signOutComplete | Unit | deprecated, never emitted — the SDK no longer signs out on its own; collect reauthenticationRequired instead |
subscriptionLost | Unit | the server rejected an authenticated call for no active device subscription; host signs the user out + explains why (see §3.2.1) |
reauthenticationRequired | Unit | the session is over — no usable credential, or the server rejected the one there was; host ends the session and routes to sign-in (see §3.2.2) |
3.2.1 subscriptionLost and the subscription block
When the server rejects an authenticated call because the account has no active device subscription, the SDK does two things: it emits subscriptionLost, and it enters a subscription block — it drops the BLE link and refuses to auto-connect or sync until the block lifts. The block is a data-exfil guard, not a UI state: BLE sync pulls data off the band with no server round-trip, so the gate is persisted and deliberately survives relaunch.
What a host needs to know:
- The band is inert while blocked. No auto-connect on launch, no reconnect after a drop. The paired record stays, and pairing a new band still works, so "paired but never connects" is the shape the user sees.
- It can arrive in any app state, and not only after a call you made. Background uploads and the SDK's own foreground re-verification both reach the server, so this can land mid-session, while backgrounded, or moments after launch. Act on it without needing a screen to present on: sign the user out first and explain afterwards. Gating the sign-out behind a dialog is what left iOS users signed in with a dead band and no explanation (SB-1884) — MySensr signs out immediately, states the reason on the onboarding landing, and adds a local notification when the app was not in front of the user.
- It lifts by itself when the subscription is genuinely fine. Any successful authenticated RPC clears the block and reconnects the band — the server gates its whole authenticated surface on the subscription, so a
200is proof. A block armed by a transient server condition therefore heals on the next successful call or the next foreground, with no alert and no user action. - Inconclusive is not "cleared". Offline or a transport failure leaves the block standing and re-checks next foreground, rather than freeing the band on no evidence.
So the host's job is only the sign-out plus the explanation. Do not build a local mirror of the blocked state, and do not treat one emission as permanent — the SDK owns the lifecycle and stops emitting once the server stops rejecting.
spotCheckReport — the report, before the upload
A spot check's report is not a server calculation. bioedge derives it on the phone from the recording's beat-to-beat intervals, the submit ships those numbers up as its SpotCheckData, the server persists them, and fetchSpotCheckDetails(id) hands the same values back. A host that waits for the round trip is holding the user on a spinner to retrieve numbers the device already produced.
spotCheckReport fires once per finalized spot check, at the end of finalize — before the submit, and independent of whether it ever succeeds. Every field the server would return is populated, including the HR graph (read from the same continuous_hr rows the upload sends) and the HRV baseline (read from the persisted user). There is no server-only field to wait for, so the report needs no refresh once the submit lands.
The two outcomes that produce no report instead throw out of recordDetailedBiometrics, which is where this platform already reports finalize verdicts:
| outcome | channel | meaning | host should |
|---|---|---|---|
| the report | spotCheckReport | built from the data being uploaded | show it now — no wait, works offline |
SB_RecordingError.NotEnoughData | throw | the window is empty after a settled sync: nothing was captured, so no report exists and none will | tell the user there wasn't enough data |
SB_RecordingError.StillSyncing | throw | the window is empty because the post-stop sync never settled — the data may still be on the band | tell the user the band hasn't finished handing the scan over |
Neither error submits: a dataless submit leaves an in-flight card nothing can ever reconcile away (SB-1745). All three are terminal for the scan — none is followed by another.
iOS divergence. iOS publishes the same three verdicts as one
SB_SpotCheckReportEventenum (.ready/.unscoreable/.deferred) on its equivalent subject, because its finalize cannot throw. The information is identical; only the channel differs. iOS's.readyalso omitspdfReportURL— Android'sSB_SpotCheckDetailshas no such field, so this report is complete.
activityReport / meditationReport — the same idea for the other two types
Every recording type now derives its report on the phone at finalize and keeps it, instead of the user waiting on a round trip, read-replica lag the server pads with sleeps, and a timeline refetch — for numbers the device already had. Both fire exactly once per finalized recording, on the fresh path and the restore-after-kill path alike.
There is no "not enough data" verdict on these two. An activity or a meditation is a real event with a duration, a name and a time whether or not biometrics came through: if we have data we plot it, if we don't we don't. A window that captured no heart rate simply yields a SB_WorkoutDetail with a null hrmData, and the host leaves that chart out rather than rendering an empty axis. Spot check is the exception and keeps its three-way verdict, because its entire content is its biometrics and the server genuinely declines to score it.
The reports are also persisted against their submission row, so a host that misses the emit — a relaunch, a recreated view model, the user backing out and returning — reads it back with localWorkoutDetail / localMeditationGraph (§5). fetchWorkoutDetail and fetchMeditationGraph already fall back to them automatically.
Two parity caveats, and they are the honest difference from spot check. A spot check agrees with the server by construction — the phone derives the numbers, the submit ships them, the server stores them verbatim. These two do not:
| report | what the server does differently | effect |
|---|---|---|
activityReport | recomputes calories from its own copy of the HR series and its own 30-day resting-HR baseline, and picks its calorie formula with deployment env flags the client cannot observe (CALORIE_FORMULA_VO2MAX and CALORIE_UPPER_CLAMP off unless set to true, CALORIE_MET_FALLBACK on unless set to false, so the server default is HR-only Keytel with the MET fallback and no upper clamp). The SDK implements HR-only Keytel. | the headline calorie figure can settle when the timeline entry lands |
meditationReport | rates the HR / HRV trend lines (hrLinearFit / hrvLinearFit) against baselines drawn from the whole account; the SDK's come from local sleep history (sleep-gated, five-day minimum, median, "0 means not established"). | a device with less history than the account can colour a trend line differently, or leave it unrated where the server would rate it |
The HR series on both is the band's continuous-HR channel. The band emits two independent HR signals — the per-second continuous_hr stream and the PPG algorithm's own hrResult — on different cadences. Activity and meditation graphs take the continuous stream as the series and admit an algorithm sample only where the continuous stream has nothing within 5 s, so the two are never interleaved. Continuous HR is primary because it is what the live-measures upload sends, which keeps the on-device graph and the server's graph the same graph. Earlier builds merged the two on exact timestamp equality; because their cadences differ the merge never collided and both survived, drawing two series as one (SB-2134). HRV and respiration still merge by equality — their two sources are the same ppg_metrics packet recorded twice at one epoch, so every point collides by design. The HR series is clamped to 20–220 bpm on all three report types; meditation alone had previously skipped that.
Note that this makes the graph coherent, not automatically correct: if the continuous-HR channel itself is wrong for a span, the graph shows that wrong value smoothly rather than fighting with the algorithm's.
Hosts should refresh an on-screen report in place when the server entry lands rather than re-navigating.
There is no meditation score (SB-2154).
SB_MeditationGraphcarries the series, the aggregates, the survey, the trend lines and the pause segments; thescore/scoreFactors/scorePenaltyfields and theSB_MeditationScore/SB_MeditationScoreFactor/SB_MeditationScorePenalty/SB_MeditationProcessStatetypes were removed, as was the local scoring model, because no host rendered them. Breaking: a host reading those fields no longer compiles.
3.2.2 reauthenticationRequired — the session is over
Emitted when an authenticated call cannot succeed for a credential reason that no retry will fix: either the SDK holds no usable credential, or it held one and the server rejected it with the single-flight refresh unable to replace it.
The SDK does not sign the user out — you do. It can tell that a session is dead; it cannot get a new one. Rebuilding an SDK session needs a freshly minted single-use sdk_token, which only your backend can produce (§5.1), so ending the session is your decision. Tearing down local state — the paired band included — is not the SDK's to make on your behalf. This matches iOS, which surfaces SB_AuthError.refreshTokenExpired for the same reason.
Handle it. Ignore it and your app stays on an authenticated screen where every call fails and the user has no way back. A minimal handler is signOut() + clearPrefsOnLogout(), then route to your own sign-in; see ExampleApp's AppRoot.
It is a one-shot per episode: a dead session 401s every in-flight call at once, and they collapse into a single emission. The next call that gets a response re-arms it.
Distinct from its neighbours, and the distinction is the point:
| signal | what happened | who rejected |
|---|---|---|
subscriptionLost | live session, no active subscription | server |
reauthenticationRequired | no credential to send, or the credential was rejected past recovery | the SDK before the wire, or the server |
signOutComplete | deprecated — fired when the SDK signed the user out itself; it no longer does | — |
The SDK now refuses to dispatch such a call rather than sending it with no auth header. The server's authentication gatekeeper rejects a request carrying neither auth nor access_token every time, the persistent upload queue retries it indefinitely, and none of it is visible to the user: in SB-2105 that meant on the order of 78,000 rejected uploads per affected device while the app rendered a normal dashboard for three days.
What a host can rely on:
- Emitted at most once per episode, re-arming after the next authenticated call that succeeds — a draining upload queue produces one emission, not one per job.
- The blocked call closes locally with
UNAUTHENTICATED. - Queued uploads stop retrying. Nothing carrying user data is discarded: the packet, biometrics, temperature, engine-result and sleep paths mark rows uploaded only on success, so the rows stay put and re-queue once the user has signed back in.
- It can arrive in any app state, background included.
- Only emitted when a session is actually persisted — session on disk plus no readable credential is the state this reports, and nothing else is. An app that is merely signed out has no session to re-authenticate, so it never sees this.
- The pre-auth calls are never affected, and not because of the rule above: they are exempt by name.
SB_APIClient.UNAUTHENTICATED_METHODSmirrors the server's own exemption list (api/mobile/mobile.go) and carries all thirteen RPCs the server serves without a credential — login, account creation, activation-code and e-mail validation, and the whole forgotten-password family. Membership there is what decides an RPC's auth contract, on this platform and on iOS (SB_APIClient.unauthenticatedMethods, SB-2135).
3.2.3 Analytics events — analyticsEvents / SB_AnalyticsEvent
analyticsEvents: SharedFlow<SB_AnalyticsEvent> publishes SDK telemetry for you to forward to your own analytics provider. SB_AnalyticsEvent is data class SB_AnalyticsEvent(val name: String, val properties: Map<String, String> = emptyMap()). The SDK sends nothing to any analytics service itself; if nobody collects the flow, the events are dropped (buffer of 8, no replay).
The set is identical on iOS and Android (SB-2440) — same names, property keys and value formats. Every property value is a String; numbers are formatted locale-independently (. decimal separator, no grouping). Add your own context (device metadata, app state, user) before forwarding.
Every event carries phone_epoch — the phone's wall-clock time, epoch seconds. The SDK stamps it with the emission time unless the event sets its own (listed in its row below: the removal, pairing and failure times, and the phone clock device epoch updated compared the band against).
| Event | When | Properties |
|---|---|---|
device epoch updated | the configure step found the band clock ≥ 5 s off the phone and rewrote it | device_epoch — band epoch before correction, seconds · phone_epoch — phone epoch, seconds · delta_seconds — phone_epoch − device_epoch, signed integer |
device errored | at most once per synced chunk containing diagnostic error packets | error_type — space-separated tokens, in this order, no leading/trailing space: ble watchdog ppg imu_overflow algorithm_nan_in_accel_buffer · packet_bytes — each error packet as uppercase space-separated hex bytes, packets joined by ", " (e.g. 87 0B 07 0C 01, 87 0B 07 07 02) · epoch — band timestamp of the latest packet in the batch, seconds |
device sync failed | the SDK NAKs a sync batch (intermediate or final) | reason — always present, see below · intermediate — true / false · number_of_packets_recorded — packets the band reported for this sync · number_of_packets_synced — packets received so far · expected_sequence_number, received_wrong_sequence_number — only when reason = out_of_sequence |
device synced | after a successful sync drain, throttled: only if more than 5 min have passed since the last emission's anchor. Counters accumulate between emissions and reset after each one; the anchor only advances on a non-intermediate sync. In-memory (not persisted) | packet_count — packets synced since the last emission · number_of_syncs — syncs since the last emission · sync_duration — accumulated seconds, exactly 2 decimals (e.g. 12.34) |
device removed | the host removed the paired band through the SDK (removeDeviceFromPairedDevices); captured before the teardown | serial_number — the removed band's serial ("" if never read) · phone_epoch — time of the removal, seconds |
device paired | once per new pairing through the SDK's pairing flow (pairingState → Paired) — never on a reconnect of an already-paired band. Sent once the band's serial and firmware version are both known (normally at once, since pairing configures the band; otherwise on the first configuration after it). In-memory: a pair whose report is still waiting when the app is killed is not reported | serial_number — band serial · firmware_version — as firmwareVersion publishes it · phone_epoch — when the pairing completed, seconds |
device firmware update failed | an updateFirmware call failed — once per call, just before it throws SB_FirmwareUpdateError (which is unchanged) | reason — see below · current_version — band firmware when the update started ("" if unknown) · attempted_version — the version being installed: known when the bytes are the image the SDK's own getFirmware returned (internal builds), else "" · phone_epoch — time of the failure, seconds |
device firmware update successful | an updateFirmware call succeeded — once per call. Sent after the band reboots and reconnects, so new_version is what the band itself reports; if it isn't back within 5 minutes, sent then with the installed version | old_version — band firmware before the update · new_version — the version the band reports after its reboot, else the installed version ("" if the SDK didn't know it) |
sleep recording uploaded to server successful | the sleep upload RPC returned OK (including when the server flagged the sleep spurious) | sleep_end_epoch — sleep end, milliseconds |
sleep recording upload failed | the server permanently rejected a sleep upload, so the SDK dropped the sleep and will not retry it — once per sleep. Transient failures (no internet, timeouts, server errors) send nothing: the sleep stays queued and is retried | reason — see below · sleep_end_epoch — sleep end, milliseconds |
device sync failed reason values:
reason | Meaning | Platforms |
|---|---|---|
out_of_sequence | a batch's sequence number wasn't the previous one + 1 (skipped, duplicated or replayed); the band re-sends from its last ack | both |
store_write_failed | persisting the batch failed, so it was NAK'd to keep it on the band | both |
store_in_memory | the SwiftData store fell back to in-memory | iOS only |
unknown | any other NAK | reserved — Android never NAKs for another cause today |
sleep recording upload failed reason values (the same on iOS):
reason | Meaning |
|---|---|
invalid | the upload response's status was STATUS_CODE_INVALID |
bad_sleep_request | … STATUS_CODE_BAD_SLEEP_REQUEST |
sleep_stages_timeseries_data_issue | … STATUS_CODE_SLEEP_STAGES_TIMESERIES_DATA_ISSUE |
unrecognized_status | … a status code the SDK doesn't recognise |
invalid_argument | the RPC itself failed with gRPC INVALID_ARGUMENT — the server validated the payload and refused it |
device firmware update failed reason values. When the band / Bluetooth layer reported an OTA status, reason is that status's name, lowercased (the same list on iOS):
reason | Meaning |
|---|---|
crc_error | the band rejected the image's CRC |
invalid_header_info | the band rejected the image header |
invalid_packet_length | the band rejected a packet's length |
insufficient_buffer | the band ran out of buffer |
unknown_error | the band reported an unknown error, or sent a response the Bluetooth layer couldn't parse |
status_max | the band reported the out-of-range "max" status |
app_cancel | the transfer was cancelled — on Android this is also what a link lost mid-flash and the transfer's 5 s no-response watchdog report |
app_not_enough_data | the image file is too short to be a firmware image |
app_missing_objects | the phone's Bluetooth objects for the transfer were missing |
app_missing_file | the image file couldn't be opened |
app_missing_device | no device to transfer to |
app_existing_ota | the band holds an incomplete earlier update (the SDK resets the band and retries once before reporting this) |
Otherwise an SDK-level code:
reason | Meaning | Platforms |
|---|---|---|
not_connected | no band connected when updateFirmware was called | both |
not_configured | the band reported it isn't configured | both |
unknown | any other error, including a cancelled calling coroutine | both |
Not emitted (removed in SB-2440): recording started / recording ended (the host knows when it starts and ends a recording — fire your own), user consent given (fire your own when the user accepts), device in foreground connected, and the old name device sync failed due to missing sequence number (now device sync failed).
Related domain signals are separate flows, not analytics events: syncCompleted, hrSyncFinishedForActivity, sleepUploaded, deviceReset and latestBookend (§3.2 table).
3.3 Recording control (suspend, on the facade)
| Member | Signature | Notes |
|---|---|---|
recordDetailedBiometrics | suspend (duration, minDuration) -> Unit | spot-check, awaits the whole session end-to-end; auto-finalizes on the countdown or via finishCurrentRecording(). The report arrives earlier, on spotCheckReport (§3.2). Throws NoPairedDevice/BleStartFailed/TooShort/BleStopFailed/NotEnoughData/StillSyncing; cancel the coroutine to abort |
recordActivity | suspend (activityName, minDuration) -> Unit | activity (count-up). Awaits the whole session end-to-end — returns on the successful submit (host then runs its survey), throws NoPairedDevice/BleStartFailed/TooShort/NotEnoughData |
recordMeditation | suspend (duration, minDuration, sessionName?, sessionNameAlreadyExists, surveyUrl?) -> Unit | meditation (always a duration-sec countdown). Awaits end-to-end; same return/throw contract as recordActivity |
awaitActiveRecordingCompletion | suspend () -> Unit | await a recording the host did not start via record*() (a process-kill resume) so it can run the survey + surface errors identically; no-op when idle |
finishCurrentRecording | suspend () -> Unit | signal stop + window-sync + schedule submit; outcome surfaces in the in-flight record*() await |
cancelCurrentRecording | () -> Unit | abort without submit — the session is discarded outright: nothing is stored, no report is published, nothing is queued for upload, and the persisted envelope is cleared so a later launch can't resurrect it. The band is stopped (or the stop armed for the next configure) and recordingState goes straight from Recording to Idle with no Finalizing phase; an in-flight record*()/awaitActiveRecordingCompletion() await resolves as a cancellation |
pauseRecording | () -> Unit | pause the running activity/meditation: freeze the elapsed clock + stop the device PPG stream (no biometrics accrue). No-op if not recording / already paused / spot-check |
resumeRecording | () -> Unit | resume a paused recording: record the pause window + restart the device stream. Each paused span is excluded from the session's active_workout_segments |
resumeActiveRecording | () -> Unit | resume a recording persisted across a process kill (crash-restore / app launch). Since SB-1745 this is restore, not blindly resume: if the persisted envelope carries a stop intent (the user had already tapped End before the process died) it re-enters finalize at the persisted stop instant instead of resuming the count-up; if the envelope is older than 24h with no stop intent it is discarded rather than resurrected. Only a genuinely still-running session resumes live |
activeRecording | val SB_PersistedRecording? | crash-restore: a recording persisted across process death |
activeRecordingState | val SB_ActiveRecordingInfo? | flat snapshot of the live activity/meditation recording the engine is driving (for the live screen) |
Tick cadence vs. publish cadence (SB-1949). Activity/meditation run a 200ms timer loop and spot check its own 250ms one, but on both paths recordingState is published only when the whole second changes — at most once per second — and the elapsedMs it carries is floored to that whole second. Hosts driving a MM:SS display or a targetMs - elapsedMs countdown see no difference; hosts that were relying on sub-second elapsedMs resolution will now see whole seconds. Both loops are retained at their original cadence because each is also the poll interval for its countdown expiry, so auto-stop precision is unchanged. (Publishing raw milliseconds made every emission a distinct value that no StateFlow collector could dedupe: four to five recompositions a second, per collector, for the length of a recording. Measured on a Pixel 10 Pro over matched 20-minute screen-on activity recordings, coalescing plus the host-side chart and animation fixes was worth ~13% of app CPU and ~12% of battery drain.)
Countdowns end on their target (SB-2243). For a countdown (targetMs != null) the published elapsedMs never exceeds targetMs, and a session that auto-stops on its countdown is stored ending at the instant it reached the target, so a 30-minute meditation records exactly 30:00 no matter how late the stop tick ran. The SDK holds a partial wakelock while a countdown runs (released on pause and at the end, and bounded by a timeout) so the auto-stop and its end cue fire on time with the screen off. The WAKE_LOCK permission merges in from the SDK manifest; the host doesn't declare it.
3.4 Device & BLE control (on the facade)
Pairing, connection, device commands, and sync are driven through the facade. (Device-telemetry observation is the §3.1 connected / charging / batteryLevel / bluetoothAvailable / buttonTaps flows + the §3.2 deviceConnected / deviceFullyConfigured / deviceDisconnected events, plus the connected-device identity below.)
Pairing — one SDK-owned transaction
Pairing is one transaction owned by the SDK, not a sequence of host calls. Three methods open, advance, and close it; everything in between is reported on the pairingState flow (§3.1).
| Member | Signature | Notes |
|---|---|---|
beginPairing | () -> Unit | open a transaction and start scanning. Calling it again restarts one already open |
selectDevice | (id: String) -> Unit | pair with one of the bands from the current Scanning payload; id is the band's macAddress, the same identifier connect/disconnect take |
endPairing | () -> Unit | cancel a running transaction, or dismiss a terminal one. Idempotent, safe from any state |
pairingState | StateFlow<SB_PairingState?> | the transaction's state; null when none is open |
kotlin
sealed interface SB_PairingState {
data class Scanning(val devices: List<SB_DiscoveredDevice>) : SB_PairingState // cumulative, de-duplicated
data class Connecting(val device: SB_DiscoveredDevice) : SB_PairingState
data class AwaitingConfirmation(val device: SB_DiscoveredDevice) : SB_PairingState // band blinking; press its button
data class Paired(val device: SB_PairedDeviceState) : SB_PairingState // terminal
data class Failed(val reason: SB_PairingFailure) : SB_PairingState // terminal
}
enum class SB_PairingFailure {
ScanTimeout, ConnectTimeout, ConnectionLost, NotConfirmed, DeviceUnavailable, BluetoothOff
}SB_PairingFailure | Meaning |
|---|---|
ScanTimeout | no pair-eligible band was found within the scan window |
ConnectTimeout | the BLE link to the selected band never came up |
ConnectionLost | the band disconnected after connect, before the pair completed |
NotConfirmed | the band connected, but the user never pressed its button within the confirmation window |
DeviceUnavailable | selectDevice was called with an id that isn't in the current Scanning payload |
BluetoothOff | the phone's Bluetooth adapter is off, so no scan was started. Reported immediately from beginPairing(), not after the scan window |
Render the state; make three calls:
kotlin
lifecycleScope.launch {
SensorBioSDK.pairingState.collect { state ->
when (state) {
is SB_PairingState.Scanning -> showList(state.devices) // tap → selectDevice(device.macAddress)
is SB_PairingState.Connecting -> showConnecting()
is SB_PairingState.AwaitingConfirmation -> showPressTheButton()
is SB_PairingState.Paired -> showAllSet(state.device) // dismiss → endPairing()
is SB_PairingState.Failed -> showCantReachBand(state.reason) // dismiss → endPairing()
null -> showStartScreen()
}
}
}
SensorBioSDK.beginPairing()What the SDK does inside the transaction, so the host doesn't: scanning and discovery de-duplication; re-issuing the scan once Bluetooth becomes available (a scan issued while the adapter is still coming up is refused, which is what happens on a first-run pair with the permission prompt still on screen); connecting; the on-band confirmation choreography (blink + buzz, listening for the button, acknowledging the press, and refusing a late press once the window closes); persistence; server registration including the device-type wire mapping; configuring the band over the link that is already up; suppressing BLE auto-reconnect so a previously-paired band can't steal the link mid-pair; and every timeout — scan, connect, confirm, and a configure backstop.
Handling Bluetooth off. beginPairing() checks the real adapter state before it scans. With the adapter off it starts no scan and publishes Failed(BluetoothOff) straight away, instead of scanning an empty list for the whole scan window and then reporting ScanTimeout. The SDK never shows a dialog or turns Bluetooth on itself; the host asks the user, then opens a fresh transaction:
kotlin
private val enableBluetooth =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) SensorBioSDK.beginPairing()
}
// in the pairingState collector:
is SB_PairingState.Failed -> if (state.reason == SB_PairingFailure.BluetoothOff) {
SensorBioSDK.endPairing()
enableBluetooth.launch(Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)) // needs BLUETOOTH_CONNECT on API 31+
} else {
showCantReachBand(state.reason)
}Close the failed transaction with endPairing() before retrying, as above. pairingState is a StateFlow, so a beginPairing() over a still-published Failed(BluetoothOff) while Bluetooth is still off publishes an equal value, and a collector never sees it: the retry looks like it did nothing.
The host keeps what is genuinely host-side: the runtime Bluetooth permissions (§1.1 — the SDK scans, it never asks for the grant), which screen to show, analytics, and any cosmetic hold or countdown.
Nothing is persisted, registered, or reported to the server until the user confirms on the band. A transaction that ends any way other than
Paired— cancelled, timed out, dropped — leaves no trace: no persisted device, no BLE registration, no server-side link event. There is nothing for the host to undo, which is why no un-pair or reset call is needed on the failure paths.
Paired means the band is ready: persisted, registered, reported, and configured — no reconnect required. A band that pairs but fails to configure (firmware too old to answer some setup commands) still reports Paired, because the pair is real and configuration retries on the next reconnect; unpairing it would put the forced-firmware-update flow that fixes it out of reach. The two terminal states persist until endPairing(), so a host showing an "all set" or "can't reach the band" screen keeps the transaction open until that screen is dismissed — and the SDK keeps the forced-firmware prompt (updateRequired) suppressed for that whole window. A required update is raised on the reconnect after pairing, so a host that wants it raised promptly drops the link (disconnect()) when it dismisses the all-set screen.
Connection, unpair & device commands
| Member | Signature | Notes |
|---|---|---|
connect | (id: String) -> Unit | manual reconnect of the paired device; not used for pairing |
disconnect | (id: String? = null) -> Unit | drop the connection (null = current device) |
removeDeviceFromPairedDevices | (id: String) -> Unit | unpair |
reset | () -> Unit | send the connected band its reset command. This is a plain reset, not a factory reset; the outcome arrives on deviceReset (§3.2) |
userLED | suspend (red=…, green=…, blue=…, blink=…, seconds: Int) | LED control (awaits the BLE write) |
hapticMotor | suspend (pulse: Boolean = false, intensity: Int, seconds: Int) | run the haptic motor (awaits the BLE write). pulse = pulse vs. solid (haptic analogue of blink); intensity is 0..100% |
updateFirmware / setFirmwareUpdateDeviceId | suspend (url, delay?, size?) or suspend (data: ByteArray, delay?, size?) (throws SB_FirmwareUpdateError(canRetry)) / (deviceId: String?) | firmware flash — url = a local file, or pass data = the bytes from getFirmware (SDK temp-files them internally); progress on the firmwareProgress event (§3.2). Each call reports device firmware update failed or device firmware update successful on analyticsEvents (§3.2.3). setFirmwareUpdateDeviceId is the session-guard seam |
updateConnectedDeviceFirmware | (packet: SB_FirmwareVersionPacket) -> Unit | apply a resolved firmware-version packet to the connected device |
migrateDeviceTypeAfterFlash | () -> Unit | call after a flash completes: if the device was an Alter/AlterV2 migrated onto Sensr firmware, rewrite its stored type to the Sensr equivalent + re-register so the forced-update gate stops re-firing on reconnect. No-op for a same-type flash |
setAskForDeviceResponse | (enable: Boolean) -> Unit | device button-tap prompting. Not needed for pairing — beginPairing runs the LED/haptic confirmation and the button listening itself; reach for this (and userLED / hapticMotor) only for your own device interactions outside a pair |
syncDeviceData | suspend (force: Boolean = false) -> … | trigger a packet-count sync |
airplaneMode | suspend () -> Unit | put the connected device into airplane mode; persists + publishes deviceAirplaneModeOn, cleared on next connect |
performBackgroundTasks | suspend () -> … | run queued background work (WorkManager entry) |
Connected-device identity (on the facade; populated after connect, cleared on disconnect):
| Member | Type | Notes |
|---|---|---|
serialNumber | StateFlow<String?> | connected device serial, null until read |
firmwareVersion | StateFlow<String?> | connected device firmware revision, null until read |
hardwareRevision | StateFlow<String?> | connected device hardware revision string, null until read |
type | StateFlow<SB_BluetoothDeviceType?> | resolved device model (hardware-revision aware), null when disconnected |
isConnectedDeviceSensr | val Boolean | connected device is a "sensr"-family device (vs "alter") |
isFullyConfigured | StateFlow<Boolean> | connected device has reported its hardware revision |
modelNumber / manufacturerName | StateFlow<String?> | device-info strings, null until read |
bluetoothSoftwareRevision / algorithmsSoftwareRevision / sleepSoftwareRevision | StateFlow<String?> | per-component software revisions, null until read |
worn | StateFlow<Boolean?> | whether the device is currently worn; null until reported |
deviceAirplaneModeOn | StateFlow<Boolean> | device put into airplane mode via airplaneMode(); hydrated from prefs, cleared on connect |
isAirplaneModeActive | val Boolean | convenience snapshot of deviceAirplaneModeOn |
Remote config / globals + lifecycle (also on the facade):
| Member | Type | Notes |
|---|---|---|
remoteGlobals | SB_RemoteGlobals | goals/branding globals |
rawDataEnabled | val Boolean | whether raw sensor logging is active (sensor-config raw channel or legacy rawSensorDataLogging); raw logging fills device storage faster, so the host shortens its "haven't synced" reminder (armed off §3.2 syncCompleted) when true |
attachRemoteGlobals(owner) / refreshGlobalState() | — / suspend (): SB_OrgMembership | globals lifecycle auto-refresh / manual refresh returning org membership |
deviceId | val String | SDK-owned stable per-install id (generated + persisted in sdk_prefs; survives clearPrefsOnLogout, changes only on reinstall / data clear); read-only — the host reads it only to tag its own analytics with the same id |
clearLocalRecordingState() | — | recording-state lifecycle |
refreshUserAppSettings() | suspend (): SB_UserAppSettings | force-refresh the app-settings backing the userAppSettings flow (§3.1) |