Skip to main content

Stress

The Stress module provides comprehensive stress measurement and monitoring capabilities for wearable devices. It supports both manual user-initiated stress measurements and automatic background monitoring, with real-time data streaming and historical data synchronization features.

Prerequisites

  • Device must support stress measurement or monitoring functionality
  • Device must be properly connected and paired with the iOS app
  • For automatic monitoring, device firmware must support background monitoring capabilities
  • Time parameters for data synchronization should use Unix timestamps (seconds since 1970)

Data Models

TSStressValueItem

Single stress sample or measurement record.

PropertyTypeDescription
stressValueUInt8Stress level value, typically on a 0–100 scale
isUserInitiatedBOOLIndicates whether the measurement was user-initiated (YES) or automatically monitored (NO)
startTimeNSTimeIntervalStart time of the measurement (inherited from TSHealthValueItem)
endTimeNSTimeIntervalEnd time of the measurement (inherited from TSHealthValueItem)
durationNSTimeIntervalDuration of the measurement in seconds
valueTypeTSHealthValueTypeType indicator for the value (e.g., min, max, normal)

TSStressDailyModel

Per-day aggregated stress data model that extends TSHealthDailyModel.

PropertyTypeDescription
maxStressItemTSStressValueItem *The highest stress measurement recorded for the day
minStressItemTSStressValueItem *The lowest stress measurement recorded for the day
manualItemsNSArray<TSStressValueItem *>Array of user-initiated stress measurements, ordered chronologically
autoItemsNSArray<TSStressValueItem *>Array of automatically monitored stress items, ordered chronologically
dayStartTimeNSTimeIntervalStart time of the calendar day in UTC (inherited from TSHealthDailyModel)

Enumerations

No public enumerations are defined in this module. The module uses standard types from TSHealthValueType for value categorization.

Callback Types

Stress Measurement Start Handler

void (^)(BOOL success, NSError * _Nullable error)

Completion block invoked when stress measurement starts or fails to start.

ParameterTypeDescription
successBOOLYES if measurement started successfully; NO otherwise
errorNSError *Error information if startup failed; nil if successful

Stress Data Handler

void (^)(TSStressValueItem * _Nullable data, NSError * _Nullable error)

Completion block that receives real-time measurement data during an active measurement.

ParameterTypeDescription
dataTSStressValueItem *Real-time stress measurement data; nil if an error occurred
errorNSError *Error information if data reception failed; nil if successful

Stress Measurement End Handler

void (^)(BOOL success, NSError * _Nullable error)

Completion block invoked when measurement ends normally or abnormally.

ParameterTypeDescription
successBOOLYES if measurement ended normally; NO if interrupted
errorNSError *Error information if measurement ended abnormally; nil if normal end

Auto Monitor Configs Completion Handler

void (^)(TSAutoMonitorConfigs * _Nullable configuration, NSError * _Nullable error)

Completion block that delivers current automatic monitoring configuration or error.

ParameterTypeDescription
configurationTSAutoMonitorConfigs *Current automatic monitoring configuration; nil if retrieval failed
errorNSError *Error information if configuration retrieval failed; nil if successful

Raw Data Sync Completion Handler

void (^)(NSArray<TSStressValueItem *> * _Nullable stressItems, NSError * _Nullable error)

Completion block that delivers synchronized raw stress measurement items or error.

ParameterTypeDescription
stressItemsNSArray<TSStressValueItem *> *Synchronized raw stress measurement items; nil if sync failed
errorNSError *Error information if synchronization failed; nil if successful

Daily Data Sync Completion Handler

void (^)(NSArray<TSStressDailyModel *> * _Nullable dailyModels, NSError * _Nullable error)

Completion block that delivers synchronized daily aggregated stress data or error.

ParameterTypeDescription
dailyModelsNSArray<TSStressDailyModel *> *Synchronized daily stress models, each representing one day; nil if sync failed
errorNSError *Error information if synchronization failed; nil if successful

API Reference

Check Manual Stress Measurement Support

Determines whether the connected device supports manual (user-initiated) stress measurement.

- (BOOL)isSupportActivityMeasureByUser;

**Return Value**

TypeDescription
BOOLYES if the device supports manual stress measurement; NO otherwise

**Code Example**

id<TSStressInterface> stressInterface = /* obtained from health manager */;

