Skip to main content

Sleep

The Sleep module provides comprehensive sleep data management and analysis capabilities. It enables synchronization of raw sleep segments and daily aggregated sleep data from wearable devices, including detailed sleep stage information, quality metrics, and support for multiple sleep statistics algorithms.

Prerequisites​

  • Device must be connected and paired with the SDK
  • Device firmware must support sleep data collection
  • User must have granted necessary health data permissions
  • For raw data sync: device must have recorded sleep data within the requested time range
  • For daily data sync: at least one complete sleep cycle must exist in the target date range

Data Models​

TSSleepDailyModel​

Daily sleep data model representing one sleep calendar day with summary, segments, and raw items.

PropertyTypeDescription
statisticsRuleTSSleepStatisticsRuleStatistics rule used for this sleep record
dailySummaryTSSleepSummary *Overall daily sleep summary with aggregated metrics
rawSleepItemsNSArray<TSSleepDetailItem *> *Raw sleep detail items synced from device before processing
nightSleepsNSArray<TSSleepSegment *> *Night sleep segments for this day
daytimeSleepsNSArray<TSSleepSegment *> *All daytime sleep segments classified for this day

TSSleepDetailItem​

Single sleep stage segment containing stage type, start time, and duration.

PropertyTypeDescription
stageTSSleepStageSleep stage type (Awake/Light/Deep/REM)
belongingDateNSTimeIntervalTimestamp of 00:00:00 of the day this sleep belongs to (20:00 day boundary)

TSSleepSegment​

Continuous sleep segment with period type, summary statistics, and detailed items.

PropertyTypeDescription
periodTypeTSSleepPeriodTypeSleep period type (Night/Daytime)
summaryTSSleepSummary *Statistical summary of this sleep segment
detailItemsNSArray<TSSleepDetailItem *> *Detailed sleep stage items in chronological order

TSSleepSummary​

Statistical summary of sleep data including duration, quality, and stage breakdown.

PropertyTypeDescription
startTimeNSTimeIntervalUnix timestamp of sleep start time
endTimeNSTimeIntervalUnix timestamp of sleep end time
durationNSTimeIntervalTotal duration from start to end (seconds)
totalSleepDurationNSTimeIntervalTotal effective sleep time excluding awake periods (seconds)
qualityScoreUInt8Sleep quality score (0-100)
awakeDurationNSTimeIntervalTotal awake duration during sleep period (seconds)
lightSleepDurationNSTimeIntervalTotal light sleep duration (seconds)
deepSleepDurationNSTimeIntervalTotal deep sleep duration (seconds)
remDurationNSTimeIntervalTotal REM sleep duration (seconds)
awakePercentageUInt8Awake percentage relative to total sleep duration
lightSleepPercentageUInt8Light sleep percentage relative to total sleep duration
deepSleepPercentageUInt8Deep sleep percentage relative to total sleep duration
remPercentageUInt8REM sleep percentage relative to total sleep duration
awakeCountUInt16Number of awake episodes
lightSleepCountUInt16Number of light sleep episodes
deepSleepCountUInt16Number of deep sleep episodes
remCountUInt16Number of REM episodes

Enumerations​

TSSleepStage​

Sleep stage type enumeration according to AASM standards.

ValueDescription
TSSleepStageAwakeAwake stage during sleep period
TSSleepStageLightLight sleep stage (N1 and N2 phases)
TSSleepStageDeepDeep sleep stage (N3 phase, slow-wave sleep)
TSSleepStageREMRapid Eye Movement sleep phase (dream sleep)

TSSleepPeriodType​

Sleep period type enumeration based on data header time.

ValueDescription
TSSleepPeriodTypeNightNight sleep period [20:00-09:00)
TSSleepPeriodTypeDaytimeDaytime sleep period [09:00-20:00)

TSSleepStatisticsRule​

Sleep statistics rule type based on device capabilities.

ValueDescription
TSSleepStatisticsRuleWithoutNapNo nap support; sensor active 20:00-12:00; all sleep treated as night sleep
TSSleepStatisticsRuleWithNapNap support enabled; sensor active 24h; distinguishes night/day sleep
TSSleepStatisticsRuleLongestNightUses longest continuous night sleep segment (20:00-08:00); valid naps counted
TSSleepStatisticsRuleLongestOnlyNo distinction between night/day; uses longest continuous sleep segment only

API Reference​

Get sleep statistics rule​

- (TSSleepStatisticsRule)sleepStatisticsRule;

Retrieves the sleep statistics algorithm used by the current device.

