Skip to content

The SB_SDK Facade ​

All customer-facing functionality is exposed off the sensorBio singleton. The class drops the canonical-product prefix from history because it is the SDK — there is one and only one — but adopts SB_ in the source rename for binary-distribution hygiene.

3.1 Singleton & class shape ​

swift
public class SB_SDK: @unchecked Sendable {
    public static let shared = SB_SDK()
}

public let sensorBio = SB_SDK.shared

3.2 Observable state (Combine @Published) ​

Subscribe via sensorBio.$propertyName or read directly. All are read-only from the app's perspective.

Session & user

PropertyTypeDescription
sessionSB_Session?Signed-in user session (token + profile snapshot)
userProfileSB_UserProfile?Full user identity + body metrics
organizationSB_OrgMembership?User's org / group membership
featureFlags[String]Server-driven feature flags

An absent birthday is null, not a sentinel. SB_UserProfile.birthday is DateComponents? — nil 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 SDKConstants.DefaultUserMetrics.Age, which is what the SDK's own internal compute uses and is the same on both platforms.

Pairing, connection & reachability

PropertyTypeDescription
pairedDeviceSB_PairedDeviceState?Pre-connection device snapshot (name, type, macAddress)
haveDeviceBoolA device is paired
pairingStateSB_PairingState?Where the open pairing transaction stands; nil when none is open (§6.1)
connectedBoolBLE connection is up
isFullyConfiguredBoolDevice finished configuration and is usable
bluetoothAvailableBoolBLE is available on the phone
networkStatusSB_NetworkStatusReachability — wifi / cellular / unreachable

Sync

PropertyTypeDescription
deviceSyncingBoolActive sync in progress
percentSyncedIntSync progress (0–100)
lastSyncdDateWall-clock of last successful sync
latestDeviceEpochInMillisInt64Epoch (ms) of the newest sensor packet synced from the device; advanced only from real packet timestamps (never wall-clock). Monotonic within a launch; resets to 0 on relaunch. Recording finalize reads it too: a value past a recording's stop time is one of the two ways finalize concludes the band has handed over that recording's data (the other is a matching activity bookend)

Device telemetry

PropertyTypeDescription
batteryLevelInt?0–100
chargingBool?Device is on its charger
wornBool?Device is being worn
buttonTapsInt?Last button-tap event. Pairing no longer needs this — the SDK consumes it internally to detect the confirmation press (§6.1)

Device identity & firmware

PropertyTypeDescription
typeSB_BluetoothDeviceType?Device model
serialNumberString?
modelNumberString?
manufacturerNameString?
hardwareRevisionString?
firmwareVersionString?Device firmware as "major.minor.build"
latestFirmwareVersionString?Recommended firmware version
bluetoothSoftwareRevisionString?
algorithmsSoftwareRevisionString?
sleepSoftwareRevisionString?

Update prompts & misc

The following @Published properties are also observable:

forceUserToUpdatePassword, forceUserToUpdateProfile, exerciseZoneAttributes, updateSuggested, updateRequired, deviceAirplaneModeOn, webAppCookie, lastSyncedTemp.

updateSuggested and updateRequired are never raised for a device emulator (serial number starting EMULATR) that reports firmware 99.99.99: that version is always treated as current, and latestFirmwareVersion stays nil.

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, and this property publishes those values.

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] x (maxHr - rhr).

This drives the live recording HR-zone bands. It does not retro-score stored workouts — see HR zones on a stored workout in §4 for why. 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. Nothing is uploaded — this decides the boundaries only.

3.3 Computed read-only properties ​

swift
public var isAuthenticated: Bool         // session != nil
public var hasStoredAuthToken: Bool      // keychain holds an auth token
public var isDeviceConnected: Bool       // paired + connection up
public var sdkVersion: String            // underlying BLE SDK version string
public var isAirplaneModeActive: Bool    // device is in airplane mode
public var isRawLoggingEnabled: Bool     // white-label raw-sensor-logging on (offline mode included)
public var haveUnuploadedPackets: AnyPublisher<Bool, Never>
public var developmentLogStats: (storeURL: URL, enginePacketCount: Int)

