Skip to content

Server APIs (async/await) ​

Every method below is async throws on the SB_SDK facade. All return typed SB_* domain models; authentication is automatic once the user is signed in. Outcome-style methods (e.g. registerUser, updateGoals) return discriminated enums rather than raw errors for common business cases.

Caching (dashboard + detail reads). These reads are disk-cache-backed. The policy has three cases:

  • Today (any granularity) is always fetched fresh so the latest server data wins. The response is still cached, and on a network failure the last cached payload is returned — a cold relaunch with no connectivity shows stale "today" instead of a blank screen.
  • A past date is served straight from the on-disk cache with no network call — but only once that cache is final, i.e. it was written after the date's own calendar day ended. An entry cached while the date was still "today" is provisional (the day was still accumulating — a late device sync, a sleep the server scores hours later), so the first time you open that day after it has passed the SDK refetches once to finalize it, then serves from cache thereafter. This is transparent to the caller: keep calling fetch… on load and the SDK decides whether a network hit is needed.
  • forceRemote: true (pull-to-refresh) always fetches, regardless of the above.

Stale-while-revalidate streams. Each cache-backed read also has an …Updates(…) variant returning AsyncThrowingStream<T, Error> that yields the last cached value first (if any), then the fresh server value — consume it with for try await v in …. This replaces the older synchronous cachedX(for:) peeks (removed): the peek read the store on the caller's (main) thread; the stream reads off-main and non-blocking (SB-1546), so for try await inside a @MainActor Task both paints instantly and keeps the UI thread free. On a fetch failure with a cached value present, the cached value is delivered and the stream finishes (no throw); with nothing cached it throws. fetch… (single value) is retained for pull-to-refresh (forceRemote: true) and one-shot reads. The stream variants: dashboardUpdates(for:tzOffset:), dailyHRUpdates(for:) / rangeHRUpdates(for:granularity:) (and the HRV / RR / SpO2 equivalents), stepsUpdates(for:granularity:), caloriesUpdates(for:granularity:), dailyActivityDetailUpdates(for:granularity:), dailyRecoveryUpdates(for:) / rangeRecoveryUpdates(for:granularity:), sleepDetailUpdates(endDate:endTimestamp:), sleepAggregationUpdates(for:granularity:), and workoutTimelineUpdates(for:). Each takes a trailing forceRemote: Bool = false (except workoutTimelineUpdates, whose page is always today). Exceptions: dailyRecoveryUpdates has no stale peek and yields once — its value is computed on-device, so a peek would only paint a stale server score first (see Local-first recovery score). dailyActivityDetailUpdates is the same on its local-first .day path, and keeps the stale peek for .week / .month / .year (see Local-first activity detail).

Non-blocking store access (SB-1546). All SDK SwiftData reads/writes on the async path (getSkinTemperature, the cache reads/writes behind the streams, and the packet-upload queue ops) now suspend on the store's serial queue rather than blocking the calling thread. getSkinTemperature(date:) is therefore async.

forceRemote (pull-to-refresh). Every cache-backed fetch… read takes a trailing forceRemote: Bool = false. When true, every cache shortcut is bypassed and the read always hits the network (still writing the fresh result to the cache, and still falling back to the cached payload on a network failure). Pass forceRemote: true from a user-initiated refresh. This is the escape hatch for data that changes after the fact — a device synced days later, or sleep/recovery scores the server finishes processing asynchronously after upload — on top of the automatic provisional-cache refetch described above.

Offline mode (SB-2421) ​

An organization can turn on offline mode in its white-label settings when it does not want Sensor Bio holding its users' data. The SDK picks the setting up on its own, as it does every white-label setting, and while it is on:

  • Nothing is uploaded. Metrics from the band are still decoded and stored on the device, exactly as before, but nothing is sent: no biometrics, activity, steps, temperature or sleep uploads, no recording submissions, surveys, workout edits or algorithm results, and no battery telemetry. If the organization turns offline mode off, everything held is uploaded then.
  • Raw device data packets are kept on the device instead of uploaded, for your app to collect as CSV with getDevicePackets (see Device data export below). Raw sensor logging follows the organization's setting (isRawLoggingEnabled), as it does online: with it on, the band's raw waveforms (PPG, accelerometer, gyro, ECG) are kept alongside the summary data (steps, events, HR, BBI, sleep/wake, …). Raw logging multiplies what the band stores and syncs, and so what accumulates on the phone until getDevicePackets collects it.
  • Server reads fail. Every fetch… method and every …Updates stream throws SB_OfflineModeError.unavailable, even when a cached copy exists — except the configuration reads listed under still allowed below (fetchGoals, fetchLockedDevices), and the dashboard (fetchDashboardData / dashboardUpdates), which returns the day assembled on the device (getDashboardData(date:)). The on-device get… reads (getHRPoints, getSleepDetail, getSkinTemperature, getSpO2, …) keep working, and so do the local-first paths (fetchDailyActivityDetail / fetchDailyRecovery with preferLocal: true) for as long as they don't fall back to the server. Writes that go to the server (addSleepSession, updateGoals, profile updates, …) throw the same error.
  • Still allowed: sign-in and sign-up, token refresh, sign-out, account deletion, password change, agreements, the white-label settings fetch itself, reading goals (fetchGoals — the on-device sleep score needs the sleep goal), the enabled-algorithm list, and pairing / device linking (fetchLockedDevices).
swift
public enum SB_OfflineModeError: Error {
    case unavailable   // the data lives on the server, and offline mode allows no server reads
}

Device data export (SB-2629) ⚠️ interface change ​

In offline mode the band's raw device data stays on the phone. getDevicePackets parses it on the device into CSV — the same rows, byte for byte, that the web device-data download produces — and hands it to your app a page at a time. Where the CSV goes (a file, your own server, another app) is up to you.

swift
@discardableResult
public func getDevicePackets(
    _ handler: @Sendable (SB_DevicePacketBatch) async throws -> Void
) async throws -> Int      // pages delivered

public struct SB_DevicePacketBatch: Sendable {
    public let serialNumber: String                    // the band the data came from
    public let csv: [SB_DeviceDataStream: String]      // data rows per stream, each ending "\n", no header line
    public let isEndOfStream: Bool                     // this band's stream ended (offline mode turned off, or the band removed)
}

public enum SB_DeviceDataStream: String, CaseIterable, Sendable {
    case ppg, imu, gyro, ecg, events, steps, activity
    case skinTemperature = "skin_temperature", battery, afeSettings = "afe_settings", worn, motion
    case continuousHR = "continuous_hr", sleepWake = "sleep_wake", bbi, bookends
    case ppgResults = "ppg_results"

    public var csvHeader: String   // the stream's CSV header line, no trailing "\n"
}
swift
try await sensorBio.getDevicePackets { batch in
    for (stream, rows) in batch.csv {
        let file = folder(for: batch.serialNumber).appending(path: "\(stream.rawValue).csv")
        try appendCreatingWithHeader(file, header: stream.csvHeader, rows: rows)   // throw if the write fails
    }
}
  • Nothing is deleted until your handler returns. The SDK deletes a page's data only after handler returns without throwing. If it throws — or the app is killed mid-page — the call stops (and rethrows your error), and that page comes back on the next call. Make the handler's write durable before it returns.
  • Call it whenever you like. With nothing stored it returns 0 without calling handler. Calls don't overlap: a second call waits for the first to finish.
  • Pages, not one blob. Each call delivers everything stored, one page and one band at a time (a page is about 1 MB of raw data, typically 4–14 MB of CSV). csv has no header lines, so pages append straight onto one file per stream: write stream.csvHeader once, when you create the file. A stream with no rows in a page has no entry.
  • The rows. The first column of every stream is ts(ns), nanoseconds since the Unix epoch. Rows of a stream arrive in the order the band recorded them, which is almost always — but not strictly — time order; sort on ts(ns) if you need it. Different streams are not in step with each other. ppg always carries all five channel columns (an absent channel is an empty field).
  • The newest samples arrive with the next sync. Each sensor's last second or two of samples is held until the band's next sync, when its timing becomes known. Nothing is lost; it is in a later page.
  • Storage is yours to manage. Data is kept only until it is delivered, but in offline mode it accumulates until you call. A day of continuous high-rate sensor capture can be tens of MB of raw data (hundreds of MB of CSV), so call it regularly — on app launch or a refresh, say.
  • Outside offline mode the data is uploaded instead, and the call returns 0. The one exception is the first call after offline mode is turned off: it delivers each band's final page, with isEndOfStream == true. Whatever was not yet delivered when offline mode turned off is uploaded.
  • Removing the band (removeDeviceFromPairedDevices) ends its stream. The next call delivers whatever of it was not yet delivered, then a final page with isEndOfStream == true that holds each sensor's last samples. A band added afterwards — the same one or another — starts a new stream.
  • Sign-out deletes undelivered data with every other on-device record.
  • Cost. Parsing is CPU-bound — on a desktop core, roughly 0.5–1 s per MB of raw sensor data — and runs off the main thread. Avoid a time-limited background task for a large backlog.

7.1 Dashboard ​

swift
public func fetchDashboardData(date: Date, tzOffset: Int32, forceRemote: Bool = false) async throws -> SB_DashboardData
public func dashboardUpdates(for date: Date, tzOffset: Int32, forceRemote: Bool = false) -> AsyncThrowingStream<SB_DashboardData, Error>

One read per day ⚠️ behavior change ​

dashboardUpdates is the only read a dashboard needs for a day: every value it yields is a whole SB_DashboardData — the server's payload plus the tiles the SDK adds from the device (skin temperature, stress index) — so a dashboard renders each value as it arrives and makes no getSkinTemperature or stress-gating read of its own. fetchDashboardData returns the same payload once.

  • A past day it has already assembled is one cached entry, served from the device's storage without a network call; the stream yields it and ends. The entry is replaced when data lands on the day — a sync or backfill of its HR / HRV / RR, activity, steps, sleeps, skin temperature or stress points — and on forceRemote: true, which yields the entry and then refetches. It is only kept once the server's payload for the day is final (fetched after the day ended).
  • Otherwise it yields the last cached payload first (its device tiles read from the device only, so the first paint never waits on the network), then the fresh value, as before.
  • Offline mode: both reads return the day assembled on the device (getDashboardData(date:)) instead of throwing SB_OfflineModeError.unavailable.

Each ring on the dashboard is an SB_DashboardCircularItem:

swift
public struct SB_DashboardCircularItem: Codable, Equatable, Sendable {
    public var value: Float
    public var processing: Bool     // server's own "still working" flag
}

value vs processing — read both. value is not guaranteed to be 0…100. The server sends -100 for a sleep it has recorded but never scored, and negative recovery values are a documented sentinel meaning "no real score for the day" (pair with SB_DashboardItemRecoveryStage.stageNotAvailable). Treat any non-positive value as "no score", and read processing for progress — the two are independent. Inferring progress from a missing or non-positive value is wrong: it cannot distinguish "recorded but unscoreable" from "still being worked on", and will leave a ring showing Processing forever.