if ([stressInterface isSupportActivityMeasureByUser]) {
TSLog(@"Device supports manual stress measurement");
} else {
TSLog(@"Device does not support manual stress measurement");
}

Start Stress Measurement

Initiates a stress measurement with specified parameters and real-time data streaming callbacks.

- (void)startMeasureWithParam:(TSActivityMeasureParam *_Nonnull)measureParam
startHandler:(void(^_Nullable)(BOOL success, NSError * _Nullable error))startHandler
dataHandler:(void(^_Nullable)(TSStressValueItem * _Nullable data, NSError * _Nullable error))dataHandler
endHandler:(void(^_Nullable)(BOOL success, NSError * _Nullable error))endHandler;

**Parameters**

NameTypeDescription
measureParamTSActivityMeasureParam *Measurement parameters specifying duration, target settings, etc.
startHandlervoid (^)(BOOL, NSError *)Called when measurement starts or fails to start
dataHandlervoid (^)(TSStressValueItem *, NSError *)Called repeatedly with real-time measurement data
endHandlervoid (^)(BOOL, NSError *)Called when measurement completes or terminates

**Code Example**

id<TSStressInterface> stressInterface = /* obtained from health manager */;
TSActivityMeasureParam *param = [[TSActivityMeasureParam alloc] init];
param.duration = 60; // 60 seconds measurement

[stressInterface startMeasureWithParam:param
startHandler:^(BOOL success, NSError *error) {
if (success) {
TSLog(@"Stress measurement started successfully");
} else {
TSLog(@"Failed to start measurement: %@", error.localizedDescription);
}
} dataHandler:^(TSStressValueItem *data, NSError *error) {
if (data) {
TSLog(@"Real-time stress value: %d", data.stressValue);
} else {
TSLog(@"Data error: %@", error.localizedDescription);
}
} endHandler:^(BOOL success, NSError *error) {
if (success) {
TSLog(@"Measurement completed normally");
} else {
TSLog(@"Measurement interrupted: %@", error.localizedDescription);
}
}];

Stop Stress Measurement

Halts an ongoing stress measurement.

- (void)stopMeasureCompletion:(nonnull TSCompletionBlock)completion;

**Parameters**

NameTypeDescription
completionTSCompletionBlockCompletion block called when measurement stops or fails to stop

**Code Example**

id<TSStressInterface> stressInterface = /* obtained from health manager */;

[stressInterface stopMeasureCompletion:^(NSError *error) {
if (error) {
TSLog(@"Failed to stop measurement: %@", error.localizedDescription);
} else {
TSLog(@"Stress measurement stopped successfully");
}
}];

Check Automatic Stress Monitoring Support

Determines whether the connected device supports automatic background stress monitoring.

- (BOOL)isSupportAutomaticMonitoring;

**Return Value**

TypeDescription
BOOLYES if the device supports automatic stress monitoring; NO otherwise

**Code Example**

id<TSStressInterface> stressInterface = /* obtained from health manager */;

if ([stressInterface isSupportAutomaticMonitoring]) {
TSLog(@"Device supports automatic stress monitoring");
} else {
TSLog(@"Device does not support automatic monitoring");
}

Check Monitor Schedule Time Support

Determines whether the device supports configuring specific time ranges for stress monitoring.

- (BOOL)isSupportMonitorScheduleTime;

**Return Value**

TypeDescription
BOOLYES if the device supports configuring start/end times for monitoring; NO otherwise

**Code Example**

id<TSStressInterface> stressInterface = /* obtained from health manager */;

if ([stressInterface isSupportMonitorScheduleTime]) {
TSLog(@"Device supports configuring monitor time range");
} else {
TSLog(@"Device does not support time range configuration");
}

Check Monitor Interval Support

Determines whether the device supports configuring the monitoring interval between measurements.

- (BOOL)isSupportMonitorScheduleInterval;

**Return Value**

TypeDescription
BOOLYES if the device supports configuring monitoring interval; NO otherwise

**Code Example**

id<TSStressInterface> stressInterface = /* obtained from health manager */;

if ([stressInterface isSupportMonitorScheduleInterval]) {
TSLog(@"Device supports configuring monitor interval");
} else {
TSLog(@"Device does not support interval configuration");
}

Configure Automatic Stress Monitoring