3.4 Event streams (Combine subjects) ​

Subscribe via sensorBio.<subject>.sink { … }.

swift
// Auth & connection lifecycle
// (Pairing is not here — it is one transaction reported on the
//  `$pairingState` @Published property. See §6.1.)
public let signOutComplete:             PassthroughSubject<Void, Never>
public let deviceDisconnected:          PassthroughSubject<String, Never>   // payload: the device's BLE `id` (same value as `pairedDevice.macAddress`)
public let deviceConnected:             PassthroughSubject<Void, Never>     // low-level BLE connect
public let deviceFullyConfigured:       PassthroughSubject<Void, Never>     // post-configure
public let deviceLinkFailed:            PassthroughSubject<SB_DeviceLinkFailure, Never>  // server rejected the device-link (serial-enforced subscription)
public let subscriptionLost:            PassthroughSubject<Void, Never>     // server rejected an authenticated RPC for no active subscription — host should alert + force logout (see §3.4.1)
public let reauthenticationRequired:    PassthroughSubject<Void, Never>     // the SDK has no stored credential for an authenticated RPC — host should route to sign-in (see §3.4.2)

// Sync
public let syncCompleted:               PassthroughSubject<SB_SyncResult?, Never>  // a sync drained (see §3.4.3)
public let hrSyncFinishedForActivity:   PassthroughSubject<Void, Never>     // the stopped recording's data has synced (see §3.4.3)

// Telemetry for your analytics provider
public let analyticsEvents:             PassthroughSubject<SB_AnalyticsEvent, Never>  // see §3.4.4

// Streaming biometrics — timestamp + value
public let hr:    PassthroughSubject<(Int, Int),     Never>                 // bpm
public let hrv:   PassthroughSubject<(Int, Int),     Never>                 // ms
public let rr:    PassthroughSubject<(Int, Int),     Never>                 // breaths/min
public let spo2:  PassthroughSubject<(Int, Float),   Never>                 // %
public let snr:   PassthroughSubject<(Int, Float),   Never>                 // dB
public let bbi:   PassthroughSubject<(Int64, Int),   Never>                 // ms
public let ppg:   PassthroughSubject<(Int64, Float), Never>                 // raw
public let ecg:   PassthroughSubject<(Int64, Float), Never>                 // raw
public let firmwareProgress:            PassthroughSubject<Float, Never>

// Biometric-record & sleep-store results
public let biometricRecordResult:       PassthroughSubject<SB_BiometricRecordResult, Never>
public let spotCheckReport:             PassthroughSubject<SB_SpotCheckReportEvent, Never>   // local report, at finalize
public let activityReport:              PassthroughSubject<SB_WorkoutDetail, Never>          // local report, at finalize
public let meditationReport:            PassthroughSubject<SB_MeditationGraph, Never>        // local report, at finalize
public let biometricRecordProcessed:    PassthroughSubject<Void, Never>
public let sleepStored:                 PassthroughSubject<Void, Never>              // once per newly decoded, non-overlapping sleep (before upload)
public let sleepDetected:               PassthroughSubject<SB_DetectedSleep, Never>  // once per valid, non-overlapping on-device sleep stored (start/end epoch ms)
public let sleepUploaded:               PassthroughSubject<Void, Never>              // a stored sleep reached the server (pairs with sleepStored)

sleepStored and sleepDetected each fire exactly once per sleep (SB-2440). Before, a non-overlapping sleep sent both twice: sleepStored from two sites in the decode pass, and sleepDetected once at decode (for every session, overlapping or not) and again when the session was stored. A sleep that overlaps one already on record sends neither.

3.4.1 subscriptionLost and the subscription block ​