The stress index tile (SB-2228) ⚠️ interface change ​

SB_DashboardMetricType has a new case, .stressIndexDashMetric (raw value 7). It is SDK-only: the server's dashboard has no stress value, so the SDK appends this tile to metrics itself, from its own continuous stress index day read. valueFloat is the day's latest reading (SB_StressIndexDay.latest.value), value is that rounded, title is "STRESS INDEX", valueUnit is "" and there is no footer. The tile is present exactly while the organization runs the continuous_stress_index algorithm on the mobile SDK — so it is also your row's show/hide signal — with value and valueFloat 0 for a day with no readings (render your row's empty state then, as for any server tile with no data). ⚠️ Earlier versions left the tile out for a day with no readings. A switch over SB_DashboardMetricType needs the new case.

Where the reading comes from:

ReadStress source
fetchDashboardData, any dayfetchStressIndex(date:); falls back to getStressIndex(date:) when it throws or returns nil (the server only has a point once the phone uploaded it). Past days are fetched too, so a day the device has no points for — every day, right after a logout → login — still gets its tile (SB-2550)
dashboardUpdates cached first valuegetStressIndex(date:) — on device, so the first paint never waits on the network
dashboardUpdates fresh valueas fetchDashboardData
getDashboardData (offline mode)getStressIndex(date:)

A stress failure never fails the dashboard read; the tile carries 0. The stress read runs alongside the server's dashboard request, not after it.

Caching. The tile is never written into the server payload's response cache. It is added on every call after the cached or fresh payload is resolved, so today's bad-internet fallback still carries the stress the device has now, and the cached first paint is never missing one. A past day's assembled entry (see One read per day) holds the tile, and is replaced when stress points land on the day.

The skin temperature tile ​

The SDK also appends a .temperatureDashMetric tile: the day's mean skin temperature, as getSkinTemperature(date:)'s average — valueFloat in Celsius, value that rounded, title "SKIN TEMPERATURE", valueUnit "°C", no footer. It is absent for a day with no temperature reading. Like the stress tile it is read from the device (falling back to the server when the device has nothing for the day), alongside the server's request, and never fails the read; the cached first paint reads the device only.

data.sleep is now populated whenever the server sends a sleep goal item, including when its value is non-positive (it was previously dropped to nil by a value > 0 gate). data.sleep != nil therefore no longer implies "there is a score" — check value > 0 for that, and use data.sleeps (the session list) to tell whether the server knows about any sleep session at all.

7.2 Activity reads ​

swift
public func fetchSteps(date: Date, granularity: SB_ViewGranularity, forceRemote: Bool = false)        async throws -> SB_StepsTrending
public func fetchCalories(date: Date, granularity: SB_ViewGranularity, forceRemote: Bool = false)     async throws -> SB_CaloriesTrending
public func fetchDailyActivityDetail(date: Date, granularity: SB_ViewGranularity, forceRemote: Bool = false, preferLocal: Bool = true) async throws -> SB_DailyActivityDetail
public func fetchDailyRecovery(date: Date, forceRemote: Bool = false, preferLocal: Bool = true) async throws -> SB_DailyRecoveryTrending
public func fetchRangeRecovery(date: Date, granularity: SB_ViewGranularity, forceRemote: Bool = false) async throws -> SB_RecoveryRangeTrending

fetchDailyRecovery is computed on-device where possible — see Local-first recovery score below. fetchRangeRecovery (week/month/year) is unchanged and stays server-served.

fetchDailyActivityDetail likewise, for .day — see Local-first activity detail below. .week / .month / .year stay server-served.

fetchDailyActivityDetail returns the activity score plus a per-metric breakdown — steps, calories burned, distance, and active time — each carrying chart datapoints. The metrics reuse SB_StepMetric (switch on metricType: .steps / .caloriesBurned / .distance / .totalDuration):

swift
public struct SB_DailyActivityDetail: Codable, Equatable, Sendable {
    public var score: SB_ActivityScore?
    public var metrics: [SB_StepMetric]
    public var isLocallyComputed: Bool       // true when this day was computed on-device
}

public struct SB_ActivityScore: Codable, Equatable, Sendable {
    public var score: Float                  // 0–100
    public var diffVsBaseline: Float
    public var diffVsLastGranularityValue: Float
    public var scoreDescription: String
    public var colorHex: String              // server-suggested; app may ignore
    public var progressPercentage: Float     // baseline-relative ring fill, NOT the score
}

fetchDailyRecovery / fetchRangeRecovery return the recovery score (via goalItem) plus the sleep-derived context that fed it. Both trending wrappers also carry the signed-in user's joinedDate (sourced from the profile, not the recovery payload) so the app can describe the averaging window:

swift
public struct SB_DailyRecoveryTrending: Codable, Equatable, Sendable {
    public var graph: SB_DailyRecoveryGraph?
    public var joinedDate: Date?             // from the user profile, nil if unknown
    public var isLocallyComputed: Bool       // true when this day's score was computed on-device
}

public struct SB_RecoveryRangeTrending: Codable, Equatable, Sendable {
    public var graph: SB_RecoveryRangeGraph?
    public var joinedDate: Date?             // from the user profile, nil if unknown
}

public struct SB_DailyRecoveryGraph: Codable, Equatable, Sendable {
    public var goalItem: SB_DashboardItemRecovery
    public var variationPercentage: Float
    public var sleepTimeSeconds: Float
    public var restingHr: Float
    public var scoreFactors: [SB_RecoveryScoreFactor]   // daily only
    public var nocturnalHrv: Float?          // ms; local path only, nil when server-served
}

public struct SB_RecoveryRangeGraph: Codable, Equatable, Sendable {
    public var goalItem: SB_DashboardItemRecovery
    public var variationPercentage: Float
    public var sleepTimeSeconds: Float
    public var restingHr: Float
    public var recoveryScoreSection: SB_RecoveryScoreSection?
}

Each contributing factor reports its percentile (0–100) and a pre-computed scoreValue — the factor's weighted contribution to the recovery score, i.e. percentile × weight under 0.4·HRV + 0.4·RHR + 0.1·Sleep Efficiency + 0.1·Sleep Duration. Colors are not returned; the app derives them from the percentile.

swift
public struct SB_RecoveryScoreFactor: Codable, Equatable, Sendable {
    public var title: String
    public var description: String
    public var percentile: Float             // 0–100 (e.g. a nocturnal-HRV percentile of 73)
    public var scoreValue: Float             // weighted points, e.g. 73 × 0.4 = 29.2
}

Local-first recovery score ​

fetchDailyRecovery(date:) / dailyRecoveryUpdates(for:) keep their signatures and their SB_DailyRecoveryTrending return, but the score behind them is now computed on-device whenever the night is on the device (SB-1682). Unlike the get…Points family this is not a new entry point — it is the same trending read with a local source, so no caller changes are required.

The daily recovery score ranks last night against the user's own recent nights (server GenerateRecoveryScore):

score = round(100 · (0.4·fracHRV + 0.4·fracBPM + 0.1·sleepGoalAchieved + 0.1·sleepEfficiency))
  • fracHRV / fracBPM — the share of the prior 30 days' nights whose resting HRV was no higher than last night's / whose resting BPM was no lower (both comparisons inclusive). Each night's resting values are derived from that night's on-device PPG with the same server-parity math the sleep detail uses (CalculateRestingBPM — the mean of the 5 lowest outlier-free BPM; CalculateRestingHRV — the residual-outlier-free OLS HRV-vs-time line evaluated at the last epoch);
  • sleepGoalAchieved — min(1, totalSleep / goal) against the user's locally-cached sleep goal (an unset goal scores full credit);
  • sleepEfficiency — totalSleep / (totalSleep + excessAwake + excessLatency), where awake time up to 5% of total sleep and latency up to 20 minutes are free. Both sleep terms read the same clamped stage minutes the local sleep detail reports.

The returned graph carries the ring score + stage (.restUp <30 · .goEasy <50 · .medium <60 · .ready <75 · .excellent ≥75) and its message, the night's resting HR and total sleep, the vs-average trend (variationPercentage, measured against the mean of the last 30 days' locally-computed scores — which is why the read gathers 60 days of nights: each of those 30 prior days ranks against its own 30 priors), and the four contributing factors in the server's order — Nocturnal HRV (0.4), Resting HR (0.4), Sleep Efficiency (0.1), Total Sleep Duration (0.1, the sleep-goal term despite the name) — each with its percentile and its weighted point contribution.

Missing nights are backfilled, not skipped. The score reads 61 nights: last night and the 60 before it. Any prior night this device can't supply all of the inputs for — it was never recorded here (before the device's history began, or on another phone), or its window is here without its HR, its HRV or its stage minutes (the partial day a fresh login leaves behind) — would otherwise drop out of the ranking or the average, or shrink a denominator, moving the score with nothing to signal it. Such a night is filled first: the read pulls that day's sleep list and the longest sleep's detail, HR and HRV from the server — raw data only, never the server's resting values or score — stores them, and computes the night's resting HR and HRV from them, the same way as a band night's. Last night itself is filled only when its window is already on the device; a day with no on-device night is not made scorable from the server. Each missing day is pulled once per signed-in session, shared with the sleep score's backfill, and later reads are local — so the first recovery read on a new device may make up to 60 days' worth of server reads (about four per day). In offline mode nothing is pulled and the score uses the nights the device has. A result computed while a night could not be filled (a failed read) is returned but not cached, so the next read tries that night again. The same read also fills a night whose HRV series is short of its HR series (fewer than half as many points: part of the night's HRV was never pulled), and once more a server night stored before the SDK kept the server's own stage totals. A server night is stored with the totals the server scores it with — asleep minutes from the detail's sleepTimeSec, the light / deep / REM split, total awake and latency from the detail's tiles — not totals summed from its stage intervals, which fall short of them.

The maths runs in the shared C library (SB_recoveryScore in mobile_edge_algorithms), the same code Android runs, checked bit for bit against the server's own recovery code.

The read falls back to the server for a day the device cannot score the server's way:

  • no on-device sleep for the day, or a night with a window but no stage minutes (such a night would evaluate both sleep terms to zero — a silent 20-point hole — so it is never scored, though it still counts as a prior, since it supplies resting values);
  • the night has no resting BPM or no resting HRV;
  • fewer than four prior nights with sleep / with resting BPM / with resting HRV — the server's five-nights-including-tonight gate. This window matters: the backend blends a population baseline to serve a real score on days 1–4, and that baseline is not on the device, so those days deliberately stay server-served rather than showing nothing.

