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.
| Property | Type | Description |
|---|---|---|
statisticsRule | TSSleepStatisticsRule | Statistics rule used for this sleep record |
dailySummary | TSSleepSummary * | Overall daily sleep summary with aggregated metrics |
rawSleepItems | NSArray<TSSleepDetailItem *> * | Raw sleep detail items synced from device before processing |
nightSleeps | NSArray<TSSleepSegment *> * | Night sleep segments for this day |
daytimeSleeps | NSArray<TSSleepSegment *> * | All daytime sleep segments classified for this day |
TSSleepDetailItem
Single sleep stage segment containing stage type, start time, and duration.
| Property | Type | Description |
|---|---|---|
stage | TSSleepStage | Sleep stage type (Awake/Light/Deep/REM) |
belongingDate | NSTimeInterval | Timestamp 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.
| Property | Type | Description |
|---|---|---|
periodType | TSSleepPeriodType | Sleep period type (Night/Daytime) |
summary | TSSleepSummary * | Statistical summary of this sleep segment |
detailItems | NSArray<TSSleepDetailItem *> * | Detailed sleep stage items in chronological order |
TSSleepSummary
Statistical summary of sleep data including duration, quality, and stage breakdown.
| Property | Type | Description |
|---|---|---|
startTime | NSTimeInterval | Unix timestamp of sleep start time |
endTime | NSTimeInterval | Unix timestamp of sleep end time |
duration | NSTimeInterval | Total duration from start to end (seconds) |
totalSleepDuration | NSTimeInterval | Total effective sleep time excluding awake periods (seconds) |
qualityScore | UInt8 | Sleep quality score (0-100) |
awakeDuration | NSTimeInterval | Total awake duration during sleep period (seconds) |
lightSleepDuration | NSTimeInterval | Total light sleep duration (seconds) |
deepSleepDuration | NSTimeInterval | Total deep sleep duration (seconds) |
remDuration | NSTimeInterval | Total REM sleep duration (seconds) |
awakePercentage | UInt8 | Awake percentage relative to total sleep duration |
lightSleepPercentage | UInt8 | Light sleep percentage relative to total sleep duration |
deepSleepPercentage | UInt8 | Deep sleep percentage relative to total sleep duration |
remPercentage | UInt8 | REM sleep percentage relative to total sleep duration |
awakeCount | UInt16 | Number of awake episodes |
lightSleepCount | UInt16 | Number of light sleep episodes |
deepSleepCount | UInt16 | Number of deep sleep episodes |
remCount | UInt16 | Number of REM episodes |
Enumerations
TSSleepStage
Sleep stage type enumeration according to AASM standards.
| Value | Description |
|---|---|
TSSleepStageAwake | Awake stage during sleep period |
TSSleepStageLight | Light sleep stage (N1 and N2 phases) |
TSSleepStageDeep | Deep sleep stage (N3 phase, slow-wave sleep) |
TSSleepStageREM | Rapid Eye Movement sleep phase (dream sleep) |
TSSleepPeriodType
Sleep period type enumeration based on data header time.
| Value | Description |
|---|---|
TSSleepPeriodTypeNight | Night sleep period [20:00-09:00) |
TSSleepPeriodTypeDaytime | Daytime sleep period [09:00-20:00) |
TSSleepStatisticsRule
Sleep statistics rule type based on device capabilities.
| Value | Description |
|---|---|
TSSleepStatisticsRuleWithoutNap | No nap support; sensor active 20:00-12:00; all sleep treated as night sleep |
TSSleepStatisticsRuleWithNap | Nap support enabled; sensor active 24h; distinguishes night/day sleep |
TSSleepStatisticsRuleLongestNight | Uses longest continuous night sleep segment (20:00-08:00); valid naps counted |
TSSleepStatisticsRuleLongestOnly | No 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.
| Parameter | Type | Description |
|---|---|---|
| return | TSSleepStatisticsRule | Enum 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.
| Parameter | Type | Description |
|---|---|---|
| return | BOOL | YES 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.
| Parameter | Type | Description |
|---|---|---|
startTime | NSTimeInterval | Unix timestamp (seconds) of the starting point |
completion | void (^)(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.
| Parameter | Type | Description |
|---|---|---|
startTime | NSTimeInterval | Unix timestamp (seconds) of range start (inclusive) |
endTime | NSTimeInterval | Unix timestamp (seconds) of range end (exclusive); range is [startTime, endTime) |
completion | void (^)(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.
| Parameter | Type | Description |
|---|---|---|
startTime | NSTimeInterval | Unix timestamp (seconds) of the starting day |
completion | void (^)(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.
| Parameter | Type | Description |
|---|---|---|
startTime | NSTimeInterval | Unix timestamp (seconds) of range start day (inclusive) |
endTime | NSTimeInterval | Unix timestamp (seconds) of range end day (exclusive); range is [startTime, endTime) |
completion | void (^)(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
-
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.
-
Different devices support different statistics rules. Call
sleepStatisticsRulebefore processing to determine the appropriate algorithm for your device. -
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.
-
Time ranges for sync methods use Unix timestamps in seconds. The range [startTime, endTime) is inclusive of start and exclusive of end.
-
REM sleep support varies by device. Check
isSupportREMSleepbefore relying on REM stage data in analysis. -
Valid naps are filtered by duration: greater than or equal to 20 minutes and less than or equal to 3 hours. Use
validNapsmethod onTSSleepDailyModelto get the filtered subset. -
Quality score (0-100) is calculated based on total sleep duration, deep sleep percentage, and number of awakenings. Higher scores indicate better sleep quality.
-
All callbacks are executed on the main thread. Perform heavy processing on background threads if needed.
-
Sleep segments may span across calendar day boundaries when using the 20:00 day boundary rule. Handle time calculations carefully.
-
Ensure device is synced and has sufficient battery before initiating large data sync operations to avoid incomplete transfers.