ParameterTypeDescription
returnTSSleepStatisticsRuleEnum value indicating which algorithm is used for sleep data processing

Code Example:

id<TSSleepInterface> sleepInterface = (id<TSSleepInterface>)kit;
TSSleepStatisticsRule rule = [sleepInterface sleepStatisticsRule];

switch (rule) {
case TSSleepStatisticsRuleWithoutNap:
TSLog(@"Device: No nap support");
break;
case TSSleepStatisticsRuleWithNap:
TSLog(@"Device: Nap support enabled");
break;
case TSSleepStatisticsRuleLongestNight:
TSLog(@"Device: Longest night strategy");
break;
case TSSleepStatisticsRuleLongestOnly:
TSLog(@"Device: Longest only strategy");
break;
}

Check REM sleep support​

- (BOOL)isSupportREMSleep;

Checks if the device supports REM (Rapid Eye Movement) sleep stage detection.

ParameterTypeDescription
returnBOOLYES if device supports REM sleep detection, NO otherwise

Code Example:

id<TSSleepInterface> sleepInterface = (id<TSSleepInterface>)kit;
BOOL supportsREM = [sleepInterface isSupportREMSleep];

if (supportsREM) {
TSLog(@"Device supports REM sleep detection");
} else {
TSLog(@"Device does not support REM sleep detection");
}

Check sleep-analysis support​

- (BOOL)isSupportSleepAnalysis;

Returns whether the device supports sleep analysis. Check this value before using analysis-dependent behavior.

Sync raw sleep data from start time​

- (void)syncRawDataFromStartTime:(NSTimeInterval)startTime
completion:(nonnull void (^)(`NSArray<TSSleepDetailItem *>` *_Nullable sleepItems, NSError *_Nullable error))completion;

Synchronizes raw sleep segments from a specified start time.

ParameterTypeDescription
startTimeNSTimeIntervalUnix timestamp (seconds) of the starting point
completionvoid (^)(NSArray<TSSleepDetailItem *> *_Nullable, NSError *_Nullable)Callback returning array of raw sleep items or error

Code Example:

id<TSSleepInterface> sleepInterface = (id<TSSleepInterface>)kit;
NSTimeInterval startTime = [[NSDate dateWithTimeIntervalSinceNow:-7*24*3600] timeIntervalSince1970];

[sleepInterface syncRawDataFromStartTime:startTime
completion:^(`NSArray<TSSleepDetailItem *>` *sleepItems, NSError *error) {
if (error) {
TSLog(@"Error syncing raw sleep data: %@", error.localizedDescription);
return;
}

for (TSSleepDetailItem *item in sleepItems) {
NSString *stageName = @"Unknown";
switch (item.stage) {
case TSSleepStageAwake: stageName = @"Awake"; break;
case TSSleepStageLight: stageName = @"Light"; break;
case TSSleepStageDeep: stageName = @"Deep"; break;
case TSSleepStageREM: stageName = @"REM"; break;
}
TSLog(@"Sleep stage: %@, Duration: %.0f seconds", stageName, item.duration);
}
}];

Sync raw sleep data within time range​

- (void)syncRawDataFromStartTime:(NSTimeInterval)startTime
endTime:(NSTimeInterval)endTime
completion:(nonnull void (^)(`NSArray<TSSleepDetailItem *>` *_Nullable sleepItems, NSError *_Nullable error))completion;

Synchronizes raw sleep segments within a specified time range.

ParameterTypeDescription
startTimeNSTimeIntervalUnix timestamp (seconds) of range start (inclusive)
endTimeNSTimeIntervalUnix timestamp (seconds) of range end (exclusive); range is [startTime, endTime)
completionvoid (^)(NSArray<TSSleepDetailItem *> *_Nullable, NSError *_Nullable)Callback returning array of raw sleep items or error

Code Example:

id<TSSleepInterface> sleepInterface = (id<TSSleepInterface>)kit;
NSDate *startDate = [NSDate dateWithTimeIntervalSinceNow:-7*24*3600];
NSDate *endDate = [NSDate date];

[sleepInterface syncRawDataFromStartTime:[startDate timeIntervalSince1970]
endTime:[endDate timeIntervalSince1970]
completion:^(`NSArray<TSSleepDetailItem *>` *sleepItems, NSError *error) {
if (error) {
TSLog(@"Error: %@", error.localizedDescription);
return;
}

TSLog(@"Retrieved %lu raw sleep items", (unsigned long)sleepItems.count);
}];

Sync daily aggregated sleep data from start time​