When the server rejects an authenticated RPC because the user has no active device subscription, the SDK does two things: it fires subscriptionLost, and it enters a subscription block — it disconnects the band 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 about it:

  • The band is inert while blocked. No auto-connect on launch, no reconnect after a drop. pairedDevice stays populated and pairing a new band still works, so "paired but never connects" is the shape the user sees.
  • The signal 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 subscriptionLost can land mid-session, while backgrounded, or moments after a launch. A host must therefore be able to act on it without a screen to present on: sign the user out first and explain afterwards, rather than gating the sign-out behind a modal that a backgrounded app cannot show. 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 that was 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 alert + forced sign-out on subscriptionLost. Do not build a local mirror of the blocked state, and do not treat one subscriptionLost as permanent — the SDK owns the lifecycle and will stop re-firing once the server stops rejecting.

biometricRecordResult emits once for every accepted spot check, and the host has three outcomes to tell apart:

iderrormeaninghost should
non-nilnilscored — a report existsshow the report
nilnon-nilsubmit failedretryable; the SDK keeps re-driving it
nilnilaccepted, but the server scored no reporttell the user there wasn't enough data — nothing further is coming

The third row is the one to handle explicitly. It previously emitted nothing at all (the publish guarded on the id being present), so a host waiting on this subject would wait forever for a report the server had already declined to produce. Note also that such a submission is retired to processed at submit time rather than entering the in-flight set, so it does not appear as a card of any kind — neither "Processing…" nor "Insufficient Data" (SB-2558). Rows that earlier builds left parked as uploaded with scoredNoResult set are retired the same way at the next launch or reconcileSubmissions, so SB_RecordingSubmissionInfo.scoredNoResult / SB_LocalRecordingEntry.scoredNoResult are now always false on anything the SDK hands a host; both are kept only for source compatibility.

The server returns a recording id only for a submit that carries spotCheckData, which is derived from the window's beat-to-beat intervals. So the SDK refuses a spot check before submitting it when a completed post-stop sync leaves the window with no BBI — it throws SB_RecordingError.insufficientData, creates no submission row, and nothing reaches the timeline. (Earlier builds gated on any HR / HRV / RR row instead, so a window with continuous HR but no BBI was submitted and came back with no id.) The third row of the table is now reachable only for a scan whose post-stop sync could not run.

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 spotCheckData, the server persists them, and fetchSpotCheckDetails(id:) hands the same values back. A host that waits for the round trip is therefore 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:

swift
public enum SB_SpotCheckReportEvent: Sendable, Equatable {
    case ready(SB_SpotCheckDetails)
    case unscoreable
    case deferred
}
casemeaninghost should
.readythe report, built from the data being uploadedshow it now — no wait, works offline
.unscoreabledata is all in and holds no beat-to-beat intervals: no report exists and none willtell the user there wasn't enough data
.deferredthe post-stop sync couldn't run, so the window's data may still be on the bandtell the user it'll appear on their timeline

.ready carries every field the server would return except pdfReportURL, which only exists once the server has rendered it. Keep any "share the PDF" affordance hidden until biometricRecordResult delivers an id for the same recording; that id is also what the timeline entry is keyed on, so a host showing a local report can refresh it in place when the id lands (the numbers are identical by construction — the shown report and the uploaded one are the same derive).

.deferred and .unscoreable are both terminal for the in-session decision: neither will be followed by a .ready for that recording.

The HR graph is the band's own continuous-HR series, not a beat-to-beat derivation. The RMSSD, stress index and PNS/SNS tiles come from bioedge over the window's intervals, but hrGraphDatapoints — and the minHR / maxHR / avgHR computed from it — read the same continuous-HR rows the live-measures upload sends, clamped to a plausible 20–220 bpm. That is what makes the local graph and the server's graph the same graph, and it matches Android. Earlier iOS builds synthesized a denser per-beat series from the intervals instead; it could disagree with both the server and the band, so a host that cached those points should not expect them to line up with a refetched report (SB-2134).

activityReport and meditationReport — always a report ​

Both fire exactly once per finalized recording and carry the report directly — SB_WorkoutDetail for an activity, SB_MeditationGraph for a meditation. These are the same types fetchWorkoutDetail(workoutTime:) and fetchMeditationGraph(date:sessionTimestamp:) return, so a host renders local and server data through one screen.

