Skip to content

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) ​

FlowElementMeaning
pairedDeviceSB_PairedDeviceState?the single paired device's slim identity (macAddress/name/type); null when none paired
haveDeviceStateFlow<Boolean>a device is paired (derived from pairedDevice)
pairingStateSB_PairingState?where the open pairing transaction stands; null when none is open (§3.4 Pairing)
updateRequiredStateFlow<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
updateSuggestedStateFlow<Boolean>a firmware update is suggested (newer baseline exists, not mandatory). Never true for a device emulator on firmware 99.99.99
latestFirmwareVersionStateFlow<String?>the version the host would flash to; null when no device/firmware or upgrades disabled
deviceSyncingStateFlow<Boolean>a device sync is in progress
percentSyncedStateFlow<Int>connected device's sync progress 0–100 (100 = up to date); resets to 100 on disconnect
recordingStateSB_RecordingStaterecording FSM (Idle / Recording(elapsed,target) / Finalizing(phase))
canFinalizeBooleanwhether the active recording may be finished early
isRecordingPausedStateFlow<Boolean>whether the active recording is paused (drives the Pause/Resume button); false off-session
recordingHRSeriesStateFlow<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
recordingPauseSegmentsStateFlow<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)
lastSyncedTempSB_LiveMetric?latest skin-temp reading from sync as a dashboard live-metric (value/unit in the user's °C/°F units); null until first
exerciseZoneAttributesSB_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
buttonTapsStateFlow<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
connectedStateFlow<Boolean>BLE connection is up
bluetoothAvailableStateFlow<Boolean>phone BLE availability
chargingStateFlow<Boolean>device is on its charger
batteryLevelStateFlow<Int?>device battery 0–100; null until first
lastSyncStartEpoch / lastSyncEndEpochStateFlow<Long?>bulk-sync window endpoints (epoch ms); null until first sync
lastSyncdStateFlow<Long?>wall-clock epoch (ms) of the last completed sync; survives disconnect; null until first
networkStatusStateFlow<SB_NetworkStatus>phone reachability (UNREACHABLE/WIFI/CELLULAR/OTHER)
haveUnuploadedPacketsStateFlow<Boolean>synced packets buffered on disk awaiting upload
inflightSubmissionsStateFlow<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)
webAppCookieStateFlow<String?>web-dashboard auth cookie from the login response; set on sign-in, cleared on sign-out, persisted
userProfileFlowStateFlow<SB_UserProfile?>reactive signed-in profile; emits on sign-in / profile / photo / goals / globals refresh / sign-out
userAppSettingsStateFlow<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()
sessionStateFlow<SB_Session?>reactive auth-session identity, derived from the profile; null when signed out
organizationStateFlow<SB_OrganizationMembership?>reactive org membership; null when signed out
featureFlagsStateFlow<List<String>>reactive feature flags; set at login + globals refresh, cleared on sign-out
forceUserToUpdatePassword / forceUserToUpdateProfileStateFlow<Boolean>forced-on-login flags; set at login, cleared on sign-out

An absent birthday is null, not a sentinel. SB_UserProfile.birthday is SB_CalendarDate? — null when the server has no birthday for the user — and SB_UserProfile.age is Int? 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 threw IllegalFieldValueException out of age, BMR and CFF. Host code that has to produce a number should substitute SB_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 BMR now reports that. Profile scalars arrive from the server as proto3 floats, where "not set" is 0 — there is no null — so SB_UserProfile.weightKG / heightCM are 0f, never null, for a user who never entered one. A plain null check does not catch that. As of SB-2004 SB_UserProfile.BMR returns null when 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 reading weightKG / heightCM directly should apply the same > 0 test — the value being present is not the same as it being real. iOS has the matching behaviour in its currentUserBMR (SB-2002).

Where exerciseZoneAttributes comes from. Normally the server's: maxHr, rhr and zoneWeights are 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, and SB_ExerciseZoneAttributes.deviceComputed is true.

The device-computed form follows the published How Heart Rate Zones Work methodology: maxHr is always estimated from the user's age and sex — a max stored on SB_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. rhr is 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 — and zoneWeights are [0.5, 0.6, 0.7, 0.8, 0.9]. Zone n therefore opens at rhr + weight[n] × (maxHr − rhr).

If you derive your own max HR, stand it down when deviceComputed is true. 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) ​