nocturnalHrv carries the night's raw resting HRV in ms — the value, not the percentile the scoreFactors carry. The recovery payload has never had this, so a host wanting to show it had to make a second pair of sleep reads per day view just to recover one number; on the local path the score has already derived it, so it is surfaced for free. It is nil on the server-served path, where the host should fall back to the sleep detail's restingHrv (the same figure). Note that fallback genuinely needs the network for a server-backfilled night: the local sleep detail deliberately skips stage-less rows, since it cannot draw a stage timeline for a night the device never recorded.

SB_DailyRecoveryTrending.isLocallyComputed reports which source actually served the day, so a host can distinguish a genuine local score from a fallback rather than reporting the source it asked for. preferLocal: false (on both fetchDailyRecovery and dailyRecoveryUpdates) skips the on-device computation and reads the server's score; the default true keeps every existing caller local-first.

dailyRecoveryUpdates has no stale peek — unlike the other …Updates streams it does not pre-yield the last cached value. The local computation is fast enough to be the first emission, so peeking would paint a stale server score for a frame and then swap it. It yields once.

forceRemote applies to the fallback fetch only — it does not bypass the local computation, matching the rest of the offline-first family. Factor titles and stage messages are the SDK's own English strings (the server's are localized server-side) — the same trade-off the local sleep score makes.

The dashboard's recovery ring comes from a different read (fetchDashboardData), not this one, and is still server-served.

Local-first activity detail ​

fetchDailyActivityDetail(date:granularity:) / dailyActivityDetailUpdates(for:granularity:) keep their return type, but a .day read is now rebuilt on-device from the day's activity rows (SB-1684) — score, baseline comparison and all four metrics. As with the recovery score this is not a new entry point, so no caller changes are required.

The daily activity score is a pure function of one day (server GenerateActivityScore) — no history, no statistical aggregation, no calibration, and so (unlike recovery) no gate it can fail:

score = round(100 · (0.8·min(1, activeCals/caloriesGoal) + 0.2·min(1, activeHours/12)))
  • activeCals — the day's active calories, max(0, Σ totalStepCalories + Σ workoutCalories − Σ workoutStepCalories) over the day's per-minute rows, as the calories read builds them — including the backend's per-minute round(steps/10) step-calorie cap, which the server applies in its DB row scan and skips for workout minutes. The minutes are summed signed and only the day's total is floored, as the server's score does, so a workout minute the HR model scores below resting takes calories off the day. That makes it the calories read's Active total (SB_CaloriesDataPoints.totalActiveCalories) except on such days, where it is lower: Active floors each minute, as the server's calorie graph does. It is deliberately not SB_StepsDataPoints.totalCalories, which caps every minute including workout ones;
  • activeHours — local hours with more than 250 steps (strictly greater), off the same hourly buckets the steps read exposes;
  • caloriesGoal — the user's active-calorie goal, cached locally from fetchGoals() / updateGoals(…), with the server's 500 default substituted for an unset goal. Because the goal is the score's divisor rather than a soft term, a cold cache is warmed once per process from fetchGoals() rather than silently scoring against the default. The score and the baseline comparison are computed in the shared C library (SB_activityScore / SB_activityBaseline in mobile_edge_algorithms), the same code on both platforms, checked bit for bit against the server's own Go.

The ring's fill is not the score: the server publishes progressPercentage relative to a rolling baseline, and diffVsBaseline alongside it. Both are reproduced — the baseline is the same score recomputed for each of the prior 30 days and averaged, published only once 5 prior days have a score, matching the server's gate (below that the server omits progressPercentage too, and a host falls back to the raw score). progressPercentage is a full 100 at or above the baseline and the shortfall as a percentage below it (server util.CalculateProgressPercentage with no goal — activity has no goal term, the baseline IS the target). A prior day this device has no activity rows for — before its history began, or recorded on another phone — is filled first: the read pulls that day's steps and calories from the server (raw data only, the same reads the scored day's own backfill uses), stores them, and scores the day from them, so the average covers the same days as the server's. Each missing day is pulled at most once per signed-in session, six at a time, so the first read on a new device may make up to 30 days' worth of server reads (two per day); later reads are local. A day the server has nothing for either does not contribute, which is how the server treats a date with no stored score. In offline mode nothing is pulled and the baseline uses the days the device has. A result computed while a day could not be filled (a failed read) is returned but not cached, so the next read tries that day again.

The Sensor Bio app fills its activity ring from score, not progressPercentage, so the baseline is reproduced here for API parity with the server payload (and with Android) rather than because the shipping app needs it.

The four metrics — Calories, Duration, Distance, Steps, in the server's order — carry their day total in avgValue and hourly timeDatapoints in the API's wall-clock-encoded-as-UTC convention. .distance is emitted in the user's display unit (km, or miles for an imperial profile, rounded to two decimals), as the API sends it; every other metric is SI. name / unit / barChartTitle are left empty — those are localized server-side and the SDK owns no strings, so a host that shows them supplies its own (the app does, in ActivityMetricFormat).

The read falls back to the server when the day has no activity rows on device even after a backfill attempt, and always for .week / .month / .year — those periods average the server's stored daily scores and aggregate from its rollup tables, which the device does not reproduce.

SB_DailyActivityDetail.isLocallyComputed reports which source actually served the day, so a host can distinguish a genuine local score from a fallback rather than reporting the source it asked for. preferLocal: false (on both fetchDailyActivityDetail and dailyActivityDetailUpdates) skips the on-device computation and reads the server's payload; the default true keeps every existing caller local-first.

As with recovery, dailyActivityDetailUpdates has no stale peek on the local .day path (it yields once) while the range granularities keep theirs, and forceRemote applies to the fallback fetch only — it does not bypass the local computation.

Org custom / white-label activity scoring stays server-computed.

7.3 Biometric reads — HR / HRV / RR · SpO2 🚧 WIP ​

swift
public func fetchDailyHR(date: Date, forceRemote: Bool = false)                                       async throws -> SB_BiometricDailyTrending
public func fetchRangeHR(date: Date, granularity: SB_ViewGranularity, forceRemote: Bool = false)      async throws -> SB_HRRangeTrending
public func fetchDailyHRV(date: Date, forceRemote: Bool = false)                                      async throws -> SB_BiometricDailyTrending
public func fetchRangeHRV(date: Date, granularity: SB_ViewGranularity, forceRemote: Bool = false)     async throws -> SB_HRVRangeTrending
public func fetchDailyRR(date: Date, forceRemote: Bool = false)                                       async throws -> SB_BiometricDailyTrending
public func fetchRangeRR(date: Date, granularity: SB_ViewGranularity, forceRemote: Bool = false)      async throws -> SB_RRRangeTrending

// 🚧 WIP
public func fetchDailySpO2(date: Date, forceRemote: Bool = false)                                     async throws -> SB_BiometricDailyTrending
public func fetchRangeSpO2(date: Date, granularity: SB_ViewGranularity, forceRemote: Bool = false)    async throws -> SB_SpO2RangeTrending

One daily shape for all four metrics (SB-1737) ⚠️ breaking ​

All four daily reads return the same SB_BiometricDailyTrending; the per-metric SB_HRDailyTrending / SB_HRVDailyTrending / SB_RRDailyTrending / SB_SpO2DailyTrending and their four graph types are gone. The metric is identified by the call you made, not by the type. Range reads keep their per-metric types — those graphs genuinely differ.

swift
public struct SB_BiometricDailyTrending: Codable, Equatable, Sendable {
    public var graph: SB_BiometricDailyGraph?          // nil when the day has no processed data
}

public struct SB_BiometricDailyGraph: Codable, Equatable, Sendable {
    public var resting: Float                          // HR: resting HR · HRV: RMSSD · RR/SpO2: nocturnal average
    public var average: Float                          // whole-day mean, sleep included
    public var lowest: Float
    public var highest: Float
    public var baseline: Float                         // 30-day median, server-computed
    public var points: [SB_BiometricPoint]             // ascending by timestamp
    public var linearFit: SB_TimeValueStraightLine?    // recovery-rate fit; HRV-only today
}

public struct SB_BiometricPoint: Codable, Equatable, Sendable {
    public var timestamp: Int64                        // absolute ms epoch
    public var value: Float
    public var valueType: SB_BiometricValueType        // sleep / awake / outlier / abnormal-rhythm
}

Migrating:

wasnow
graph.restingBpm / .rMssd / .brpm / .spo2graph.resting
graph.rawAvg / .rawLowest / .rawHighest / .rawBaselinegraph.average / .lowest / .highest / .baseline
graph.heartRateTimeseriesPointsgraph.points
graph.rawSleepPoints + graph.rawDatetimePoints (and the …HrvPoints pair)graph.points, split by valueType (.sleep / .awake)
graph.tzOffset, point.timezoneremoved — timestamp is an absolute ms epoch; render it in the viewer's own zone
graph.startTimestampremoved — derive the axis start as min(localMidnight, floorToHour(points.first))
graph.improvementVsBaselineremoved — compute resting - baseline, sign-flipped where lower is better (HR, RR); 0 when baseline <= 0
SB_HeartRateValueType / SB_HRVValueTypeSB_BiometricValueType (HR's case list; HRV's .hrvOutlier maps to .sleepOutlier)
SB_HeartRateTimeValuePoint / SB_HRVTimeValuePointSB_BiometricPoint
line.lineColor (SB_LineColor)line.rating (SB_ImprovementRating) — pick your own colours

SB_TimeValuePoint also loses timezone, so every graph that carries those points (sleep biometrics, workout, activity, meditation, spot check) now hands back (timestamp, value) only.

Range graphs lose improvementVsBaseline too, spell Avg out (averageBpm / average / averageBrpm / averageSpo2, rolling7DayAverage), and SB_HRVRangeGraph.rawBaseline is dropped as a duplicate of baseline.

Cached responses from an older build fail to decode once, are deleted, and refetch — no migration step needed.

Local-first HR points ​

getHRPoints(date:) returns a day's HR samples local-first: it reads the day's on-device HR with no API round-trip when that data is already synced locally. Each point is tagged .awake / .asleep from the device's sleep sessions. Only when the day predates local sync (no local HR for the window) does it fall back to the API, backfill the HR + sleep locally, and rebuild — so a subsequent call for the same day is served entirely from the device.

The day a sample belongs to, and whether it counts as asleep, follow the server's daily-trending contract exactly (SB-1994). A day is local midnight→midnight plus the full [onset, wakeUp] span of every sleep filed under that day — and a sleep is filed under the day it ends, not the day it began. So for a 10pm→7am night:

  • asking for the wake day returns samples starting at 10pm the previous evening, all tagged .asleep;
  • asking for the day that night started returns midnight→midnight only, and its 10pm→midnight block is tagged .awake, because the sleep covering it belongs to the next day.

A point is .asleep iff it falls inside one of that day's own sleeps — not merely inside any sleep. Callers that plot these points must let the x-axis start before midnight, since the first sample routinely does.