There is no "not enough data" verdict on these two, deliberately. An activity or a meditation is a real event with a duration, a name and a time whether or not biometrics came through — so whatever the window holds is plotted and whatever it doesn't simply isn't there. A workout that captured no heart rate yields a detail with hrmData == nil; a meditation with no respiration yields an empty brpms. Hosts already omit a chart with no series, which is the whole behaviour.

Spot check is the exception, and keeps its three-way SB_SpotCheckReportEvent: its entire content is its biometrics, so an empty window leaves genuinely nothing to show, and the server will decline to score it.

activityReport's .headerMetrics carry duration, calories and — for step-based workouts only — distance and pace. Non-step workouts (swimming, basketball) carry no steps or distance rather than zeros: the band doesn't count them there, so a zero would read as "you took no steps" instead of "steps aren't measured here". This mirrors the server, which skips the block entirely for them.

Neither is guaranteed to match the server, and that is worth knowing before building on it. A spot check's report agrees by construction — the phone computes it, the submit ships it, the server stores it verbatim. These two do not:

  • Activity calories. The server recomputes from its own copy of the HR series and its own 30-day resting-HR baseline, and chooses between two calorie formulas with a deployment flag the client can't see (SB_WorkoutCalorieFormula documents this). The computation is ported line-for-line, so the drift is small and confined to the calorie figure — but the number can settle when the server's entry lands.
  • Meditation trend lines. hrLinearFit / hrvLinearFit carry a colour encoding improvement against a 30-day baseline. The server draws that baseline from the whole account; the SDK's comes from local sleep history, so a device holding less history than the account produces a lower baseline — or none, in which case the fit is returned uncoloured rather than coloured against a wrong number.

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 hr_result — 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 timestamp, so every point collides by design.

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.

Refresh the on-screen report in place when the server's entry arrives, rather than re-navigating.

Manually-logged sessions (createActivitySession) fire neither — there is no recorded window to build a report from.

SB_MeditationGraph gains hrLinearFit / hrvLinearFit (SB_TimeValueStraightLine?). The server has always sent them; the SDK simply never surfaced them. They are bridged from the proto as well as built locally, so a fetched graph and a local one carry the same fields. A series of fewer than 2 points, or more than 3600, can't be fitted and leaves the field nil.

SB_MeditationGraph no longer carries a meditation score (SB-2153). score, scoreFactors and scorePenalty, the SB_MeditationScore / SB_MeditationScoreFactor / SB_MeditationScorePenalty types and the SB_MeditationScoreProcessState enum are all removed, along with the local port of the server's scoring model that populated them on the offline path. Nothing consumed them. The server still computes and returns a score on the wire, so a host that wants one reads it from the API directly.

3.4.2 reauthenticationRequired — no credential to send ​

Fires when the SDK is asked to make an authenticated RPC while no stored credential exists. The host should route the user to sign-in.

This is a distinct failure from the two neighbouring ones, and the distinction is the point:

signalwhat happenedwho rejected
subscriptionLostlive session, no active subscriptionserver
SB_AuthError.refreshTokenExpiredrefresh token rotated / revoked / expiredserver
reauthenticationRequiredno credential existed to sendthe SDK, before the wire

The SDK now refuses to dispatch an authenticated RPC without a credential rather than sending a headerless request. The server's authentication gatekeeper rejects any request carrying neither auth nor access_token, so such a call can never succeed — and from the persistent upload queue it is retried indefinitely. In SB-2105 that produced ~78,000 rejected uploads per affected device with no user-visible symptom, because reads pre-check the credential and return early while uploads did not: nothing reached the wire to fail visibly, and the app rendered a normal dashboard for three days.