FlowPayloadPurpose
deviceResetSB_DeviceResetResult(id, successful)device-reset outcome: the device id and whether the band confirmed the reset
analyticsEventsSB_AnalyticsEventSDK 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
latestBookendSB_LatestBookend(startTs, endTs)activity window (epoch ms) resolved by a sync from the band's activity bookends (spot-check confirm)
deviceLinkFailedSB_DeviceLinkFailurea device-link (serial-enforcement) rejection; host alerts "wrong device" / retry
firmwareProgressFloatraw firmware-flash progress percent (0–100); pairs with the suspend updateFirmware() (§3.4)
syncCompletedSB_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
biometricRecordResultSB_BiometricRecordResultspot-check submit outcome (recording id on success / error on terminal failure)
spotCheckReportSB_SpotCheckDetailsthe spot check's report, built from local data at finalize — before the submit and without waiting on it (see below)
activityReportSB_WorkoutDetaila finished activity's report, built from local data at finalize — before the submit and without waiting on it (see below)
meditationReportSB_MeditationGrapha finished meditation's report, built from local data at finalize (see below)
biometricRecordProcessedUnitspot-check data synced + submit dispatched; host resets post-biometric UI
hr / hrv / rr / snr / bbi / ppgSB_HeartRateSample / SB_HrvSample / SB_RespiratoryRateSample / SB_SnrSample / SB_BbiSample / SB_PpgSamplehigh-frequency per-sample biometric streams during a live/manual session (buffered + DROP_OLDEST)
ecgSB_EcgSampleECG waveform samples (V3 hardware)
spo2SB_Spo2Samplestandalone live SpO2 stream (declared for parity; surfaced via synced trending)
sleepStoredUnita sleep session was decoded + stored on-device
sleepUploadedUnita sleep session finished uploading; host refreshes affected UI (e.g. dashboard)
sleepDetectedSB_DetectedSleepa valid auto-detected on-device sleep session was finalized (start/end epoch ms); host prompts the post-sleep survey
deviceConnectedUnitraw BLE link came up (signal only; read identity from the facade)
deviceFullyConfiguredUnitthe device finished full configuration and is usable (rising edge of isFullyConfigured)
deviceDisconnectedStringthe device disconnected; payload = macAddress
hrSyncFinishedForActivityUnita recorded activity's HR/data finished syncing+uploading
signOutCompleteUnitdeprecated, never emitted — the SDK no longer signs out on its own; collect reauthenticationRequired instead
subscriptionLostUnitthe server rejected an authenticated call for no active device subscription; host signs the user out + explains why (see §3.2.1)
reauthenticationRequiredUnitthe 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 200 is 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:

outcomechannelmeaninghost should
the reportspotCheckReportbuilt from the data being uploadedshow it now — no wait, works offline
SB_RecordingError.NotEnoughDatathrowthe window is empty after a settled sync: nothing was captured, so no report exists and none willtell the user there wasn't enough data
SB_RecordingError.StillSyncingthrowthe window is empty because the post-stop sync never settled — the data may still be on the bandtell 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_SpotCheckReportEvent enum (.ready / .unscoreable / .deferred) on its equivalent subject, because its finalize cannot throw. The information is identical; only the channel differs. iOS's .ready also omits pdfReportURL — Android's SB_SpotCheckDetails has 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:

reportwhat the server does differentlyeffect
activityReportrecomputes 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
meditationReportrates 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_MeditationGraph carries the series, the aggregates, the survey, the trend lines and the pause segments; the score / scoreFactors / scorePenalty fields and the SB_MeditationScore / SB_MeditationScoreFactor / SB_MeditationScorePenalty / SB_MeditationProcessState types 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:

signalwhat happenedwho rejected
subscriptionLostlive session, no active subscriptionserver
reauthenticationRequiredno credential to send, or the credential was rejected past recoverythe SDK before the wire, or the server
signOutCompletedeprecated — 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_METHODS mirrors 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).

EventWhenProperties
device epoch updatedthe configure step found the band clock ≥ 5 s off the phone and rewrote itdevice_epoch — band epoch before correction, seconds · phone_epoch — phone epoch, seconds · delta_seconds — phone_epoch − device_epoch, signed integer
device erroredat most once per synced chunk containing diagnostic error packetserror_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 failedthe 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 syncedafter 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 removedthe host removed the paired band through the SDK (removeDeviceFromPairedDevices); captured before the teardownserial_number — the removed band's serial ("" if never read) · phone_epoch — time of the removal, seconds
device pairedonce 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 reportedserial_number — band serial · firmware_version — as firmwareVersion publishes it · phone_epoch — when the pairing completed, seconds
device firmware update failedan 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 successfulan 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 versionold_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 successfulthe sleep upload RPC returned OK (including when the server flagged the sleep spurious)sleep_end_epoch — sleep end, milliseconds
sleep recording upload failedthe 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 retriedreason — see below · sleep_end_epoch — sleep end, milliseconds

device sync failed reason values:

reasonMeaningPlatforms
out_of_sequencea batch's sequence number wasn't the previous one + 1 (skipped, duplicated or replayed); the band re-sends from its last ackboth
store_write_failedpersisting the batch failed, so it was NAK'd to keep it on the bandboth
store_in_memorythe SwiftData store fell back to in-memoryiOS only
unknownany other NAKreserved — Android never NAKs for another cause today

sleep recording upload failed reason values (the same on iOS):

reasonMeaning
invalidthe 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_argumentthe 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):

reasonMeaning
crc_errorthe band rejected the image's CRC
invalid_header_infothe band rejected the image header
invalid_packet_lengththe band rejected a packet's length
insufficient_bufferthe band ran out of buffer
unknown_errorthe band reported an unknown error, or sent a response the Bluetooth layer couldn't parse
status_maxthe band reported the out-of-range "max" status
app_cancelthe 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_datathe image file is too short to be a firmware image
app_missing_objectsthe phone's Bluetooth objects for the transfer were missing
app_missing_filethe image file couldn't be opened
app_missing_deviceno device to transfer to
app_existing_otathe band holds an incomplete earlier update (the SDK resets the band and retries once before reporting this)