The three resting figures (restingHR / restingHRV / restingRR) follow the server's other rule: each is derived from the day's longest sleep alone, by that metric's own algorithm — not by averaging the day's .asleep samples. A day with a nap therefore has one set of sleeps driving the point tags and a single, narrower window driving the headline number.

swift
public func getHRPoints(date: Date) async throws -> SB_HRDataPoints

public struct SB_HRDataPoints: Codable, Equatable, Sendable {
    public let points: [SB_HRDataPoint]
    // Server-parity resting HR (`CalculateRestingBPM`): the mean of the 5 lowest
    // outlier-free samples of the day's LONGEST sleep — not a mean of the .asleep
    // points. nil when the day has no sleep, or fewer than 5 usable samples in it.
    public let restingHR: Int?
    // Computed on the fly from `points`; each is nil when `points` is empty.
    public var averageHR: Int?   // mean value of all points
    public var lowestHR: Int?    // min value
    public var highestHR: Int?   // max value
}

public struct SB_HRDataPoint: Codable, Equatable, Sendable {
    public let epoch: Int64          // ms
    public let value: Int            // bpm, rounded from the stored Float
    public let type: SB_HRPointType
}

public enum SB_HRPointType: Codable, Equatable, Sendable {
    case awake
    case asleep
}

throws only on the server-backfill path (e.g. SB_AuthError.missingAuthToken when signed out); the pure-local path never touches the network.

Local-first HRV points ​

getHRVPoints(date:) is the HRV sibling of getHRPoints(date:): it returns a day's HRV samples local-first, reading the day's on-device HRV with no API round-trip when that data is already synced locally. HRV shares the same per-epoch PPGResult rows as HR (its own hrvValue/hrvValid slot). Each point is tagged .awake / .asleep from the device's sleep sessions, over the same day window and sleep-filing rule as getHRPoints(date:) — see above. Only when the day predates local sync (no local HRV for the window) does it fall back to the API, backfill the HRV + sleep locally, and rebuild — so a subsequent call for the same day is served entirely from the device.

swift
public func getHRVPoints(date: Date) async throws -> SB_HRVDataPoints

public struct SB_HRVDataPoints: Codable, Equatable, Sendable {
    public let points: [SB_HRVDataPoint]
    // Server-parity nocturnal HRV (`CalculateRestingHRV`): the residual-filtered
    // regression line over the day's LONGEST sleep, read off at that night's last
    // epoch — not a mean of the .asleep points. nil when the day has no sleep, or
    // that sleep has too little HRV to fit.
    public let restingHRV: Int?
    // Computed on the fly from `points`; each is nil when `points` is empty.
    public var averageHRV: Int?         // mean value of all points (day average)
    public var lowestHRV: Int?          // min value
    public var highestHRV: Int?         // max value
}

public struct SB_HRVDataPoint: Codable, Equatable, Sendable {
    public let epoch: Int64          // ms
    public let value: Int            // rMSSD in ms, rounded from the stored Float
    public let type: SB_HRPointType  // .awake / .asleep (shared with HR)
}

throws only on the server-backfill path (e.g. SB_AuthError.missingAuthToken when signed out); the pure-local path never touches the network.

Local-first RR points ​

getRRPoints(date:) is the respiratory-rate sibling of getHRPoints(date:) / getHRVPoints(date:): it returns a day's RR samples local-first, reading the day's on-device RR with no API round-trip when that data is already synced locally. RR shares the same per-epoch PPGResult rows as HR/HRV (its own rrValue/rrValid slot). Each point is tagged .awake / .asleep from the device's sleep sessions, over the same day window and sleep-filing rule as getHRPoints(date:) — see above. Only when the day predates local sync (no local RR for the window) does it fall back to the API, backfill the RR + sleep locally, and rebuild — so a subsequent call for the same day is served entirely from the device.

Unlike HR/HRV (whole-number Int), RR is inherently fractional, so every RR value — each point and every aggregate — is an unrounded Float in breaths per minute (brpm), matching the API day chart's own brpm values.

swift
public func getRRPoints(date: Date) async throws -> SB_RRDataPoints

public struct SB_RRDataPoints: Codable, Equatable, Sendable {
    public let points: [SB_RRDataPoint]
    // Nocturnal RR: the sleep's own Brpm over the day's LONGEST sleep, to one
    // decimal — the median of its captures less any that are resting-HR or HRV
    // outliers, which is the server's uncertainty-weighted mean for captures
    // uploaded (as the SDK uploads them) with no uncertainty. Not a mean of the
    // .asleep points. nil when the day has no sleep, or that sleep carries no RR.
    public let restingRR: Float?
    // Computed on the fly from `points`; each is nil when `points` is empty.
    public var averageRR: Float?         // mean value of all points (day average)
    public var lowestRR: Float?          // min value
    public var highestRR: Float?         // max value
}

public struct SB_RRDataPoint: Codable, Equatable, Sendable {
    public let epoch: Int64          // ms
    public let value: Float          // breaths per minute (brpm), unrounded from the stored Float
    public let type: SB_HRPointType  // .awake / .asleep (shared with HR)
}

throws only on the server-backfill path (e.g. SB_AuthError.missingAuthToken when signed out); the pure-local path never touches the network.

Local-first Steps points ​

getStepsPoints(date:) returns a day's step intervals local-first: it reads the day's on-device steps (local midnight→midnight in the device time zone) with no API round-trip when that data is already synced locally. Steps live in their own EnginePacket table (steps / distance / calories / active-seconds columns), not the vitals' PPGResult, so there is no awake/asleep tag — each point is a per-interval activity reading. Only when the day predates local sync (no local steps for the window) does it fall back to the API, backfill the intervals locally (server rows marked already-uploaded), and rebuild — so a subsequent call for the same day is served entirely from the device.

The returned SB_StepsDataPoints computes the day totals and hourly buckets on the fly. Unlike the vitals aggregates these are non-optional (steps are counts, not a distribution) and default to 0; use points.isEmpty to distinguish "no data on device" from a genuine zero-step day. Locally-synced points are per-minute, server-backfilled points per-hour; both aggregate identically.

swift
public func getStepsPoints(date: Date) async throws -> SB_StepsDataPoints

public struct SB_StepsDataPoints: Codable, Equatable, Sendable {
    public let points: [SB_StepsDataPoint]
    // Computed on the fly from `points`; non-optional, 0 when there are no points.
    public var totalSteps: Int
    public var totalDistanceMeters: Float
    public var totalCalories: Float
    public var totalActiveSeconds: Int
    public var hourlyBuckets: [SB_StepsHourBucket]  // one per hour with points (gaps omitted)
}

public struct SB_StepsDataPoint: Codable, Equatable, Sendable {
    public let epoch: Int64          // ms
    public let steps: Int
    public let distanceMeters: Float
    public let calories: Float       // kcal, after the backend's per-minute round(steps/10) cap
    public let activeSeconds: Int
}

public struct SB_StepsHourBucket: Codable, Equatable, Sendable {
    public let hour: Int             // local hour of day 0…23
    public let steps: Int
    public let distanceMeters: Float
    public let calories: Float
    public let activeSeconds: Int
}

throws only on the server-backfill path (e.g. SB_AuthError.missingAuthToken when signed out); the pure-local path never touches the network.

Local-first Calories points ​

getCaloriesPoints(date:) is the calories sibling of getStepsPoints(date:): it returns a day's calorie intervals local-first, reading them from the same on-device EnginePacket rows as steps (so there is no awake/asleep tag). It faithfully recreates the server's per-PhysicalStats-row calorie model — each interval's totalStepCalories is the active calories the band measured, split into a step and a workout part (active = step + workout). The band never reports the split on device, so it is reconstructed: on a locally-synced day from the day's activities, with each activity minute's calories recomputed from HR using the server's own per-minute model, and on a backfilled day from the server calories graph's authoritative per-hour split. Only when the day predates local sync does it fall back to the API — one shared steps + calories backfill (server rows marked already-uploaded) — then rebuild, so a subsequent call for the same day is served entirely from the device.

The calculation always runs on device. The SDK reaches the network only for inputs it does not hold, never for a server-computed calorie figure — which is why the number is reproducible offline once the inputs are cached. Two inputs are fetched and cached on demand (SB-2016):

  • The day's activity list. Activity windows used to come only from recordings made on this device since the last sign-out, so a workout recorded on another phone — or before a logout or reinstall — was invisible and its calories silently read as 0. The day's activity list is now fetched once from the server and cached on device, then merged with the local recordings (the local copy wins where both describe the same activity, since only it knows the pauses). A completed past day's cached list is final; today's is refreshed at most every 15 minutes, and a recording made on this device appears immediately without any refresh.
  • The HR those activities need. When an activity window holds no on-device HR at all — the normal case for a workout recorded elsewhere — the day's HR is pulled into the local store through the same backfill the HR read uses.

The derived per-minute attribution is kept in its own table and joined against the packets at read time. The band's packets are never rewritten: sensor data is not overwritten with a derived value, which is also what keeps a server-authored split distinguishable from a computed one. The attribution is re-derived from its inputs on every read, so it can never serve a stale answer.

Two known divergences from the server on an activity that was not recorded on this device, both of them limits of what the phone can ask for rather than defects in the model:

  • HR density. The server scores workout minutes from a per-second trace (activity_biometrics) that this app uploads but that has no read endpoint. The densest HR the phone can fetch back is the ~2-minute PPG trace behind the daily HR graph, so a minute with no sample in it is left unscored rather than filled in from a neighbour — a synthesized sample would be a number nobody measured. A remote activity can therefore read low, in proportion to how much of its HR is missing. Adding a read endpoint for the per-second trace is what would close this.
  • Pauses. WorkoutDetail carries a pause_segments field that the server never populates for a workout, so a remote activity's pauses are not knowable and its HR is fed to the model unfiltered. A paused remote activity therefore reads slightly high. An activity recorded on this device has its pauses exactly, and an activity with no pause has nothing to exclude.

Both the dashboard calories tile and the calories detail screen read the same SB_CaloriesDataPoints instance — the tile takes totalActiveCalories, the detail screen builds its metric list from the same value — so the two cannot disagree.

The returned SB_CaloriesDataPoints computes the five day totals and hourly buckets on the fly, plus a day-level restingCalories (the user's BMR over the elapsed part of the day — full BMR for a completed past day, BMR × elapsed/86400 for today, 0 when weight/height are unknown). totalCalories = totalActiveCalories + restingCalories; totalActiveCalories drives the calories ring. These aggregates are non-optional and default to 0; use points.isEmpty && restingCalories == 0 to distinguish "no data on device" from a genuine zero-calorie day. Locally-synced points are per-minute, server-backfilled points per-hour; both aggregate identically. (Ported to match Android's local-first calories, SB-1663.)

swift
public func getCaloriesPoints(date: Date) async throws -> SB_CaloriesDataPoints