Behaviour a host can rely on:

  • The blocked call throws SB_AuthError.missingAuthToken. That part is unconditional — the call needs a credential, has none, and cannot succeed.
  • The event is narrower than the refusal (SB-2137): it is emitted only when this install is expected to hold a session — it signed in and has not signed out. An app that is merely signed out has no session to re-authenticate, and hosts turn this event into a sign-out with an explanation, so firing it at a signed-out user (or one part-way through creating an account) would log out an account that was never signed in. Android has drawn the line here since SB-2105; both platforms now agree.
  • Pairing before authenticating does not count as a session (SB-2200). A paired band used to be sufficient evidence on its own, on the reasoning that only a signed-in user can have paired one. A host that pairs before it registers or signs in breaks that: the SDK persists the band, and the pair's own link event then reads it back as proof of a session and fires this event — against bookkeeping the SDK had written a line earlier. Hosts are free to pair in whatever order suits them, and the first-party app pairs several onboarding steps ahead of account creation.
  • The pair-time device link is deferred, not lost, when no credential exists (SB-2200). UpdateUserDeviceInfo cannot succeed without one, so it is not dispatched; instead every path that establishes a session — signIn, createAccount and registerUser alike — re-registers whatever band is on record. A host that pairs first therefore gets its link on the first authentication, and one that authenticates first is unaffected.
  • The event is sent at most once per episode, and re-arms after the next authenticated RPC that succeeds — so a draining upload queue produces one event, not one per job.
  • Queued uploads stop retrying (SB_JobRetryPolicy treats a missing credential as terminal). Nothing that carries user data is discarded: the packet, biometrics, temperature, engine-result, sleep and recording-submit paths all mark their rows processed only on a successful upload, so the rows stay put and the post-sync sweep re-queues them once the user has signed back in.
  • The RPCs the server itself treats as unauthenticated are never blocked by this guard — they carry no auth header at all, by design, because they run before a session exists: login, createUser, validateAccountRequirements (activation code), checkEmailAvailability, and requestPasswordReset (plus the internal code-based requestPasswordResetCode / resetPasswordWithCode). Everything else on the surface requires a valid session. SB-2135: four of those were still dispatching through the authenticated path, so on a fresh install the guard refused them and sign-up failed at the e-mail step.
  • An SDK-key host does not get an automatic session rebuild here (SB-2095): only a freshly minted single-use token can rebuild an SDK-key session, the SDK cannot mint one, and holding something that could is what used to force the organization key onto the device. Getting fresh credentials is the host's call.

3.4.3 Sync, recording and sign-out results ​

SubjectPayloadWhen it fires
syncCompletedSB_SyncResult?A sync drained. nil on the short-circuit path: the band had too few packets to be worth fetching, so nothing was fetched. Non-nil when the final batch of a fetch was acknowledged — acknowledge (always true), logCount (packets the band reported for this sync) and syncDuration (seconds since the fetch started). A NAK'd sync does not fire; it is reported as the "device sync failed" analytics event instead (§3.4.4).
hrSyncFinishedForActivityVoidAfter the user stopped a recording, once the band's data for it has synced and the recording's engine results are uploaded (or there were none). Recording finalize follows.
signOutCompleteVoidAt the end of signOut(), after the SDK's local teardown.
sleepUploadedVoidA stored sleep was accepted by the server (including one the server flags as spurious). Pairs with sleepStored for a two-stage "got it → uploaded" UI.
swift
public struct SB_SyncResult {
    public let acknowledge: Bool
    public let logCount: Int
    public let syncDuration: TimeInterval   // seconds
}

3.4.4 Analytics events ​

analyticsEvents is the SDK's telemetry for your analytics provider. Each SB_AnalyticsEvent carries a name and a properties: [String: String] bag. The SDK adds no user or app metadata — subscribe, merge in your own (user id, app version, environment, …), and forward. Events are always delivered on the main queue:

swift
public struct SB_AnalyticsEvent: Sendable {
    public let name: String
    public let properties: [String: String]
}

sensorBio.analyticsEvents
    .sink { event in myAnalytics.track(event.name, properties: event.properties) }
    .store(in: &cancellables)

iOS and Android emit the same set with the same names, keys and value formats (SB-2440). Every value is a String; numbers use a . decimal separator with no grouping, whatever the device locale.

Every event carries phone_epoch — phone wall-clock time, epoch seconds. It is the moment the event was sent unless the table gives it a more specific meaning (the time a pairing completed, a removal, a failure); it isn't repeated in the rows below except where it has that meaning.

