Appearance
BLE Device Control
6.1 Pairing
Pairing is one SDK-owned transaction, not a sequence of host calls. Three methods open, advance, and close it; everything in between is reported on $pairingState.
swift
public func beginPairing() // open a transaction, start scanning
public func selectDevice(_ id: String) // pair with one of the discovered bands
public func endPairing() // cancel, or dismiss a terminal state; idempotent
@Published public internal(set) var pairingState: SB_PairingState?swift
public enum SB_PairingState: Equatable, Sendable {
case scanning([SB_DiscoveredDevice]) // cumulative, de-duplicated
case connecting(SB_DiscoveredDevice)
case awaitingConfirmation(SB_DiscoveredDevice) // band is blinking; user must press its button
case paired(SB_PairedDeviceState) // terminal
case failed(SB_PairingFailure) // terminal
}
public enum SB_PairingFailure: Equatable, Sendable {
case bluetoothOff, scanTimeout, connectTimeout, connectionLost,
notConfirmed, deviceUnavailable
}Render the state; make three calls:
swift
sensorBio.$pairingState
.receive(on: DispatchQueue.main)
.sink { state in
switch state {
case .scanning(let devices): showList(devices) // tap → selectDevice(id)
case .connecting: showConnecting()
case .awaitingConfirmation: showPressTheButton()
case .paired(let device): showAllSet(device) // dismiss → endPairing()
case .failed(let reason): showCantReachBand(reason) // dismiss → endPairing()
case nil: showStartScreen()
}
}
.store(in: &cancellables)
sensorBio.beginPairing()What the SDK does inside the transaction, so the host doesn't: scanning and discovery de-duplication; re-issuing the scan when Bluetooth authorization is granted mid-scan (CoreBluetooth silently drops a scan issued before the central reaches poweredOn); 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; configuring the band over the link that is already up; and every timeout.
Bluetooth switched off. If Bluetooth is authorized but switched off, beginPairing() publishes .failed(.bluetoothOff) within about a second, instead of scanning until .scanTimeout. The SDK shows no UI for this; the host decides what to say. iOS gives apps no way to turn Bluetooth on, so tell the user to switch it on in Control Center or Settings, then call endPairing() and beginPairing() again. A first-run pair, where the Bluetooth permission prompt has not been answered yet, is unaffected: it scans as before.
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 fully ready: persisted, registered, reported, and configured — no reconnect is required. 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. The SDK suppresses the forced-firmware prompt (updateRequired) and BLE auto-reconnect for the life of the transaction.
Connect, unpair & paired-device state
swift
public func connect(_ id: String) // manual reconnect; not needed for pairing
public func disconnect(_ id: String? = nil)
public func removeDeviceFromPairedDevices(_ id: String) // unpair: also clears the persisted store; sends the "device removed" analytics event (§3.4.4)
public func clearPairedDevice() // wipe the paired snapshot (e.g. fresh-onboarding reset)
public func reclassifyPairedDevice(macAddress: String, name: String, type: SB_BluetoothDeviceType)
public internal(set) var isSigningOut: Bool // true from signOut() until the next registerUserThe SDK owns paired-device persistence end-to-end — there is no app-built devices dictionary, and no host-side write on pair. removeDeviceFromPairedDevices(_:) clears it on an explicit unpair; clearPairedDevice() wipes the snapshot outright; signOut() clears it too, and additionally unlinks the device server-side. Hosts do not need to call updateUserDeviceInfo(…, unlinkDevice: true) themselves on logout. isSigningOut is read-only state the SDK uses to gate BLE auto-reconnect across the signed-out window.
reclassifyPairedDevice(…) exists for one case: a band flashed onto different firmware is a different device type from then on, and the BLE layer reports a paired band's type from what was registered out of storage, not from the hardware. Leave storage alone after an Alter → Sensr migration and the band reconnects still classified as an Alter, updateRequired fires again, and the flash repeats forever. It is not part of pairing.
Static bootstrap accessor (callable before SB_SDK.shared initializes):
swift
public static var persistedDevicesDictionary: [String: AnyObject]? // persisted devices dict (devicesKey)6.2 Device commands
swift
public func userLED(red: Bool = false, green: Bool = false, blue: Bool = false,
blink: Bool = false, for seconds: Int) async throws
public func hapticMotor(pulse: Bool = false, intensity: Int, for seconds: Int) async throws
public func setAskForDeviceResponse(_ enable: Bool)
public func airplaneMode() async throws
public func reset()
public func updateFirmware(_ url: URL, delay: Int? = nil, size: Int? = nil) async throwsreset() sends the band its reset command. It is a plain reset, not a factory reset. It returns immediately and sends the command in the background. If no band is paired, or the command fails, the failure is only logged.
updateFirmware (both the URL and the Data overload) reports each call once on analyticsEvents as device firmware update failed or device firmware update successful (§3.4.4); the error a failed call throws is unchanged.
These are raw device commands. Pairing does not require any of them — beginPairing() runs the LED/haptic confirmation and the button listening itself (§6.1). Reach for userLED / hapticMotor / setAskForDeviceResponse only for your own device interactions outside a pair.
Firmware debug hooks. Gated behind SENSORBIO_INTERNAL; absent from the binary.
swift
public var debugOfferFirmwareUpdate: Bool // offer a reflash of the version already on the band
public var debugFailFirmwareUpdate: Bool // drop the link ~20% into the next flashBoth exist to rehearse the firmware failure → band reset → retry path on demand, which is otherwise hard to provoke deliberately and easy to regress silently.
debugOfferFirmwareUpdate forces updateSuggested and points latestFirmwareVersion at the device's current firmware, so an update can be triggered without a newer release existing. It takes effect immediately — the update decision re-runs on assignment rather than waiting for a reconnect — and deliberately overrides the white-label firmware gate and the Alter/UART-migration special cases, since it means "let me trigger an update now". The one thing it does not override is a device emulator on firmware 99.99.99, which never offers an update.
debugFailFirmwareUpdate fails the next flash about 20% in by dropping the BLE link. Dropping the link rather than throwing is what makes it faithful to a real interrupted update: the band is left holding a partial image, the host takes its disconnect-during-update path, and the band reset that clears the partial image cannot be delivered until the band returns — so the host's deferral of that reset is exercised too. Leave it on to watch the failure, turn it off and retry to watch the recovery.
6.3 Recording
Recording is fully SDK-orchestrated — there is no low-level start/stop surface; the SDK owns the BLE session lifecycle end-to-end.
High-level orchestrations. Each runs a session end-to-end: BLE start/stop, timer (fixed-duration countdown or open-ended count-up), post-stop sync wait, session build, and submission. Three completion paths each: natural completion (countdown modes only) / early-finish-with-submit via finishCurrentRecording() / cancellation via Task.cancel(). Submission is automatic — there is no separate "submit" call.
swift
@MainActor
public func recordDetailedBiometrics(
duration: TimeInterval,
minDuration: TimeInterval
) async throws
@MainActor
public func recordMeditation(
duration: TimeInterval,
minDuration: TimeInterval,
sessionName: String? = nil,
sessionNameAlreadyExists: Bool = false
) async throws
@MainActor
public func recordActivity(
activityName: String,
minDuration: TimeInterval
) async throws
public func finishCurrentRecording() // signal: "user tapped End Recording"; persists the stop intent synchronously
public func pauseRecording() // freeze the timer + stop the device stream
public func resumeRecording() // restart the device stream + resume the timerrecordActivity(...) is open-ended — it has no duration: parameter and runs until finishCurrentRecording() flips or the calling Task cancels. recordingState publishes .recording(elapsed:, target: nil) so countdown UIs render count-up format from the nil target.
Tick cadence vs. publish cadence (SB-1949). The orchestration loop runs at 250ms, but recordingState is published only when the whole second changes — at most once per second — and the elapsed it carries is floored to that whole second. Hosts driving a MM:SS display or a target - elapsed countdown see no difference; hosts that were relying on sub-second elapsed resolution will now see integer seconds. The 250ms loop is retained because it is also the poll interval for finishCurrentRecording() and for countdown expiry, so End Recording latency and auto-stop precision are unchanged.
All three are @MainActor. They drive recordingState / canFinalize from a 250ms tick, and those are @Published, so the loop has to run on the main actor or SwiftUI observers get "Publishing changes from background threads is not allowed". SB_SDK itself is not main-actor-isolated, so a non-isolated async method would have hopped straight off the main actor and published from the cooperative pool. Source-compatible for callers: awaiting from any context still works, and callers already on the main actor (the usual case for a UI-driven recording) see no change.
Countdowns end on their target (SB-2243). For a countdown (target != nil) the session is stored ending no later than the instant its pause-adjusted elapsed time reached target, however late the auto-stop tick ran — a locked phone suspends the app until a BLE event wakes it, so the tick can land seconds past the target. A countdown that ran out while the process was dead is finalized at that instant on restore instead of being resumed, and the .recording(elapsed:, target:) published at restore never reads past target.
Pause / resume (recordActivity + recordMeditation). pauseRecording() freezes the elapsed clock (recordingState holds its last .recording(elapsed:, target:) value and canFinalize stops advancing) and stops the device's manual PPG stream, so the paused span carries no biometric data. resumeRecording() restarts the stream and continues the clock. Both are no-ops outside an active recording; the device stop/start is a fire-and-forget BLE round-trip so the timer freezes/thaws instantly. Each paused window is submitted as the complement activeWorkoutSegments on the finished session, so downstream sees only the active spans.
Live HR for the recording (recordingHRSeries, SB-1968). A recording's HR chart should be bound to recordingHRSeries, not accumulated from the hr publisher.
hr is a live BLE passthrough: it emits only while the band is connected and streaming. A chart built from it therefore carries a hole exactly the width of any Bluetooth disconnect — which is a normal event during a workout, not an error. The data is not lost. The band keeps logging its own per-second HR through a disconnect, and the next sync delivers it; but reassembling that into a correct series means unioning two on-device tables, filtering implausible values, excluding the spans the user paused, re-reading on each sync, and anchoring the whole thing at the recording's start. The SDK does all of it:
swift
@Published public internal(set) var recordingHRSeries: [SB_TimeValuePoint] = [] // ascending by timestamp
@Published public internal(set) var recordingPauseSegments: [SB_TimeSegment] = []Lifecycle — it is the current or most recent recording's series:
- cleared and re-seeded when a recording starts;
- live samples append as they arrive;
- every completed sync republishes it, which is where a disconnect's gap closes. Points land inside the series, so treat each emission as a new array rather than diffing the tail — a chart that only appends will draw the wrong thing;
- a recording restored after an app kill seeds from the on-device tables across the whole
[start, now]window, so it returns complete instead of restarting at the moment the host re-subscribed; - finalize leaves it standing. Finalize runs for up to ~68s, and clearing at the stop tap would blank a host's chart underneath its own "Syncing…" screen. The next recording's start is what resets it.
Paused spans are excluded from the series, and recordingPauseSegments says where they were. Shade those; leave other gaps alone. Do not infer pauses from gaps in the series — since it back-fills, a surviving gap usually means the band captured nothing there (off-wrist, poor contact), which is not the same thing and should not read as "you paused". Completed windows only; a pause in progress appears on resume, and isRecordingPaused covers the live state.
Note that getHRPoints(date:) is not a substitute. It answers "what was this person's HR today" from the periodic algorithm output and does not see the dense per-second recording trace at all — a short workout can be complete in one and absent from the other.
recordingHRSeries and the finalize report (activityReport) are built from the same underlying window read and exclude paused spans the same way, so the live chart and the report the user opens seconds later agree — including in their min / avg / max and zone breakdown. This also matches the server, which filters a workout's HR by activeWorkoutSegments. The paused spans are still drawn as bands on the report; there is simply no line under them.
Manual session logging. For "log an activity that happened earlier" (no live recording, no device involvement). The SDK builds the session from the typed inputs and queues it for upload.
swift
public func createActivitySession(
activityName: String,
startDate: Date,
duration: TimeInterval
)Observable orchestration state — gates the recording UI:
| Property | Type | Description |
|---|---|---|
recordingState | SB_RecordingState | .idle / .recording(elapsed, target) / .finalizing(phase) |
canFinalize | Bool | True once elapsed ≥ minDuration AND at least one HR sample has arrived |
isRecordingPaused | Bool | True while the recording is paused (see pauseRecording()); drives the Pause/Resume button |
recordingHRSeries | [SB_TimeValuePoint] | The recording's complete HR series — live samples merged with what synced from the band, gaps back-filled, paused spans excluded, anchored at the recording's start. Bind a live chart to this (see below) |
recordingPauseSegments | [SB_TimeSegment] | The recording's completed pause windows, for shading those spans on that chart |
Throws SB_RecordingError:
swift
public enum SB_RecordingError: Error {
case alreadyRecording
case noPairedDevice
case bleStartFailed(underlying: Error)
case bleStopFailed(underlying: Error)
case tooShort(elapsed: TimeInterval, minimum: TimeInterval)
case insufficientData // detailed-biometrics only
}insufficientData means a completed post-stop sync left the spot check's window with no beat-to-beat intervals — the one thing the server scores a spot check from. HR samples alone don't count. The recording is not submitted and gets no submission row, so the host's "not enough data" notice is the only trace of it, and there is no timeline card to clean up (SB-2558).
Persist + restore across app kill. The SDK persists every in-flight record*(...) orchestration on entry and clears the envelope on every terminal path. If the host process is killed mid-recording, SB_SDK.init() re-publishes the matching recordingState synchronously on next launch and decides what to do with the envelope, in this order:
- Stop already requested (
isStopRequested, or a legacy stop-date newer than the envelope's start) — the user tapped End before the kill, so the recording is over. It is finalized at the persisted stop time and submitted; it is never resumed.recordingStatecomes up.finalizing(...), not.recording(...). - Abandoned (
isAbandoned— in flight longer thanSB_PersistedRecording.maxInFlightDuration, 12h) — nobody ended it and there is no defensible end timestamp, so the session is discarded rather than invented. The window's packets still upload via the normal passive path, so no biometrics are lost. - Expired (fixed-duration, past its expected end) — skip the remaining countdown and finalize.
- Otherwise — resume the countdown / open-ended count-up.
A recording killed while paused comes back paused (SB-1968). Pause state was in-memory only, so restore previously resumed it as running: the user paused, killed the app, returned, and the recording had quietly carried on — its paused span counted as active time, plotted on the chart, and submitted as an active segment. The envelope now carries the open pause (pausedAtEpochMs) and restore re-publishes isRecordingPaused == true with the elapsed clock still frozen. Hosts already binding to isRecordingPaused for their Pause/Resume button need no change; hosts that assumed a restored recording is always running should stop assuming it.
Case 1 is the important one: finishCurrentRecording() persists the stop request synchronously, at the moment it is called, before it signals the orchestration and before any BLE stop goes out. So "the user tapped End" survives a kill anywhere from the tap onward — including the up-to-250ms gap before the recording loop notices the flag. Previously that fact lived only in memory, so a kill mid-finalize resurrected the recording on the next launch — and because .activity envelopes have no expiry, an activity recording could be resurrected on every launch indefinitely.
Submission still flows automatically. Host viewmodels rebind via awaitActiveRecordingCompletion() — same async throws shape as the original record*(...) call.
swift
public var activeRecording: SB_PersistedRecording? { get }
public func awaitActiveRecordingCompletion() async throws
public func cancelCurrentRecording()activeRecordingis non-nil wheneverrecordingState != .idle. Itskind(andactivityName/sessionName) say which recording view to show — on launch, and equally whenever a live screen needs to re-attach.- Fresh and restored recordings are the same thing to a host (SB-2447). Every recording runs as one SDK-owned task, whether a
record*(...)call started it in this process or it was restored after a kill.record*(...)itself still returns / throws exactly as before, and cancelling the caller'sTaskstill cancels the recording. awaitActiveRecordingCompletion()waits on the recording in flight, live or restored, and throws what therecord*(...)call would. It is how a host attaches a screen to a recording it doesn't hold theTaskfor; any number of callers may await the same recording. Returns immediately when nothing is in flight, so host VMs can call it unconditionally. Cancellation forwards to the recording. Behaviour change: before SB-2447 it returned immediately for a live (non-restored) recording, which a host could only read as "finished".cancelCurrentRecording()cancels the recording in flight without submission, live or restored — the stop for a host that no longer holds theTask. Behaviour change: before SB-2447 it reached only restored recordings and was a no-op on a live one.
The persisted envelope:
swift
public enum SB_PersistedRecordingKind: String, Codable, Sendable, Equatable {
case biometrics, meditation, activity
}
public struct SB_PersistedRecording: Codable, Sendable, Equatable {
public let kind: SB_PersistedRecordingKind
public let startEpochMs: Int64
public let duration: TimeInterval? // nil for .activity
public let minDuration: TimeInterval
public let sessionName: String?
public let sessionNameAlreadyExists: Bool
public let activityType: SB_ActivityType? // .activity only
public let activityName: String? // .activity only
public let stopRequestedEpochMs: Int64? // nil while still running
public let stopConfirmedEpochMs: Int64? // nil if the band never acked
public let pauseSegments: [SB_TimeSegment]? // nil on envelopes written before SB-1968
public let pausedAtEpochMs: Int64? // nil unless a pause was open when this was written
public var startDate: Date { get }
public var endDate: Date? { get } // nil for .activity
public var isExpired: Bool { get }
public var stopRequestedDate: Date? { get }
public var stopConfirmedDate: Date? { get }
public var isStopRequested: Bool { get }
public var isAbandoned: Bool { get }
public static let maxInFlightDuration: TimeInterval // 12h
}stopRequestedEpochMsis written before the BLE stop goes out, so the user's intent to end the recording is durable across a process kill. It is also the session's end timestamp — deliberately not "whenever finalize happened to complete", which after a kill can be a different day.stopConfirmedEpochMsrecords that the band acknowledged the stop. Tracked separately because the remedies differ: user intent is final at the tap, whereas an unconfirmed device stop is re-delivered on the next full configure. Diagnostic — no finalize decision reads it.pauseSegmentscarries the recording's completed pause windows so they survive a process kill (SB-1968). Without them a restored recording would back-fillrecordingHRSeriesstraight through a span the user deliberately paused.nilmeans an envelope written before the field existed, and is read as "no pauses".pausedAtEpochMsis the open half of the same pair: a window only joinspauseSegmentson resume, so an app killed while the user sat paused used to lose that pause entirely — the recording restored as running, back-filled the span onto the chart, and submitted it as active. It is now what lets restore bring the recording back paused (see below); the window stays open, and closes on the user's own resume.isAbandonedbounds an envelope's lifetime..activityis open-ended, soendDate(and thereforeisExpired) is structurallynil/falsefor it and nothing else caps how long one may sit in flight.
6.4 Sync — automatic
Sync runs automatically once a paired device connects. No customer-side method call is required to trigger it; the SDK manages the sync lifecycle internally and emits state changes via the @Published deviceSyncing / percentSynced / lastSyncd properties (see §3.2).
Upload is automatic too. Every data type the device produces — biometrics, activity, steps, temperature, and sleep — is uploaded to the server by the SDK with no customer-side trigger. Uploads are driven off sync completion and a persistent, retrying job queue that survives app relaunches and waits for connectivity, so there is nothing to call and nothing to schedule. (Sleep upload previously exposed SB_OnDeviceSleepDecoder.launchSleepUploadThread(); that is removed — sleep is now handled internally like every other type.)
On-device storage recovers by itself. The SDK keeps synced data on the device until the server has it. If that store can't be opened (for example, a background launch before the first unlock after a reboot, or a damaged file), the SDK holds the data on the band instead of acknowledging it, retries the store, and after repeated failures sets the old store aside and starts a fresh one. The set-aside copy is deleted after 14 days or at sign-out. Signing out while the store is unavailable still clears the user's local data before anything can read it. Nothing is required from the host app.