- (void)syncDailyDataFromStartTime:(NSTimeInterval)startTime
completion:(nonnull void (^)(`NSArray<TSSleepDailyModel *>` *_Nullable sleepModel, NSError *_Nullable error))completion;

Synchronizes daily aggregated sleep data from a specified start time.

ParameterTypeDescription
startTimeNSTimeIntervalUnix timestamp (seconds) of the starting day
completionvoid (^)(NSArray<TSSleepDailyModel *> *_Nullable, NSError *_Nullable)Callback returning array of daily sleep models or error

Code Example:

id<TSSleepInterface> sleepInterface = (id<TSSleepInterface>)kit;
NSTimeInterval startTime = [[NSDate dateWithTimeIntervalSinceNow:-30*24*3600] timeIntervalSince1970];

[sleepInterface syncDailyDataFromStartTime:startTime
completion:^(`NSArray<TSSleepDailyModel *>` *sleepModels, NSError *error) {
if (error) {
TSLog(@"Error syncing daily sleep data: %@", error.localizedDescription);
return;
}

for (TSSleepDailyModel *model in sleepModels) {
TSSleepSummary *summary = model.dailySummary;
TSLog(@"Date: %@, Total Sleep: %.0f min, Quality: %d",
[NSDate dateWithTimeIntervalSince1970:model.startTime],
summary.totalSleepDuration / 60.0,
summary.qualityScore);
}
}];

Sync daily aggregated sleep data within time range​

- (void)syncDailyDataFromStartTime:(NSTimeInterval)startTime
endTime:(NSTimeInterval)endTime
completion:(nonnull void (^)(`NSArray<TSSleepDailyModel *>` *_Nullable sleepModel, NSError *_Nullable error))completion;

Synchronizes daily aggregated sleep data within a specified date range.

ParameterTypeDescription
startTimeNSTimeIntervalUnix timestamp (seconds) of range start day (inclusive)
endTimeNSTimeIntervalUnix timestamp (seconds) of range end day (exclusive); range is [startTime, endTime)
completionvoid (^)(NSArray<TSSleepDailyModel *> *_Nullable, NSError *_Nullable)Callback returning array of daily sleep models or error

Code Example:

id<TSSleepInterface> sleepInterface = (id<TSSleepInterface>)kit;
NSDate *startDate = [NSDate dateWithTimeIntervalSinceNow:-7*24*3600];
NSDate *endDate = [NSDate date];

[sleepInterface syncDailyDataFromStartTime:[startDate timeIntervalSince1970]
endTime:[endDate timeIntervalSince1970]
completion:^(`NSArray<TSSleepDailyModel *>` *sleepModels, NSError *error) {
if (error) {
TSLog(@"Error: %@", error.localizedDescription);
return;
}

for (TSSleepDailyModel *model in sleepModels) {
TSSleepSummary *summary = model.dailySummary;
TSLog(@"Night Sleep: %.0f min, Deep: %d%%, Quality: %d",
summary.totalSleepDuration / 60.0,
summary.deepSleepPercentage,
summary.qualityScore);

`NSArray<TSSleepSegment *>` *validNaps = [model validNaps];
TSLog(@"Valid naps: %lu", (unsigned long)validNaps.count);
}
}];

Important Notes​

  1. Sleep data uses 20:00 as the day boundary [20:00→20:00). Sleep occurring at 21:00 on Nov 19 belongs to Nov 20 calendar day.

  2. Different devices support different statistics rules. Call sleepStatisticsRule before processing to determine the appropriate algorithm for your device.

  3. Raw data sync returns fine-grained sleep stage segments suitable for timeline visualization and custom analysis. Daily data sync returns aggregated summaries per calendar day.

  4. Time ranges for sync methods use Unix timestamps in seconds. The range [startTime, endTime) is inclusive of start and exclusive of end.

  5. REM sleep support varies by device. Check isSupportREMSleep before relying on REM stage data in analysis.

  6. Valid naps are filtered by duration: greater than or equal to 20 minutes and less than or equal to 3 hours. Use validNaps method on TSSleepDailyModel to get the filtered subset.

  7. Quality score (0-100) is calculated based on total sleep duration, deep sleep percentage, and number of awakenings. Higher scores indicate better sleep quality.

  8. All callbacks are executed on the main thread. Perform heavy processing on background threads if needed.

  9. Sleep segments may span across calendar day boundaries when using the 20:00 day boundary rule. Handle time calculations carefully.

  10. Ensure device is synced and has sufficient battery before initiating large data sync operations to avoid incomplete transfers.