EventPropertyValue
device epoch updated — configure found the band clock ≥ 5 s off the phone and rewrote itdevice_epochBand epoch before the correction, seconds
phone_epochPhone epoch, seconds
delta_secondsphone_epoch − device_epoch, signed integer
device errored — at most once per synced chunk that carries diagnostic error packetserror_typeSpace-separated tokens, in this order, no leading or trailing space: ble watchdog ppg imu_overflow algorithm_nan_in_accel_buffer
packet_bytesThe error packets as uppercase space-separated hex bytes, packets joined by ", " — e.g. 87 0B 07 0C 01, 87 0B 07 07 02
epochBand timestamp of the latest packet in the chunk, seconds
device sync failed — the SDK NAK'd a sync batch, intermediate or finalreasonAlways present; see below
intermediatetrue / false
number_of_packets_recordedPackets the band reported for this sync
number_of_packets_syncedPackets received so far
expected_sequence_numberOnly when reason is out_of_sequence
received_wrong_sequence_numberOnly when reason is out_of_sequence
device synced — successful syncs, throttled (see below)packet_countPackets synced since the last device synced
number_of_syncsAcknowledged batches since the last device synced
sync_durationTheir summed duration in seconds, exactly two decimals (e.g. 12.34)
device removed — the host unpaired the band with removeDeviceFromPairedDevices(_:); captured before any teardownserial_numberThe removed band's serial number; "" if it was never read
phone_epochTime of the removal, seconds
device paired — a band was newly paired through beginPairing() / selectDevice(_:) (never on a reconnect of an already-paired band); sent once per pairing, as soon as the serial number and firmware version are both known — usually right away, otherwise after the first configuration that reads themserial_numberThe band's serial number
firmware_versionThe band's firmware version as firmwareVersion publishes it
phone_epochTime the pairing completed, seconds
device firmware update failed — an updateFirmware(_:) call threw; once per call, and the error still reaches the caller unchangedreasonSee below
current_versionfirmwareVersion when the update started; "" if unknown
attempted_versionlatestFirmwareVersion when the update started — the target the SDK offered; "" when it had none
phone_epochTime of the failure, seconds
device firmware update successful — an updateFirmware(_:) call completed; once per callold_versionfirmwareVersion when the update started; "" if unknown
new_versionThe version the band reports after rebooting onto the new image and reconnecting. If it doesn't report one within 5 minutes — or the band is removed, or another update starts, first — the attempted version (latestFirmwareVersion at the start)
sleep recording uploaded to server successful — the sleep upload RPC returned OKsleep_end_epochSleep 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 upload stays queued and retriesreasonSee below
sleep_end_epochSleep end, milliseconds

device sync failed reasons. 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. store_in_memory — the on-device store fell back to memory, so acking would lose the data; repeats every sync until the real store opens. store_write_failed — saving the batch's raw sync bytes failed, so acking would lose them; the band re-sends the batch (SB-2526). unknown — a NAK with no recorded cause. This event was named device sync failed due to missing sequence number before SB-2440.

device firmware update failed reasons. When the band or the Bluetooth layer reported an OTA status, reason is that status's lowercase name — the same list on both platforms: crc_error · invalid_header_info · invalid_packet_length · insufficient_buffer · unknown_error · status_max · app_cancel · app_not_enough_data · app_missing_objects · app_missing_file · app_missing_device · app_existing_ota. Otherwise it is an SDK-level code: not_connected (no band when the update started) · not_configured · unknown. The Bluetooth layer reports every flash failure as a status — a lost link and its OTA watchdog both arrive as app_cancel, an unreadable image as app_missing_file — so the SDK-level codes cover only failures outside the flash. A flash whose completing reboot drops the link before the BLE layer reports success is reported as failed (typically app_cancel), even though the band may come back on the new firmware.

sleep recording upload failed reasons — the same on both platforms. From the upload response's status code: invalid · bad_sleep_request · sleep_stages_timeseries_data_issue · unrecognized_status (a code the SDK doesn't recognise). invalid_argument — the RPC itself failed with gRPC invalidArgument: the server validated the payload and refused it.