public struct SB_CaloriesDataPoints: Codable, Equatable, Sendable {
    public let points: [SB_CaloriesDataPoint]
    public let restingCalories: Float       // kcal, day-level BMR over the elapsed day
    // Computed on the fly from `points`; non-optional, 0 when there are no points.
    public var totalStepCalories: Float     // server "Steps" tile
    public var totalWorkoutCalories: Float  // server "Workout" tile
    public var totalActiveCalories: Float   // server "Active" tile = step + workout; drives the ring
    public var totalCalories: Float         // server "Total" tile = active + resting
    public var hourlyBuckets: [SB_CaloriesHourBucket]  // one per hour with points (gaps omitted)
}

public struct SB_CaloriesDataPoint: Codable, Equatable, Sendable {
    public let epoch: Int64          // ms
    public let stepCalories: Float   // kcal (server: totalStepCalories − workoutStepCalories)
    public let workoutCalories: Float // kcal
    public var activeCalories: Float // step + workout
}

public struct SB_CaloriesHourBucket: Codable, Equatable, Sendable {
    public let hour: Int             // local hour of day 0…23
    public let stepCalories: Float
    public let workoutCalories: Float
    public var activeCalories: Float // step + workout
}

throws only on the server-backfill path (e.g. SB_AuthError.missingAuthToken when signed out); the pure-local path never touches the network.

Continuous stress index (SB-2228) ⚠️ interface change ​

Now public in the binary (it was internal-only). The SDK computes one stress index per PPG block on device when the organization runs the continuous_stress_index algorithm, uploads it, and reads it back by day.

swift
public func getStressIndex(date: Date) async -> SB_StressIndexDay?              // the day's points + values, read on device; nil when none
public func fetchStressIndex(date: Date) async throws -> SB_StressIndexDay?     // the server's day (GetStressIndex), stored locally; nil when none

public struct SB_StressIndexDay: Equatable, Sendable {
    public let latest: Point             // the newest point — the dashboard's .stressIndexDashMetric value
    public let min: Double
    public let max: Double
    public let sleepAverage: Double?     // mean of the .asleep points; nil when none
    public let daytimeAverage: Double?   // mean of the .awake points; nil when none
    public let points: [Point]           // oldest first, never empty

    public struct Point: Equatable, Sendable {
        public let epoch: Int64          // the PPG block start, unix ms
        public let value: Double
        public let type: SB_HRPointType  // .asleep inside one of the day's sleeps, else .awake
    }
}