Applies automatic stress monitoring configuration to the device.

- (void)pushAutoMonitorConfigs:(TSAutoMonitorConfigs *_Nonnull)configuration
completion:(nonnull TSCompletionBlock)completion;

**Parameters**

NameTypeDescription
configurationTSAutoMonitorConfigs *Automatic monitoring configuration parameters
completionTSCompletionBlockCompletion block called when configuration is set or fails

**Code Example**

id<TSStressInterface> stressInterface = /* obtained from health manager */;

TSAutoMonitorConfigs *config = [[TSAutoMonitorConfigs alloc] init];
config.enabled = YES;
config.monitorSchedule = [[TSMonitorSchedule alloc] init];
config.monitorSchedule.startTime = 8; // 08:00
config.monitorSchedule.endTime = 22; // 22:00
config.monitorSchedule.interval = 30; // Every 30 minutes

[stressInterface pushAutoMonitorConfigs:config completion:^(NSError *error) {
if (error) {
TSLog(@"Failed to set monitoring config: %@", error.localizedDescription);
} else {
TSLog(@"Monitoring configuration updated successfully");
}
}];

Fetch Current Automatic Monitoring Configuration

Retrieves the current automatic stress monitoring configuration from the device.

- (void)fetchAutoMonitorConfigsWithCompletion:(nonnull void (^)(TSAutoMonitorConfigs *_Nullable configuration, NSError *_Nullable error))completion;

**Parameters**

NameTypeDescription
completionvoid (^)(TSAutoMonitorConfigs *, NSError *)Completion block with current configuration or error

**Code Example**

id<TSStressInterface> stressInterface = /* obtained from health manager */;

[stressInterface fetchAutoMonitorConfigsWithCompletion:^(TSAutoMonitorConfigs *config, NSError *error) {
if (error) {
TSLog(@"Failed to fetch monitoring config: %@", error.localizedDescription);
} else {
TSLog(@"Enabled: %@", config.enabled ? @"YES" : @"NO");
TSLog(@"Interval: %ld minutes", (long)config.monitorSchedule.interval);
}
}];

Synchronize Raw Stress Data (Time Range)

Synchronizes detailed raw stress measurement data within a specified time range.

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

**Parameters**

NameTypeDescription
startTimeNSTimeIntervalStart time for synchronization (Unix timestamp in seconds)
endTimeNSTimeIntervalEnd time for synchronization (Unix timestamp in seconds)
completionvoid (^)(NSArray *, NSError *)Completion block with raw stress items or error

**Code Example**

id<TSStressInterface> stressInterface = /* obtained from health manager */;

NSDate *today = [NSDate date];
NSTimeInterval endTime = [today timeIntervalSince1970];
NSTimeInterval startTime = endTime - (7 * 24 * 3600); // 7 days ago

[stressInterface syncRawDataFromStartTime:startTime
endTime:endTime
completion:^(NSArray<TSStressValueItem *> *items, NSError *error) {
if (error) {
TSLog(@"Sync failed: %@", error.localizedDescription);
} else {
TSLog(@"Synced %ld raw stress items", (long)items.count);
for (TSStressValueItem *item in items) {
TSLog(@"Stress: %d at %.0f", item.stressValue, item.startTime);
}
}
}];

Synchronize Raw Stress Data (From Start Time)

Synchronizes detailed raw stress measurement data from a specified start time until now.

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

**Parameters**

NameTypeDescription
startTimeNSTimeIntervalStart time for synchronization (Unix timestamp in seconds)
completionvoid (^)(NSArray *, NSError *)Completion block with raw stress items or error

**Code Example**

id<TSStressInterface> stressInterface = /* obtained from health manager */;

NSDate *oneWeekAgo = [[NSDate date] dateByAddingTimeInterval:-(7 * 24 * 3600)];
NSTimeInterval startTime = [oneWeekAgo timeIntervalSince1970];

[stressInterface syncRawDataFromStartTime:startTime
completion:^(NSArray<TSStressValueItem *> *items, NSError *error) {
if (error) {
TSLog(@"Sync failed: %@", error.localizedDescription);
} else {
TSLog(@"Synced %ld items from last week to now", (long)items.count);
}
}];

Synchronize Daily Stress Data (Time Range)