device synced throttle. Every acknowledged batch, intermediate or final, is counted. The event is sent only when more than 5 minutes have passed since the anchor, and the counters reset after each send. The anchor moves only when a final (non-intermediate) batch sends the event. The state is in memory, so the first acknowledged batch after a launch always sends.

3.5 Recording submissions (optimistic timeline) ​

In-flight finished-recording submissions the SDK is still uploading / processing, backed by the durable SB_RecordingSubmission store. Drive the timeline's pinned "we're working on it" cards off this, then reconcile them against the fetched timeline. Values cross the boundary as the SB_RecordingSubmissionInfo value type (no SwiftData leak); status is SB_RecordingSubmissionStatus (pendingUpload → uploaded → processed, or failed). Only non-processed rows are surfaced.

failed means either the submit never succeeded within the 24h retention cap, or the server rejected the session outright (SB-1851) — a non-ok submit response code (invalidTimestamps / missingMetadata / invalidMetadata) or a gRPC INVALID_ARGUMENT. A rejected row goes to failed immediately with the reason on lastErrorMessage, and is never marked uploaded. For a spot check the rejection is also published on biometricRecordResult as an error, not as an empty result.

swift
// Current in-flight submissions (status != .processed), newest first;
// CurrentValueSubject-backed, so new subscribers get the state immediately.
public var pendingSubmissionsPublisher: AnyPublisher<[SB_RecordingSubmissionInfo], Never> { get }

// One-shot snapshot of the same set (e.g. on .onAppear).
public func pendingSubmissions() -> [SB_RecordingSubmissionInfo]

// Flip any in-flight submission the server now shows to .processed (drops it
// from the set). Call after fetchWorkoutTimeline, passing the flattened
// entries: result.items.flatMap { $0.entries }. No extra network.
public func reconcileSubmissions(against entries: [SB_WorkoutEntry])

// Manually re-drive a .failed submission (reset to .pendingUpload + kick the
// engine). No-op if the id is unknown or the submission isn't .failed.
public func retrySubmission(localId: UUID)

3.5.1 Local-first timeline entries (SB-1956) ​

A finished recording's report is now stored on its submission row, so it survives a relaunch, a recreated view model, or the user backing out and coming back — none of which the PassthroughSubject events could. At that point a "Processing…" placeholder is the app declining to show data it already holds, so the SDK synthesizes the real row instead:

swift
// In-flight recordings that have a stored report, as real timeline rows.
public func localRecordingEntries() -> [SB_LocalRecordingEntry]

// The stored report for a recording, by its start timestamp.
public func localWorkoutDetail(startTsMillis: Int64) -> SB_WorkoutDetail?
public func localMeditationGraph(startTsMillis: Int64) -> SB_MeditationGraph?
public func localSpotCheckDetails(startTsMillis: Int64) -> SB_SpotCheckDetails?

SB_LocalRecordingEntry carries a real SB_WorkoutEntry — same shape the timeline read returns — plus the submission's status, its scoredNoResult flag, and the dateInt (yyyyMMdd) section it belongs in. The SDK does the assembly so a host renders these through its existing row view and routes taps through its existing per-type detail screens.

Three merge rules, each a bug if dropped:

  • Page 1 only. These are minutes old and belong at the head of the list. Cursor pages encode a server-side query; don't merge into them.
  • Dedup on the correlator, at second granularity. reconcileSubmissions normally removes a local row before its server entry renders, but there is a window where both exist. Match at seconds, not milliseconds: the spot-check server domain drops the sub-second remainder, which is why exact millisecond matching could never match a spot check (SB-1214).
  • Not while searching or filtering. A synthesized row never went through the server's query.

fetchWorkoutDetail(workoutTime:) and fetchMeditationGraph(date:sessionTimestamp:) now fall back to the stored report when the server has no answer — a just-ingested workout returns NOT_FOUND, a meditation's summary can be twelve minutes behind, and offline there is no answer at all. The server stays the authority whenever it has one. fetchSpotCheckDetails(id:) gets no such fallback: it is addressed by a server-assigned id that doesn't exist until the submit lands, so there is no key to fall back from — use localSpotCheckDetails(startTsMillis:) while entry.workoutId is empty.