Otherwise an SDK-level code:

reasonMeaningPlatforms
not_connectedno band connected when updateFirmware was calledboth
not_configuredthe band reported it isn't configuredboth
unknownany other error, including a cancelled calling coroutineboth

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) ​

MemberSignatureNotes
recordDetailedBiometricssuspend (duration, minDuration) -> Unitspot-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
recordActivitysuspend (activityName, minDuration) -> Unitactivity (count-up). Awaits the whole session end-to-end — returns on the successful submit (host then runs its survey), throws NoPairedDevice/BleStartFailed/TooShort/NotEnoughData
recordMeditationsuspend (duration, minDuration, sessionName?, sessionNameAlreadyExists, surveyUrl?) -> Unitmeditation (always a duration-sec countdown). Awaits end-to-end; same return/throw contract as recordActivity
awaitActiveRecordingCompletionsuspend () -> Unitawait 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
finishCurrentRecordingsuspend () -> Unitsignal stop + window-sync + schedule submit; outcome surfaces in the in-flight record*() await
cancelCurrentRecording() -> Unitabort 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() -> Unitpause 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() -> Unitresume a paused recording: record the pause window + restart the device stream. Each paused span is excluded from the session's active_workout_segments
resumeActiveRecording() -> Unitresume 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
activeRecordingval SB_PersistedRecording?crash-restore: a recording persisted across process death
activeRecordingStateval 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).

MemberSignatureNotes
beginPairing() -> Unitopen a transaction and start scanning. Calling it again restarts one already open
selectDevice(id: String) -> Unitpair with one of the bands from the current Scanning payload; id is the band's macAddress, the same identifier connect/disconnect take
endPairing() -> Unitcancel a running transaction, or dismiss a terminal one. Idempotent, safe from any state
pairingStateStateFlow<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_PairingFailureMeaning
ScanTimeoutno pair-eligible band was found within the scan window
ConnectTimeoutthe BLE link to the selected band never came up
ConnectionLostthe band disconnected after connect, before the pair completed
NotConfirmedthe band connected, but the user never pressed its button within the confirmation window
DeviceUnavailableselectDevice was called with an id that isn't in the current Scanning payload
BluetoothOffthe 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

MemberSignatureNotes
connect(id: String) -> Unitmanual reconnect of the paired device; not used for pairing
disconnect(id: String? = null) -> Unitdrop the connection (null = current device)
removeDeviceFromPairedDevices(id: String) -> Unitunpair
reset() -> Unitsend the connected band its reset command. This is a plain reset, not a factory reset; the outcome arrives on deviceReset (§3.2)
userLEDsuspend (red=…, green=…, blue=…, blink=…, seconds: Int)LED control (awaits the BLE write)
hapticMotorsuspend (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 / setFirmwareUpdateDeviceIdsuspend (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) -> Unitapply a resolved firmware-version packet to the connected device
migrateDeviceTypeAfterFlash() -> Unitcall 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) -> Unitdevice 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
syncDeviceDatasuspend (force: Boolean = false) -> …trigger a packet-count sync
airplaneModesuspend () -> Unitput the connected device into airplane mode; persists + publishes deviceAirplaneModeOn, cleared on next connect
performBackgroundTaskssuspend () -> …run queued background work (WorkManager entry)

Connected-device identity (on the facade; populated after connect, cleared on disconnect):

MemberTypeNotes
serialNumberStateFlow<String?>connected device serial, null until read
firmwareVersionStateFlow<String?>connected device firmware revision, null until read
hardwareRevisionStateFlow<String?>connected device hardware revision string, null until read
typeStateFlow<SB_BluetoothDeviceType?>resolved device model (hardware-revision aware), null when disconnected
isConnectedDeviceSensrval Booleanconnected device is a "sensr"-family device (vs "alter")
isFullyConfiguredStateFlow<Boolean>connected device has reported its hardware revision
modelNumber / manufacturerNameStateFlow<String?>device-info strings, null until read
bluetoothSoftwareRevision / algorithmsSoftwareRevision / sleepSoftwareRevisionStateFlow<String?>per-component software revisions, null until read
wornStateFlow<Boolean?>whether the device is currently worn; null until reported
deviceAirplaneModeOnStateFlow<Boolean>device put into airplane mode via airplaneMode(); hydrated from prefs, cleared on connect
isAirplaneModeActiveval Booleanconvenience snapshot of deviceAirplaneModeOn

Remote config / globals + lifecycle (also on the facade):

MemberTypeNotes
remoteGlobalsSB_RemoteGlobalsgoals/branding globals
rawDataEnabledval Booleanwhether 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_OrgMembershipglobals lifecycle auto-refresh / manual refresh returning org membership
deviceIdval StringSDK-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_UserAppSettingsforce-refresh the app-settings backing the userAppSettings flow (§3.1)

Sensor Bio Mobile SDK — iOS & Android integration reference.