Synchronizes aggregated daily stress data within a specified time range.

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

**Parameters**

NameTypeDescription
startTimeNSTimeIntervalStart time (Unix timestamp); auto-normalized to 00:00:00 of the day
endTimeNSTimeIntervalEnd time (Unix timestamp); auto-normalized to 23:59:59 of the day
completionvoid (^)(NSArray *, NSError *)Completion block with daily models or error

**Code Example**

id<TSStressInterface> stressInterface = /* obtained from health manager */;

NSDate *today = [NSDate date];
NSTimeInterval endTime = [today timeIntervalSince1970];
NSTimeInterval startTime = endTime - (30 * 24 * 3600); // 30 days ago

[stressInterface syncDailyDataFromStartTime:startTime
endTime:endTime
completion:^(NSArray<TSStressDailyModel *> *models, NSError *error) {
if (error) {
TSLog(@"Daily sync failed: %@", error.localizedDescription);
} else {
TSLog(@"Synced %ld days of stress data", (long)models.count);
for (TSStressDailyModel *daily in models) {
TSLog(@"Date: %.0f | Max: %d | Min: %d | Manual: %ld | Auto: %ld",
daily.dayStartTime,
[daily maxStress],
[daily minStress],
(long)daily.manualItems.count,
(long)daily.autoItems.count);
}
}
}];

Synchronize Daily Stress Data (From Start Time)

Synchronizes aggregated daily stress data from a specified start time until now.

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

**Parameters**

NameTypeDescription
startTimeNSTimeIntervalStart time (Unix timestamp); auto-normalized to 00:00:00 of the day
completionvoid (^)(NSArray *, NSError *)Completion block with daily models or error

**Code Example**

id<TSStressInterface> stressInterface = /* obtained from health manager */;

NSDate *twoMonthsAgo = [[NSDate date] dateByAddingTimeInterval:-(60 * 24 * 3600)];
NSTimeInterval startTime = [twoMonthsAgo timeIntervalSince1970];

[stressInterface syncDailyDataFromStartTime:startTime
completion:^(NSArray<TSStressDailyModel *> *models, NSError *error) {
if (error) {
TSLog(@"Daily sync failed: %@", error.localizedDescription);
} else {
TSLog(@"Synced %ld days from past two months", (long)models.count);
for (TSStressDailyModel *daily in models) {
NSArray *allItems = [daily allMeasuredItems];
TSLog(@"Total measurements this day: %ld", (long)allItems.count);
}
}
}];

Get Maximum Stress Value

Retrieves the maximum stress level for a given day from a daily model.

- (UInt8)maxStress;

**Return Value**

TypeDescription
UInt8Maximum stress value on 0–100 scale; 0 if no maximum item recorded

**Code Example**

TSStressDailyModel *dailyModel = /* obtained from sync */;
UInt8 maxValue = [dailyModel maxStress];
TSLog(@"Today's peak stress: %d", maxValue);

Get Minimum Stress Value

Retrieves the minimum stress level for a given day from a daily model.

- (UInt8)minStress;

**Return Value**

TypeDescription
UInt8Minimum stress value on 0–100 scale; 0 if no minimum item recorded

**Code Example**

TSStressDailyModel *dailyModel = /* obtained from sync */;
UInt8 minValue = [dailyModel minStress];
TSLog(@"Today's lowest stress: %d", minValue);

Get All Measured Items

Retrieves a combined, chronologically sorted array of both manual and automatic stress measurements for a day.

- (NSArray<TSStressValueItem *> *)allMeasuredItems;

**Return Value**

TypeDescription
NSArray<TSStressValueItem *> *Merged and sorted array of manual and automatic stress items

**Code Example**

TSStressDailyModel *dailyModel = /* obtained from sync */;
NSArray<TSStressValueItem *> *allItems = [dailyModel allMeasuredItems];

for (TSStressValueItem *item in allItems) {
NSString *source = item.isUserInitiated ? @"Manual" : @"Auto";
TSLog(@"[%@] Stress: %d at %.0f", source, item.stressValue, item.startTime);
}

Build Daily Models from Database Rows

Constructs daily stress models from flat database row dictionaries grouped by calendar day.

+ (NSArray<TSStressDailyModel *> *)dailyModelsFromDBDicts:(NSArray<NSDictionary *> *)dicts;