Delete and edit work on these rows — do not gate them (SB-2226). A locally-rendered row is a full timeline row in every respect a host can act on: modifyWorkout(action: .update, …) and modifyWorkout(action: .remove, …) both accept one, and the SDK decides on its own whether the operation is a server call or a local one (see §7.9). Earlier guidance to disable delete or modify on these rows is withdrawn: which case applies is bookkeeping only the SDK can see, and asking a host to know it is what produced "I can't delete the activity I just recorded" while a manually-logged one beside it deleted fine. There is no flag on SB_LocalRecordingEntry to gate on, and there does not need to be.

SB_RecordingSubmissionInfo changes. autoPresentOnProcessed and presentedAt are removed. They were added for an auto-present-on-processed flow that was designed, dropped in the 2026-07-06 scope revision, and never read; SB-1747/1952/1954 settled the question they existed for by another route — every recording type now shows its report at finalize, so there is nothing left to present later. In their place, hasLocalReport: Bool says whether a stored report exists. Submissions where it is false — a manually-logged session, an .unscoreable / .deferred recording, a row predating this version — are the only ones with nothing to render but a status.

3.6 Detected activities (confirm-or-dismiss) ⚠️ interface change ​

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, and the SDK stores it.

Nothing is uploaded on its own. A detection is an offer: the SDK holds it in the durable SB_DetectedActivity store and publishes it, and the user either confirms it (which submits it as a real activity) or dismisses it. Values cross the boundary as the SB_DetectedActivityInfo value type (no SwiftData leak).

swift
// Detections that are ready to be confirmed, oldest first. CurrentValueSubject-
// backed: a new subscriber receives the present state synchronously on
// subscribe, then every change (from SDK queues — hop to main for UI).
// The single surface, like Android's `detectedActivities` StateFlow.
public var detectedActivities: AnyPublisher<[SB_DetectedActivityInfo], Never> { get }

// Confirm a detection under `activityName`: submits it as a real general-cardio
// session and retires the detection. Returns false when the detection is unknown
// or already answered, so a second call for the same detection is a no-op.
@discardableResult
public func confirmDetectedActivity(startTsMillis: Int64, activityName: String) async -> Bool

// Dismiss a detection. Marked ignored on-device and never published again,
// including when its bookend re-syncs (which it will). Nothing is uploaded.
@discardableResult
public func dismissDetectedActivity(startTsMillis: Int64) async -> Bool

⚠️ Interface change: the two read surfaces are now one, matching Android's single detectedActivities StateFlow. detectedActivitiesPublisher is renamed detectedActivities, and the detectedActivities() snapshot call is removed — subscribe instead; the current set arrives immediately. Confirm and dismiss are now async (previously synchronous, and confirmDetectedActivity was @MainActor), matching Android's suspend functions of the same names. Call them from any context with await, e.g. Task { await sensorBio.confirmDetectedActivity(…) } from a button action. The store work runs on the SDK's SwiftData queue and the caller suspends instead of blocking; only the final submit step hops to the main actor. Behaviour is otherwise unchanged — idempotent, false for an unknown or already-answered detection, same submission path.

SB_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 / motionAndCadence), and createdAt (when the bookend synced, not when the activity happened). Field-for-field the same as Android's type of the same name, so a host porting between them has nothing to translate. Render the activity's time from tzOffsetMinutes, not the phone's current zone, so an activity 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 that fails 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 publisher 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?" predicate is vacuously true 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 SB_RecordingSubmission row, same job queue, same locally-built report, same pendingSubmissionsPublisher / localRecordingEntries() surfaces described in §3.5. A host that already renders those needs no extra work for the tail of this flow — only the card that asks the question.

The session is stamped used_hrm, because unlike a manually-logged session 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.

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 the publisher 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.

The band also needs auto-detect switched on to produce detections at all — the active-mode auto_detect_enabled setting in the advanced sensor configuration, off unless an administrator turns it on. 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.


Sensor Bio Mobile SDK — iOS & Android integration reference.