SB_StressIndexDay is a day's continuous stress index: points, oldest first, each tagged .asleep / .awake against the same day window and sleeps as getHRPoints(date:), and five values the SDK calculates from those non-zero points (SB-2417). A day with no points has no SB_StressIndexDay at all (nil); zeros never count. getStressIndex(date:) never touches the network. fetchStressIndex(date:) reads the day's points from the server instead; the five values are still calculated by the SDK from them (the server's own stats are not used), and its day is the calendar day in each point's offset (so it leaves out last night's pre-midnight points, which getStressIndex includes). Every fetched point is written to the local store as uploaded, so it is never sent back up and a later getStressIndex of that day has it on device; a point already stored keeps its value. When the device has no sleep filed under the day (a past day right after a logout → login, say), it fetches and stores the day's sleeps first, so its points are tagged .asleep / .awake against them rather than all .awake; a failed sleep fetch never fails the stress fetch (SB-2550). It throws SB_AuthError.missingAuthToken when signed out, SB_OfflineModeError.unavailable in offline mode, or the transport error.

For the dashboard's latest value you don't need these: the dashboard read already carries it as the .stressIndexDashMetric tile (see 7.1). Use them for a stress detail screen.

On-device SpO2 and skin temperature (SB-1433) ⚠️ interface change ​

getSpO2(date:) reads a day from the device only, and getSkinTemperature(date:) reads it local-first (see Skin temperature reads). Neither throws, both keep working in offline mode (where getSkinTemperature makes no network call either), and each returns nil when the day has no readings. Both are day only; fetchRangeSpO2 and fetchRangeTemperature are the server week / month / year reads.

  • SpO2 aggregates the SpO2 slot of the local PPGResult rows (the same per-epoch rows as HR / HRV / RR). Only readings the band flagged valid and greater than zero count. Values are percent.
  • Skin temperature aggregates the local temperature rows, falling back to the server only for a day with none on the device. Values are Celsius; converting for display is the host's job.

The day is the same window as getHRPoints(date:) and getStressIndex(date:): local midnight to midnight, plus the full span of every sleep filed under that day (see Local-first HR points). The first point is therefore often from the evening before, when last night began before midnight, and min / max / average include that pre-midnight sleep.

Each point is tagged with type: .asleep when it falls inside one of that day's sleeps, otherwise .awake, exactly as the HR and stress index points are. Point.init now takes type, which breaks any code that builds these points itself.

swift
public func getSpO2(date: Date) async -> SB_SpO2?
public func getSkinTemperature(date: Date) async -> SB_SkinTemperature?

public struct SB_SpO2: Sendable {
    public let min: Float        // percent
    public let max: Float        // percent
    public let average: Float    // mean of every point, percent
    public let points: [Point]   // ascending by epoch

    public struct Point: Sendable {
        public let epoch: Int64            // ms
        public let value: Float            // percent
        public let type: SB_HRPointType    // .asleep / .awake
    }
}

public struct SB_SkinTemperature: Codable, Equatable, Sendable {
    public let min: Float        // Celsius
    public let max: Float        // Celsius
    public let average: Float    // mean of every point, Celsius
    public let points: [Point]   // ascending by epoch

    public struct Point: Codable, Equatable, Sendable {
        public let epoch: Int64            // ms
        public let value: Float            // Celsius
        public let type: SB_HRPointType    // .asleep / .awake
    }
}

SB_SkinTemperature and its Point are now also Codable and Equatable (additive), since SB_DailyTemperatureTrending carries the same Point.

The on-device dashboard (getDashboardData(date:)) fills its SpO2 tile the way the server's tile is filled, not from getSpO2's average: metricType .spo2DashMetric, title "SPO2", valueUnit "%", valueFloat the SpO2 of the day's longest sleep (the median of its captures, less resting-HR and HRV outliers), or of the whole day when it has no sleep, rounded to a whole number. When that window has no valid reading it falls back to getSpO2's day average; the tile is absent for a day with no reading at all. Its footer is the SpO2 baseline's improvementVsBaseline.

fetchDailySpO2(date:) now also stores the day's points on the device, as fetchDailyHR / fetchDailyHRV / fetchDailyRR already did, so getSpO2 and the baselines can read a server day afterwards. getSpO2 itself still reads the device only.

Biometric baselines ⚠️ interface change ​

swift
public func getBiometricBaselines(date: Date) async -> SB_BiometricBaselines

public struct SB_BiometricBaselines: Codable, Equatable, Sendable {
    public let restingHR: SB_BiometricBaseline?        // nil: no baseline (see below)
    public let restingHRV: SB_BiometricBaseline?
    public let respiratoryRate: SB_BiometricBaseline?
    public let spo2: SB_BiometricBaseline?
}

public struct SB_BiometricBaseline: Codable, Equatable, Sendable {
    public let baseline: Float                // whole number; respiratory rate to one decimal
    public let value: Float?                  // the day's value as its dashboard tile shows it
    public let improvementVsBaseline: Float?  // value − baseline, positive = better; nil without a value
}

A day's resting HR, HRV, respiratory rate and SpO2 against their 30-day baselines, computed on the device the way the server's dashboard computes them:

  • Baseline: the median of the metric over the 30 days before date (the day itself is not one of them), counting only days that have a sleep and a reading. Fewer than 5 such days and that metric is nil. The per-day values are the longest sleep's resting HR / HRV (as getHRPoints / getHRVPoints compute restingHR / restingHRV) and the whole day's respiratory rate / SpO2 (the median of all of that day's captures, asleep or not).
  • value: resting HR and HRV of the day's longest sleep, rounded; respiratory rate (one decimal) and SpO2 (whole number) of that sleep, or of the whole day when it has no sleep. nil when the day has none.
  • improvementVsBaseline: the server's improvement_vs_baseline — value − baseline rounded at the second decimal the server's way, signed so a positive number is an improvement (a resting HR or respiratory rate below its baseline is positive).

Each prior day's respiratory-rate and SpO2 points are first merged from the server (once per session, for every day — a day the band also synced to another phone is only partly on this one), and a day the device is otherwise missing — before this phone's history, or recorded elsewhere — is filled from the server's raw points (the sleep, and that day's HR, HRV, respiratory rate and SpO2), so the first read after a fresh install can take a while; later reads are cached until one of those 30 days changes. Under offline mode nothing is fetched and the baselines come from what the device holds. The server's own baselines are never read. Never throws.

getDashboardData(date:) puts these in its tile footers: the resting HR, HRV, respiratory-rate and SpO2 tiles carry .improvementVsBaseline(x) when the metric has a baseline and the day a value, and .unset otherwise (steps, active calories and the stress index stay .unset). Its respiratory-rate tile falls back to the whole day's value when the day has no sleep, as the server's does.

Skin temperature reads ​

swift
public func getSkinTemperature(date: Date) async -> SB_SkinTemperature?
public func fetchDailyTemperature(date: Date, forceRemote: Bool = false)                                   async throws -> SB_DailyTemperatureTrending
public func fetchRangeTemperature(date: Date, granularity: SB_ViewGranularity, forceRemote: Bool = false)  async throws -> SB_TemperatureRangeTrending

All temperatures are Celsius.

getSkinTemperature(date:) is local-first ⚠️ behaviour change. It is served from the device whenever the day has any temperature on it, exactly as before. Only when the device has none for the day (a day from before this phone synced, or right after a logout → login) does it fetch the day from the server (fetchDailyTemperature), store every fetched point on the device, fetch and store the day's sleeps so the points are tagged .asleep / .awake against them, and read the device again — so the next call for that day makes no network call. Like getHRPoints, any day can be filled this way, today included; a reading the band recorded is never overwritten. Points stored from the server are marked already uploaded, so they are never sent back up. The signature is unchanged and it still never throws: when the fallback fails (signed out, no network, server error) it returns nil. In offline mode the fallback is skipped.

fetchDailyTemperature(date:) reads the day from the server (GetDailyTemperatureTrendingGraph), built in the device's UTC offset on date. Cache-backed like the other daily reads, keyed on the date and that offset (forceRemote bypasses the cache). All of its timestamps are unix ms; an epoch the server sends in seconds is converted. Every fetched point is also written to the device as already uploaded, so a later getSkinTemperature of that day is served on device.

fetchRangeTemperature(date:granularity:) reads the week / month / year ending on date (GetTemperatureTrendingGraph) as two series: sleep, each date's nightly sleep-time temperature, and daily, each date's whole-day average. granularity must be .week, .month or .year — the server rejects .day (use fetchDailyTemperature), which surfaces as the transport error.

swift
public struct SB_DailyTemperatureTrending: Codable, Equatable, Sendable {
    public var points: [SB_SkinTemperature.Point]   // ascending by epoch (unix ms); .asleep where the server labels SLEEPING, else .awake
    public var startTimestamp: Int64                // local midnight of the date, unix ms
    public var endTimestamp: Int64                  // next local midnight, clamped to now, unix ms
    public var tzOffset: Int32                      // UTC offset the day was built in, minutes
    public var average: Float                       // mean of every point; 0 when there are none
    public var lowest: Float
    public var highest: Float
    public var latest: Float                        // most recent point; 0 when there are none
    public var baseline: Float?                     // 30-day whole-day baseline before the date; nil until established
    public var vsBaseline: Float?                   // average − baseline, one decimal; nil without a baseline or points
    public var sleepAverage: Float?                 // the night's temperature; nil without a sleep or sleep points
    public var awakeAverage: Float?                 // mean of the .awake points; nil when none
}

public struct SB_TemperatureRangeTrending: Codable, Equatable, Sendable {
    public var sleep: SB_TemperatureTrendingGraph   // nightly sleep-time temperature per date
    public var daily: SB_TemperatureTrendingGraph   // whole-day average per date
}

public struct SB_TemperatureTrendingGraph: Codable, Equatable, Sendable {
    public var graph: SB_WMYChart?                       // mainPoints = one value per date; nil when the server sent none
    public var average: Float                            // mean over the period
    public var baseline: Float?                          // nil until established — never a placeholder value
    public var improvementVsBaseline: Float?             // average − baseline; nil whenever baseline is
    public var improvementCorrelatesDirectlyWithChange: Bool
    public var changeVsPriorPeriod: Float?               // average − the previous 7 / 30 / 365 days' average
}

Baselines. A baseline is only ever a real value: nil until the server has enough days to establish one (the range graph sends a placeholder below 5 dates with a value, which the SDK drops), and its comparison (vsBaseline / improvementVsBaseline) is nil with it.

A rise is not an improvement. improvementCorrelatesDirectlyWithChange is false for skin temperature: colour a positive improvementVsBaseline (or vsBaseline) the way you would a negative change for HRV.

7.4 Sleep reads ​

swift
public func fetchSleepDetail(endDate: Date, endTimestamp: Int64, forceRemote: Bool = false)                     async throws -> SB_SleepDetailDay
public func fetchSleepAggregation(date: Date, granularity: SB_ViewGranularity, forceRemote: Bool = false)      async throws -> SB_SleepDetailAggregated

Local-first sleep detail ​

getSleepDetail(date:sessionEndTimestamp:) is the sleep member of the local-first family — same contract as the vitals reads, but sleep is stored on-device as sessions (the on-device sleep-session rows) rather than a per-epoch timeseries, so instead of a bespoke points container it returns the same SB_SleepDetailDay fetchSleepDetail returns. The sleep-detail screen renders it unchanged. Two paths:

  • On-device day (a device-recorded session with stages exists): the detail is rebuilt entirely from the local row — no API round-trip — with all the server-parity math below. A row is only surfaced once it has settled with the server and if its window is well-formed (positive start→end and positive onset→wakeUp); a not-yet-uploaded sleep is deliberately withheld so the local list matches server-first session-for-session, and a degenerate row — the sleep detector can persist one with start == end and a wakeUp before its onset, which the server rejects and never stores — is dropped rather than rendered as a 0-minute session.
  • Old day (no on-device sleep — it predates local sync): a server-backed read, like the vitals do — it fetches the day's server sleep, persists every session's window locally (marked already-uploaded; there may be several sleeps in a day, and the windows let the vitals reads tag against them), and returns the chosen session's full server SB_SleepDetailDay (server stages / score / factors / penalties / biometrics / disturbances). So old days show the real sleep rather than an empty shell.

nil when neither the device nor the server has sleep for the day.

A session is attributed to the day it wakes up — it may start the previous evening (or be a nap fully inside the day), but a session that starts in the day and wakes the next belongs to the next day, so an overnight sleep isn't double-counted on both days. Without sessionEndTimestamp the day's longest session (most time asleep) is surfaced.

A night the band recorded in pieces is one session (SB-2436). The band often ends a sleep on a wake and starts another when the user settles again; the server joins those into one sleep, and so do the local reads, with the server's rules: sleeps that overlap or sit less than 60 minutes apart are merged when they end on the same date, and when a date's first sleep starts before 01:00 the previous date's last sleep can join it too (so a night split across midnight is one night, filed under the morning). The merged night keeps the first piece's start and onset and the last piece's wake-up; its SB_SleepItem.end is the last piece's end + 1 s, as on the server. Each gap between pieces counts as awake — in Total Awake, Awakenings, the score and the stage timeline — but, as on the server, not in the stage percentages. The resting HR / HRV, graphs and arm disturbances are read over the whole night, gaps included. This applies to every on-device sleep read — getSleepDetail, getSleepSessions, the graph and disturbance reads, the dashboard, the local recovery score and the daily resting HR / HRV — and matters most in offline mode, where nothing reaches the server to be merged there. The stored sleep rows are not changed: each piece is still uploaded on its own and the server does its own merge. A sessionEndTimestamp that is one piece's wake-up resolves to the night containing it.

The returned SB_SleepDetailDay is populated with what the device stores, recomputed to match server-first exactly (the server re-derives its stage metrics after upload, and the iOS row never even stores its own per-stage totals — those columns are always 0 and the server fills them in from the timestamped stages):

  • stage metrics — the per-epoch stages are clamped to [sleepOnset, wakeUp] and re-counted (server UpdateSleepDerivedMetricsUsingTimestampedStages), so the leading sleep-latency awake and any trailing awake are excluded. Each stage's minutes are the epoch count divided by the device's epochs-per-minute with integer truncation (server int32(count / multiplier)), matching the server to the minute. This drives the four legend percentages (largest-remainder rounding, including the server's quirk that a sub-1% bucket is never bumped to 1), the per-stage duration tiles, sleepTimeSec = (light + deep + rem) × 60, and the in-window arousal count. The stage-timeline stages.stages intervals are likewise the in-window epochs;
  • sleepOnset / wakeUpTime / timezone (the device's current TZ offset in minutes — the same value the upload path stamps);
  • biometrics from the on-device PPG over the sleep window, each reproduced the server's way: restingHr (header — CalculateRestingBPM: mean of the 5 lowest lower-fence-outlier-free BPM), the Average HR tile (median of the same outlier-free BPM) and the Nocturnal HRV tile (CalculateRestingHRV: the residual-outlier-free OLS HRV-vs-time line evaluated at the last epoch, also mirrored into restingHrv). Each is 0/omitted when there is too little data. The resting HR and HRV are computed in the shared C library (SB_restingHR / SB_restingHRV in mobile_edge_algorithms), the same code on both platforms, checked against the server's own Go: resting HR matches it exactly; resting HRV matches it to float32 precision (the server fits its line by a QR decomposition, the C by centred least squares). "Too little data" is the server's: fewer than 5 samples, or for HRV fewer than 3 non-zero samples to fit (or more than 3,600). As on the server these are rounded to whole numbers for display (util.Round) while the score is computed from the raw values — hosts render them with truncating formatters, so an unrounded value would read one lower than server-first;
  • metrics — the locally-derivable tiles, in the server's tile order with the server's labels: Total Time in Bed (= wakeUp − onset + 1 min), Total Awake, Light, Deep, REM Sleep (.duration), Nocturnal HRV (ms), Average HR (bpm), Awakenings (count), Sleep Latency (= onset − start), then the two editable .timeTz tiles Sleep Onset + Wake up Time — mirroring the only two tiles the server marks editable. The Nocturnal HRV + Average HR tiles are attached only to the day's main (longest) sleep, matching the server's sl.MainSleep guard, so a nap carries neither;
  • the sleep score + contributing factors + penalties (sleepScore / scoreFactors / scorePenalty), computed locally to match the server's CalculateSleepMainScore: score = max(1, goalAchieved × efficiency × 100 − penalties). Factors = Total Sleep (vs the user's sleep goal), Deep (or Deep And REM), Efficiency; penalties (points > 0 only) = Awakenings, Restlessness (from the arm disturbances), Latency, and Elevated Avg Heart Rate. Every input is on-device: the sleep goal comes from the SDK's own cache, which the SDK keeps warm itself by refreshing goals on sign-in / auto-login (the same fire-and-forget refresh it does for white-label settings) and on every fetchGoals() / updateGoals(...) — so the local read path never pulls it over the network, and it only falls back to the server's 7 h default before the first successful refresh. And the HR penalty's 30-day resting-HR baseline is computed on the device from each of the prior 30 nights' sleep and HR, the same way as tonight's resting HR. A night this device never recorded (before its history began, or recorded on another phone) is filled first: the read pulls that day's sleep and HR from the server — raw data only, never the server's resting HR or score — stores them, and computes the night's resting HR from them. Each missing day is pulled once per signed-in session, and later reads of the same nights are local. So the first sleep-detail read on a new device may make up to 30 days' worth of server reads (about four per day: the sleep list, the sleep detail, and the day's HR and HRV, which the recovery score also uses); in offline mode nothing is pulled, and the baseline uses the nights the device has. The HR penalty is omitted when no prior night has a resting HR (server parity; e.g. a new account). If the night itself has no resting HR, no score is produced and the header falls back to the empty "--" ring.

Everything else the server owns and the local row does not hold is left empty and simply doesn't render: bedtime recommendations, accounting, positions, apnea / breathing, bathroom breaks, survey and the temperature graph. A server-backfilled window row (persisted for vitals tagging on a day that predated local sync) has no stages and is never rebuilt into a detail.

getSleepSessions(date:) returns the day's sessions for the detail screen's multi-session grid — local-first, else the server's list for an old day, sorted by start. Key each session by SB_SleepItem.endTimestamp (its wake-up epoch) and pass it back as getSleepDetail(date:sessionEndTimestamp:), or to the graph reads, to load that session.

swift
public func getSleepDetail(date: Date, sessionEndTimestamp: Int64? = nil) async throws -> SB_SleepDetailDay?
public func getSleepSessions(date: Date) async throws -> [SB_SleepItem]

// The session's biometric-graph timeseries (HR / HRV / RR) for the sleep-detail charts.
// The session is identified by its wake-up epoch (`SB_SleepItem.endTimestamp`, or
// `SB_SleepDetailDay.wakeUpTime` from getSleepDetail).
public func getSleepHR(sessionEndTimestamp: Int64) async throws -> [SB_TimeValuePoint]
public func getSleepHRV(sessionEndTimestamp: Int64) async throws -> [SB_TimeValuePoint]
public func getSleepRR(sessionEndTimestamp: Int64) async throws -> [SB_TimeValuePoint]

getSleepHR / getSleepHRV / getSleepRR return the session's per-epoch metric over its [onset, wakeUp] window, time-ordered with real-epoch timestamps (the convention the sleep biometric chart's bucketing expects), with each metric's server-parity outlier handling applied (HR lower fence only, so high spikes are kept; HRV a two-sided drop on the residuals of a least-squares fit, which removes the spikes; RR unfiltered, rounded to 1 dp). Local-first: read from the on-device PPG; if the day predates local sync (no on-device sleep) each falls back to the server sleep detail's matching graph — hence async throws. A device-recorded session whose PPG is simply missing returns empty rather than reaching the network. A host wraps each list in an SB_SleepBiometricGraph (points + mean average) to feed the same biometric chart the server path draws; there is no local SpO2 (that card stays hidden).

getSleepArmDisturbances(sessionEndTimestamp:) returns the session's arm-restlessness severity timeline for the disturbance chart — fully local, so it never throws: bucketed from the on-device activity packets' motion value over [onset, wakeUp] with the server's fixed thresholds (≤250000 none / ≤750000 mild / ≤1250000 moderate / else severe), first + last forced .none (the awake bookends). It returns a colour-free SB_SleepDisturbanceLevel per epoch — the SDK deliberately does not return colours, so the host owns the palette (and its theming). .none points are included so the host can compute the level distribution for the legend; hosts typically drop them from the drawn series (server parity). No server fallback — the arm series is only ever local; empty when the session has no activity packets on device. (Leg / snoring disturbance graphs are dead on the server, so only the arm series is exposed.)

It is async with nothing to await, purely so the store read happens off the caller's actor (a @MainActor view model never does the fetch on the main thread) — matching Android's suspend signature.

swift
public func getSleepArmDisturbances(sessionEndTimestamp: Int64) async -> [SB_SleepDisturbancePoint]

public enum SB_SleepDisturbanceLevel: Int32, Codable, Equatable, Sendable, CaseIterable {
    case none = 0, mild = 1, moderate = 2, severe = 3
}

public struct SB_SleepDisturbancePoint: Codable, Equatable, Sendable {
    public var timestamp: Int64                    // ms, real epoch
    public var timezone: Int32                     // device TZ offset in minutes
    public var level: SB_SleepDisturbanceLevel
}

getSleepDetail / getSleepSessions / the three graph reads throw only on the server-backed path (e.g. SB_AuthError.missingAuthToken when signed out); the pure-local path never touches the network. (Ported to match Android's local-first sleep, SB-1677/SB-1678.)

7.5 Insights — personal + population + feedback ​

swift
public func fetchNewInsights() async throws -> SB_NewInsights
public func fetchPopulationInsightsMetricList() async throws -> SB_PopulationInsightsFilterList
public func fetchPopulationInsights(
    ageStart: Int32, ageEnd: Int32,
    gender: SB_PopulationGender, metricType: SB_PopulationMetricType
) async throws -> (histogram: SB_PopulationInsightsHistogram?, radarChart: SB_PopulationInsightsRadarChart?)
public func submitInsightsFeedback(insightId: Int64, feedback: SB_InsightFeedback) async throws

SB_PopulationInsightsHistogram carries the user's value as numbers so the host can build and localize the insight message itself (SB-2618). The server's insightText is deprecated on the wire (SB-2589) but still populated; fall back to it when insightValue == 0 (an older server that doesn't send the numeric fields — proto3 scalars have no presence).

swift
public struct SB_PopulationInsightsHistogram: Sendable {
    public let insightText: String                 // deprecated, server-formatted English
    public let userXPosition: Int32
    public let userXValue: Float
    public let metricType: SB_PopulationMetricType
    public let histogramData: [SB_HistogramPair]
    public let insightValue: Float                 // in insightUnit, e.g. 129 (minutes); SpO2 / BRPM 1 dp
    public let insightUnit: SB_PopulationInsightUnit
    public let insightPercentage: Int32            // % of the population the user beats, 0-100
}

public enum SB_PopulationInsightUnit: Int32, Sendable {
    case none = 0, minutes = 1, milliseconds = 2, percent = 3
}

7.6 User profile ​

swift
public func updateUserProfile(_ profile: SB_UserProfileUpdate) async throws -> SB_UpdateUserProfileOutcome
public func refreshUser() async throws
public func uploadUserPhoto(imageData: Data) async throws -> String?
public func deleteUserPhoto() async throws

location is a full-replace field. SB_UserProfileUpdate.location and SB_UserProfile.location name the same value — the user's location (city / country). It maps to a wire field historically named zipcode. updateUserProfile replaces the whole profile, so read the current value from sensorBio.userProfile?.location and pass it back in on every update; sending "" (or omitting it) overwrites the stored value on the server.

7.7 Goals ​

Steps / calories / sleep are the customer-facing goal surface. SB_Goals is returned with those three targets/currents public; its workout / routine-goal members are Sensr-Bio-only and absent from the binary. It is Equatable, Sendable.

swift
public func fetchGoals() async throws -> SB_Goals
public func updateGoals(steps: Int, calories: Int, sleep: Int) async throws -> SB_UpdateGoalsOutcome

Both cache the sleep target locally as a side effect (SB-1678), so the local-first sleep score can read the user's goal without a network round-trip. The SDK also refreshes goals itself on sign-in / account creation / auto-login (fire-and-forget, alongside the white-label refresh), so the cache is warm without the host having to call fetchGoals() at all — a host that never did would otherwise have left the local score scoring against the 7 h default. Nothing else about their behaviour changes, and the cache is only ever written with a non-zero goal.

7.8 Sleep writes ​

swift
public func fetchSleepSessions(date: Date) async throws -> [SB_SleepItem]
public func addSleepSession(onset: Date, wakeUp: Date) async throws
@discardableResult
public func modifySleepSession(onset: Date, wakeUp: Date, endTimestamp: Int64, date: Date) async throws -> String
public func deleteSleepSession(endTimestamp: Int64, date: Date) async throws
public func reprocessSleep(endDate: Int32, endTimestamp: Int64) async throws

addSleepSession and modifySleepSession throw SB_SleepWriteError:

swift
public enum SB_SleepWriteError: Error {
    case insufficientData       // not enough band data in the window
    case neverAsleep            // band data, but none of it scored as sleep
    case timeInFuture           // onset or wake-up is in the future
    case wakeUpNotAfterOnset    // wake-up is not after onset
    case invalidTimes           // onset or wake-up is missing (modify: or not ordered)
    case sessionNotFound        // modify: no session at the given end coordinates
    case modifyFailed(message: String) // modify: unrecognized refusal code
}

addSleepSession names each refusal separately (SB-2423). Before that it threw .insufficientData for all of them, and it still does for a refusal code the SDK doesn't recognize, so an existing catch SB_SleepWriteError.insufficientData keeps working.

modifySleepSession maps the server's refusal codes the same way (SB-2426): not enough data → .insufficientData, invalid times → .invalidTimes, no such session → .sessionNotFound. .modifyFailed(message:) is now only the fallback for a code the SDK doesn't recognize; before SB-2426 it was thrown for every refusal, so a catch .modifyFailed alone no longer sees the known codes. message is the server's unlocalized text — log it, don't show it. The returned String on success is the server's unlocalized status text too; show your own copy. None of the cases carry user-facing text: map each to your own localized string.

7.9 Workouts & activities ​

swift
public func fetchActivityList() async throws -> SB_ActivityRecordingList
public func fetchWorkoutRecordingInfo() async throws -> SB_WorkoutRecordingInfo
public func fetchWorkoutSummary(date: Date, granularity: SB_SummaryGranularity, workoutType: SB_WorkoutType? = nil) async throws -> [SB_WorkoutItem]
public func fetchWorkoutDetail(workoutTime: Date) async throws -> SB_WorkoutDetail?
public func fetchWorkoutTimeline(date: Date, searchTerm: String = "", filterType: SB_WorkoutEntryType = .all) async throws -> SB_WorkoutTimelineResult
public func workoutTimelineUpdates(for date: Date) -> AsyncThrowingStream<SB_WorkoutTimelineResult, Error>
public func modifyWorkout(action: SB_ModifyAction, date: Date, timestamp: Date, workoutName: String, params: [String: String] = [:]) async throws -> SB_ModifyOutcome
public func fetchMeditationGraph(date: Date, sessionTimestamp: Int64) async throws -> SB_MeditationGraph

Workout modifications (SB-2226) ​

modifyWorkout keeps its signature and there is nothing to wire, but three things about it are now different.

The SDK decides when it goes on the wire. ModifyWorkoutRequest addresses a workout by its start timestamp and nothing else, so an edit sent before the recording has been ingested had nothing to apply to and came back .notFound — for an activity the user was looking at, since the timeline and the post-recording report are both local-first (§3.5.1). An .update now goes through a durable on-device queue: for a workout the server already has it is the same synchronous call it always was, and for one still uploading the edit is recorded and dispatched the moment the recording lands. Nothing to poll and nothing to retry — the queue survives a force-quit, a sign-out is what clears it.

The outcome means something narrower. It is a verdict on the values, not on whether the RPC has happened. A retryable failure — no network, or a .notFound after the recording was confirmed, which is read-replica lag — reports .ok, because the edit is durably on disk and the SDK will land it. Only a terminal rejection of the values themselves comes back as a failure. Word any error you show accordingly: it now means "check these values", not "try again later".

The new values are readable before they are sent. Every path that produces an SB_WorkoutDetail — fetchWorkoutDetail(workoutTime:) and localWorkoutDetail(startTsMillis:) — and the rows from localRecordingEntries() all have the pending edit applied, so a host that simply re-reads after a successful save shows what the user typed, immediately, offline, and across a relaunch. A landed edit stands down in favour of the server, so an edit made later on the web dashboard wins rather than being shadowed by this device.

HR zones on a stored workout (SB-2230) ​

SB_HRMData.exerciseZoneList — the time-in-zone breakdown and the chart's zone lines — is always the server's, on every read path, including when the HR Zone algorithm is enabled.

The server scores the zones at ingest and stores them, and SubmitFinishedRecordingSession has no field to send zones up, so the device has no say in the stored copy. That is deliberate rather than a gap: a report's zones are a fact about when the workout happened. Recomputing them at read time against the wearer's current resting heart rate would make a stored report change every time it was opened, and change differently after a birthday.

So the algorithm affects the live recording chart, where "now" is the right anchor, and not a stored report. To move a stored report's zones, the algorithm's result has to be uploaded and stored — at which point the report shows them because the server holds them, not because the device recomputed them.

One exception, and only one: the report built on device the instant a recording stops, before the server has ingested it. There is no server-scored list yet, and that screen has to continue the boundaries the user just spent the workout watching, so it uses the algorithm's. Once the recording is ingested the timeline serves the server's copy as usual.

That means the same workout reads differently in the two places until the algorithm's result is uploaded: the just-finished report shows the device's zones, the timeline shows the server's. That is a known consequence of the device having no way to tell the server which zones it used, not a bug, and it closes when the upload lands.

Which zone a row is: SB_HRZone (SB-2355) ⚠️ interface change ​

The SDK identifies a heart-rate zone with an enum and no display text. What a zone is called, and its localization, is the host's job.

swift
public enum SB_HRZone: Int, CaseIterable, Codable, Comparable, Sendable {
    case baseline = 0   // under zone 1's floor
    case zone1, zone2, zone3, zone4, zone5
    public static let scored: [SB_HRZone]   // .zone1 ... .zone5
}
  • Reports: SB_HRMExerciseZone.zone: SB_HRZone? says which zone a time-in-zone row is. The below-zone-1 row is .baseline. zone is nil only when the server sent no zone number and a zone name this SDK doesn't recognize. That row is kept so the times still add up, but it isn't any zone and shouldn't be labelled or colored as one.
  • Live recording: SB_Zone.zone: SB_HRZone? says which zone a floor starts. Build one with SB_Zone(zone:minValue:hexStringColor:).
  • Deprecated, kept for one release: SB_HREffortZone, SB_HRMExerciseZone.description, SB_HRMExerciseZone.init(description:…), SB_Zone.name and SB_Zone.init(name:…). These carry the server's English names ("Warm up", "Fat Burn", …). Don't display them. Switch to zone and your own strings.
  • Cached reports written by an earlier SDK carry only the name. It is mapped to zone when the report is read, so no migration is needed.

The SDK reads the zone from HRMExerciseZone.zone in data.proto (SB-2543). When the server leaves that unset (.unspecified, as servers that predate it do), the SDK falls back to the English name in the deprecated HRMExerciseZone.description. Either way it maps to SB_HRZone when the response is decoded, and nothing after that reads the string.

Below-warm-up time and the bar colours (SB-2356) ⚠️ behaviour change ​

Every workout detail the SDK hands out — fetchWorkoutDetail, localWorkoutDetail and activityReport, whichever source built it — has its exerciseZoneList finished for display the same way. This only affects a list that has zones in it: an empty list stays empty.

  • A last row, zone == .baseline (named "Below warm up" before SB-2355), holds the time spent under the first zone's floor, so the card adds up to the whole workout. It is worked out from SB_HRMData.dataPoints against the list's own lowest floor, using the same gap-to-previous rule the zones use. It also holds the workout time with no HR reading at all, before the first sample and after the last one (SB-2404), so the rows add up to endTimestamp - timestamp, the Session figure. That matters most for an auto-detected activity, where HR can start minutes after the activity does. Its yAxisLimitChartValue is 0 because it has no floor of its own. That is also how to tell it apart from a zone: skip it when you draw chart limit lines or work out the y-axis range, or you get a line at 0 bpm.
  • hexadecimalColor is the bar colour, not the zone's floor colour. The HR chart pins each zone's colour to that zone's floor and blends upward, so each band looks like the next zone up. The bars now use that same colour: .baseline #979797, .zone1 #00a7dc, .zone2 #00ad67, .zone3#fd8635, and .zone4 and .zone5 both #ee3e41. A host that colours a chart gradient from this field should switch to its own floor colours (#979797 / #00a7dc / #00ad67 / #fd8635 / #ee3e41 from .zone1 upward). Otherwise every band moves up one colour.
  • progressValue is rescaled against the longest row, including Below warm up. On an easy walk that row is full length and the zones are short. The zone rows' displayValue and boundaries keep their scored values; only the bar length and colour change.

The zone boundaries and the five times the HR Zone algorithm uploads are unchanged.

.remove works on an un-uploaded workout. Where there is no server row, the submission is discarded on the device instead and its timeline row goes with it — same intent, different mechanism, and the host does not choose between them. The recording's biometrics are deliberately not deleted: per-second HR, BBI and packets are day-scoped passive data, so those minutes stay in the user's history and simply stop being attributed to an activity, exactly as a server-side remove behaves. .ignore is unchanged.

Timeline first-page cache (SB-1958). The workout reads are otherwise uncached — they're navigation-driven — with one exception: the timeline's first page. workoutTimelineUpdates(for:) is the stale→fresh stream for it, so the timeline paints the last-known page on cold launch instead of a skeleton, then swaps in the authoritative fetch.

Only the plain page-1 read is cached (workout.timeline.page1): no cursor, no search term, .down. A cursor is a server-side handle on a query that has moved on, and a searched result is a query whose answer has to come from the server — caching either would explode the key space and serve stale answers, so fetchWorkoutTimeline passes those straight through. fetchWorkoutTimeline for the cacheable shape also gains the usual bad-internet fallback: on a failed fetch it returns the last-known page rather than throwing.

Page 1 is always "today", so the cache never replaces the network read the way a final past-date entry does (see Caching) — the value is the pre-yield paint and the offline fallback, not a skipped round trip.

The cached copy has its pagination cursor stripped. A restored cursor would page the host into a window the server no longer recognises; with it empty, a host gating its infinite-scroll loader on cursor != nil simply has paging unavailable for the moment before the authoritative page lands, rather than wrong.

7.10 Spot-check & recording metadata ​

swift
public func fetchSpotCheckDetails(id: String) async throws -> SB_SpotCheckDetails?
public func fetchRecordingMetaInfo(_ type: SB_RecordingMetaType) async throws -> [SB_RecordingSessionMeta]
public func deleteRecordingMeta(id: String, name: String, type: SB_RecordingMetaType) async throws

7.11 Surveys & questionnaires ​

Brief surveys are the real sleep / workout / meditation survey responses the device collects; they stay on the public surface.

There are two ways to submit one. Use the queued path.

swift
public func queueBriefSurvey(_ survey: SB_BriefSurvey)
public func dismissBriefSurvey(type: SB_BriefSurveyType, timestampMillis: Int64)
public func briefSurveyWasHandled(timestampMillis: Int64) -> Bool
public func briefSurvey(forTimestampMillis timestampMillis: Int64) -> SB_BriefSurvey?

queueBriefSurvey returns immediately, and that is the whole point. The answers are written to the SDK's store synchronously, before any network, so your sheet can dismiss the moment it returns. Do not gate a spinner on it, and do not disable the way out of the screen — there is nothing to wait for. (iOS did exactly that until SB-2177, awaiting the RPC with Submit and Skip disabled; a 30s gRPC deadline, three transport attempts and a token refresh add up to minutes of a screen the user cannot leave.)

The SDK decides when to send it, and "now" is usually wrong. A survey carries its recording's start timestamp — a sleep's end timestamp — as its only link to that record. Post-recording reports are built locally and appear the instant a recording finalizes, so a user can answer within seconds, while the recording itself is still behind the biometrics-upload gate (up to a 90s bailout). Sent then, the server has nothing to attach the survey to: it answers with an empty id, the survey is orphaned, and nothing on screen says so. queueBriefSurvey holds the survey until the recording is known to have landed, then sends it. Offline, the row waits; the SDK drains it when the network returns, and across relaunches.

The answers appear before they are sent. Every read that produces a survey merges in what this device holds:

ReadKey it merges on
fetchWorkoutDetail(workoutTime:)workout start ts
fetchMeditationGraph(date:sessionTimestamp:)session start ts
fetchSleepDetail(endDate:endTimestamp:) / sleepDetailUpdates(…)sleep end ts
localWorkoutDetail(startTsMillis:) / localMeditationGraph(startTsMillis:)recording start ts

So there is nothing to stamp onto your model, nothing to assign, and nothing to refetch — submit, dismiss, and the screen behind you is already right. A queued survey is deliberately indistinguishable from a landed one; the only exception is a screen still holding a report object it was handed at finalize, which by construction predates the survey. Re-read briefSurvey(forTimestampMillis:) there after the sheet closes (a local store read, not a round trip).

Precedence: a survey that has not landed yet wins over the server's copy — the user just typed it. Once it lands, the server's copy wins, so a survey edited elsewhere (the web dashboard) is not shadowed by this device forever.

Editing is safe. The row keeps the server's id, so a second answer updates rather than creating a duplicate — and it keeps it across a screen teardown and a relaunch, which view-model state never did.

dismissBriefSurvey is how you record "asked and skipped." It writes a row that is never dispatched, so briefSurveyWasHandled can tell you not to offer that survey again. Keep this out of your own UserDefaults: rows are wiped on sign-out with everything else, which a defaults key is not.

swift
public var pendingBriefSurveysPublisher: AnyPublisher<[SB_BriefSurveySubmissionInfo], Never>
public func pendingBriefSurveys() -> [SB_BriefSurveySubmissionInfo]

Diagnostics — surveys with work still outstanding (pending, or unlinked awaiting a re-send). Nothing in a shipped UI needs these; they are for a developer readout while testing on a throttled link.

swift
public func submitBriefSurvey(_ survey: SB_BriefSurvey) async throws -> String

The direct path — prefer queueBriefSurvey. It sends immediately, with no gate and no local record, so a survey submitted through it before its record reaches the server is orphaned exactly as described above. It remains for hosts already calling it, and for surveys with no recording to wait on.

Await it before refetching. The submit suspends until the survey lands server-side. If your survey UI refetches anything on dismissal, do that after this returns — otherwise the refetch races the upload, goes out before the survey exists, and the dependent UI stays stale until some later fetch. This was fire-and-forget before SB-1835, and every caller had exactly that race.

A throw means "not landed yet", not "lost." On failure the SDK records the survey in its own store before rethrowing and retries from there (waits for connectivity, survives relaunch). So the survey will still land; treat the error as retry-in-progress rather than a discarded response, and gate your submit button while the call is in flight so a double-tap can't send twice.

SB_SurveyError.notLinked is not a transport failure. It means the server accepted the call and returned no id — it could not attach the survey to anything. The SDK keeps the answers and re-sends once the record is confirmed; do not treat it as a lost survey, and do not stamp the empty id onto your model.

Keep the returned id. A submit whose survey.id is nil creates a new survey server-side instead of updating the existing one. If a user can edit the same survey twice in one session and your second submit reuses a copy that never had the id stamped on it, you silently duplicate rather than update.

Android's equivalent is suspend (SB_BriefSurvey) -> String and iOS matches it. Android has neither the queue nor the gate yet, so it still has the race this closes, and its caller discards the id and refetches on dismissal — both worth aligning.

7.12 Devices, services & global state ​

swift
public func updateUserDeviceInfo(macAddress: String, metadata: [String: String], unlinkDevice: Bool)
public func refreshGlobalState() async throws -> SB_OrgMembership
public func refreshUserAppSettings() async throws -> SB_UserAppSettings
public func fetchDailyStats(startDate: Int32, days: Int32, metrics: [String]) async throws -> [SB_DailyStats]

Sensor Bio Mobile SDK — iOS & Android integration reference.