**Parameters**

NameTypeDescription
dictsNSArray<NSDictionary *> *Array of row dictionaries with fields like value, valueType, startTime, endTime, dayStartTime

**Return Value**

TypeDescription
NSArray<TSStressDailyModel *> *Array of daily models sorted by day; empty array if input is nil/empty

**Code Example**

NSArray<NSDictionary *> *rawRows = /* from database query */;
NSArray<TSStressDailyModel *> *dailyModels = [TSStressDailyModel dailyModelsFromDBDicts:rawRows];

for (TSStressDailyModel *daily in dailyModels) {
TSLog(@"%@", [daily debugDescription]);
}

Map Database Rows to Value Items

Converts an array of database row dictionaries into stress value item objects.

+ (NSArray<TSStressValueItem *> *)valueItemsFromDBDicts:(NSArray<NSDictionary *> *)dicts;

**Parameters**

NameTypeDescription
dictsNSArray<NSDictionary *> *Array of row dictionaries with fields like value, startTime, endTime, duration, isUserInitiated

**Return Value**

TypeDescription
NSArray<TSStressValueItem *> *Non-nil array of value items; empty array if input is nil/empty; invalid rows skipped

**Code Example**

NSArray<NSDictionary *> *rows = @[
@{ @"value": @75, @"startTime": @1700000000, @"endTime": @1700000060, @"isUserInitiated": @YES },
@{ @"value": @60, @"startTime": @1700001000, @"endTime": @1700001060, @"isUserInitiated": @NO }
];

NSArray<TSStressValueItem *> *items = [TSStressValueItem valueItemsFromDBDicts:rows];
for (TSStressValueItem *item in items) {
TSLog(@"%@", [item debugDescription]);
}

Map Single Database Row to Value Item

Converts a single database row dictionary into a stress value item object.

+ (nullable TSStressValueItem *)valueItemFromDBDict:(NSDictionary *)dict;

**Parameters**

NameTypeDescription
dictNSDictionary *Row dictionary with fields like value, valueType, startTime, endTime, duration, isUserInitiated

**Return Value**

TypeDescription
TSStressValueItem *Populated value item; nil if dict is nil

**Code Example**

NSDictionary *row = @{
@"value": @82,
@"startTime": @1700000000,
@"endTime": @1700000120,
@"isUserInitiated": @YES
};

TSStressValueItem *item = [TSStressValueItem valueItemFromDBDict:row];
if (item) {
TSLog(@"Stress value: %d", item.stressValue);
} else {
TSLog(@"Failed to parse row");
}

Important Notes

  1. **Measurement Support Check**: Always verify device capability using isSupportActivityMeasureByUser before initiating manual measurements to avoid errors.

  2. **Time Parameters**: All time parameters for data synchronization use Unix timestamps (seconds since January 1, 1970 UTC). Use [NSDate timeIntervalSince1970] to convert dates.

  3. **Auto Monitoring Configuration**: Call isSupportMonitorScheduleTime and isSupportMonitorScheduleInterval before setting corresponding fields in TSAutoMonitorConfigs to ensure device compatibility.

  4. **Daily Data Normalization**: The syncDailyDataFromStartTime:endTime:completion: method automatically normalizes start time to 00:00:00 and end time to 23:59:59 of the respective calendar days. Ensure start time is earlier than end time.

  5. **Data Ordering**: Both raw and daily stress data are returned in ascending chronological order. Use this guarantee for UI rendering and trend analysis.

  6. **Manual vs Automatic Items**: The TSStressDailyModel separates user-initiated measurements (manualItems) from background monitoring (autoItems) via the isUserInitiated flag on individual TSStressValueItem objects.

  7. **Callback Execution**: Data completion handlers are executed on the main thread. Perform long-running operations on background threads to avoid blocking UI updates.

  8. **Real-time Data Streaming**: The dataHandler in startMeasureWithParam:... may be called multiple times during an active measurement. Each callback delivers the latest measurement snapshot; process or aggregate as needed.

  9. **Measurement Cancellation**: Always call stopMeasureCompletion: when a user-initiated measurement should end, whether triggered by user action, timeout, or error recovery.

  10. **Error Handling**: Errors passed to completion handlers include domain and code information. Log the full error message to diagnose connectivity, device firmware, and permission issues.