PebbleOS
Loading...
Searching...
No Matches
Data Structures | Macros | Typedefs | Enumerations | Functions
Activity service internals

State, storage formats and helpers shared by the activity service sources. More...

Data Structures

struct  ActivitySettingsValueHistory
 History of a metric, as stored in the settings file. More...
 
struct  ActivityStepData
 Today's step metrics. More...
 
struct  ActivitySleepData
 Today's sleep metrics. More...
 
struct  ActivityHeartRateData
 Heart rate metrics. More...
 
struct  ActivityMetricInfo
 Storage information of a metric, filled by activity_metrics_prv_get_metric_info(). More...
 
struct  ActivityFeedSamples
 Samples fed by activity_test_feed_samples(). More...
 
struct  ActivityLegacySleepSessionDataLoggingRecord
 Legacy data logging record of a sleep session. More...
 
struct  ActivitySessionDataLoggingRecord
 Data logging record of an activity session. More...
 
struct  ActivitySampleCollectionData
 Raw accelerometer sample collection state. More...
 
struct  ActivityHRSupport
 Heart rate support state. More...
 
struct  ActivitySpO2Support
 Background SpO2 support state. More...
 
struct  ActivitySpO2ActivitySupport
 SpO2 reader state during detected activities. More...
 
struct  ActivityState
 Activity service state. More...
 
union  ActivitySessionDataLoggingRecord.__unnamed51__
 Type specific data (version 3). More...
 

Macros

#define ACTIVITY_SETTINGS_UPDATE_MIN   15
 Interval between saves of today's metrics to the settings file, in minutes.
 
#define ACTIVITY_SESSION_UPDATE_MIN   15
 Interval between recomputations of the activity sessions, in minutes.
 
#define ACTIVITY_SCALAR_MAX   UINT32_MAX
 Maximum value of ActivityScalarStore.
 
#define ACTIVITY_STEP_AVERAGES_MINUTES   (PBL_MIN_PER_DAY / ACTIVITY_NUM_METRIC_AVERAGES)
 Minutes covered by each step average.
 
#define ACTIVITY_STEP_AVERAGES_PER_KEY   4
 Step averages stored per settings key.
 
#define ACTIVITY_STEP_AVERAGES_KEYS_PER_DAY    (ACTIVITY_NUM_METRIC_AVERAGES / ACTIVITY_STEP_AVERAGES_PER_KEY)
 Settings keys holding one day of step averages.
 
#define ACTIVITY_ACTIVE_MINUTE_MIN_STEPS   40
 Minimum steps in a minute for it to be an active minute.
 
#define ACTIVITY_LAST_SLEEP_MINUTE_OF_DAY   (21 * PBL_MIN_PER_HOUR)
 Minute of the day (9pm) after which an ending sleep session counts as the next day's.
 
#define ACTIVITY_DEFAULT_HR_ON_TIME_SEC   (60)
 Default length of a background heart rate measurement window, in seconds.
 
#define ACTIVITY_HR_EARLY_ABORT_SEC   (40)
 Time into a heart rate window after which it is aborted without any valid reading, in seconds.
 
#define ACTIVITY_MIN_NUM_GOOD_SAMPLES_SHORT_CIRCUIT   (10)
 Good quality heart rate samples after which the window ends early.
 
#define ACTIVITY_MIN_NUM_EXCELLENT_SAMPLES_SHORT_CIRCUIT   (5)
 Excellent quality heart rate samples after which the window ends early.
 
#define ACTIVITY_MIN_NUM_GOOD_SPO2_SAMPLES_SHORT_CIRCUIT   (2)
 Good quality SpO2 samples after which the window ends early.
 
#define ACTIVITY_DEFAULT_SPO2_ON_TIME_SEC   (90)
 Maximum length of a background SpO2 measurement window, in seconds.
 
#define ACTIVITY_SPO2_EARLY_ABORT_SEC   (45)
 Time into a SpO2 window after which it is aborted if no sample was accepted, in seconds.
 
#define ACTIVITY_SPO2_ACTIVITY_INTERVAL_SEC   (5 * PBL_SEC_PER_MIN)
 Interval between SpO2 attempts during a detected activity, in seconds.
 
#define ACTIVITY_SPO2_ACTIVITY_ATTEMPT_SEC   (35)
 Duration of a SpO2 attempt during a detected activity, in seconds.
 
#define ACTIVITY_SPO2_ACTIVITY_BACKOFF_SEC   (PBL_SEC_PER_MIN)
 Heart rate time after a failed SpO2 attempt before retrying, in seconds.
 
#define ACTIVITY_MIN_NUM_SAMPLES_FOR_HR_ZONE   (5)
 Minimum heart rate samples in a minute to report a zone above zone 0.
 
#define ACTIVITY_HRM_SUBSCRIPTION_ON_PERIOD_SEC   (1)
 Heart rate subscription interval while sampling, in seconds.
 
#define ACTIVITY_HRM_SUBSCRIPTION_OFF_PERIOD_SEC   (PBL_SEC_PER_DAY)
 Heart rate subscription interval while idle, in seconds.
 
#define ACTIVITY_HRM_OFFWRIST_STALE_SEC   (15 * PBL_SEC_PER_MIN)
 Age after which the cached off-wrist status is stale, in seconds.
 
#define ACTIVITY_MAX_HR_SAMPLES   (3 * PBL_SEC_PER_MIN)
 Maximum number of heart rate samples kept to compute the median.
 
#define ACTIVITY_DAG_PER_KG   100
 Decagrams per kilogram.
 
#define ACTIVITY_SETTINGS_FILE_NAME   "activity"
 Name of the activity settings file.
 
#define ACTIVITY_SETTINGS_FILE_LEN   0x4000
 Size of the activity settings file, in bytes.
 
#define ACTIVITY_SETTINGS_CURRENT_VERSION   3
 Version of the activity settings file.
 
#define ACTIVITY_SLEEP_SESSION_LOGGING_VERSION   1
 Version of the legacy sleep session data logging records (before FW 3.11).
 
#define ACTIVITY_SESSION_LOGGING_VERSION   3
 Version of the activity session data logging records.
 

Typedefs

typedef uint32_t ActivityScalarStore
 Storage type of every scalar metric and setting, in RAM and in the settings file.
 
typedef uint32_t(* ActivityMetricConverter) (ActivityScalarStore storage_value)
 Convert a metric from its storage value to the activity_get_metric() value.
 
typedef void * ProtobufLogRef
 Measurements log handle.
 

Enumerations

enum  ActivitySettingsKey {
  ActivitySettingsKeyInvalid = 0 , ActivitySettingsKeyVersion , ActivitySettingsKeyUnused0 , ActivitySettingsKeyUnused1 ,
  ActivitySettingsKeyUnused2 , ActivitySettingsKeyUnused3 , ActivitySettingsKeyStepCountHistory , ActivitySettingsKeyStepMinutesHistory ,
  ActivitySettingsKeyUnused4 , ActivitySettingsKeyDistanceMetersHistory , ActivitySettingsKeySleepTotalMinutesHistory , ActivitySettingsKeySleepDeepMinutesHistory ,
  ActivitySettingsKeySleepEntryMinutesHistory , ActivitySettingsKeySleepEnterAtHistory , ActivitySettingsKeySleepExitAtHistory , ActivitySettingsKeySleepState ,
  ActivitySettingsKeySleepStateMinutes , ActivitySettingsKeyStepAveragesWeekdayFirst , ActivitySettingsKeyStepAveragesWeekdayLast , ActivitySettingsKeyStepAveragesWeekendFirst ,
  ActivitySettingsKeyStepAveragesWeekendLast , ActivitySettingsKeyAgeYears , ActivitySettingsKeyUnused5 , ActivitySettingsKeyInsightSleepRewardTime ,
  ActivitySettingsKeyInsightActivityRewardTime , ActivitySettingsKeyInsightActivitySummaryState , ActivitySettingsKeyInsightSleepSummaryState , ActivitySettingsKeyRestingKCaloriesHistory ,
  ActivitySettingsKeyActiveKCaloriesHistory , ActivitySettingsKeyLastSleepActivityUTC , ActivitySettingsKeyLastRestfulSleepActivityUTC , ActivitySettingsKeyLastStepActivityUTC ,
  ActivitySettingsKeyStoredActivities , ActivitySettingsKeyInsightNapSessionTime , ActivitySettingsKeyInsightActivitySessionTime , ActivitySettingsKeyLastVMC ,
  ActivitySettingsKeyRestingHeartRate , ActivitySettingsKeyHeartRateZone1Minutes , ActivitySettingsKeyHeartRateZone2Minutes , ActivitySettingsKeyHeartRateZone3Minutes
}
 Keys of the activity settings file. More...
 
enum  ActivitySpO2ActPhase { ActivitySpO2ActPhase_Idle = 0 , ActivitySpO2ActPhase_Wait , ActivitySpO2ActPhase_Sampling , ActivitySpO2ActPhase_Backoff }
 Phases of the SpO2 reader during detected activities. More...
 

Functions

ActivityState * activity_private_state (void)
 Get the activity state.
 
bool activity_is_hrm_present (void)
 Check whether a heart rate monitor is present.
 
SettingsFile * activity_private_settings_open (void)
 Open the activity settings file.
 
void activity_private_settings_close (SettingsFile *file)
 Close the activity settings file.
 
bool activity_test_reset (bool reset_settings, bool tracking_on, const ActivitySettingsValueHistory *sleep_history, const ActivitySettingsValueHistory *step_history)
 Reinitialize the activity service (test apps).
 
void activity_sessions_prv_init (SettingsFile *file, time_t utc_now)
 Load the stored activity sessions.
 
time_t activity_sessions_prv_get_sleep_window_start_utc (time_t now_utc)
 Get the start of the sleep day containing a time.
 
void activity_sessions_prv_get_sleep_bounds_utc (time_t now_utc, time_t *enter_utc, time_t *exit_utc)
 Get the sleep bounds of the current day.
 
void activity_sessions_prv_remove_out_of_range_activity_sessions (time_t utc_sec, bool remove_ongoing)
 Remove sessions older than today or in the future.
 
bool activity_sessions_prv_is_sleep_activity (ActivitySessionType activity_type)
 Check whether a session type is sleep related.
 
bool activity_sessions_is_session_type_ongoing (ActivitySessionType activity_type)
 Check whether a session of a type is ongoing.
 
void activity_sessions_prv_add_activity_session (ActivitySession *session)
 Register a new session, or update an existing one.
 
void activity_sessions_prv_delete_activity_session (ActivitySession *session)
 Delete a session.
 
void activity_sessions_prv_minute_handler (time_t utc_sec)
 Run the once a minute session maintenance.
 
void activity_sessions_prv_send_activity_session_to_data_logging (ActivitySession *session)
 Send a session to data logging.
 
void activity_metrics_prv_init (SettingsFile *file, time_t utc_now)
 Initialize all metrics from the settings file.
 
void activity_metrics_prv_get_metric_info (ActivityMetric metric, ActivityMetricInfo *info)
 Get the storage information of a metric.
 
void activity_metrics_prv_minute_handler (time_t utc_sec)
 Run the once a minute metrics maintenance.
 
uint32_t activity_metrics_prv_get_distance_mm (void)
 Get the distance covered today.
 
uint32_t activity_metrics_prv_get_resting_calories (void)
 Get the resting calories burned today.
 
uint32_t activity_metrics_prv_get_active_calories (void)
 Get the active calories burned today.
 
void activity_metrics_prv_get_median_hr_bpm (int32_t *median_out, int32_t *heart_rate_total_weight_x100_out)
 Get the median heart rate since the last reset.
 
HRZone activity_metrics_prv_get_hr_zone (void)
 Get the heart rate zone since the last reset.
 
void activity_metrics_prv_reset_hr_stats (void)
 Reset the median heart rate and the heart rate zone.
 
void activity_metrics_prv_get_spo2_sample (uint8_t *percent_out, uint8_t *quality_out)
 Consume the pending SpO2 reading for the current minute record.
 
void activity_metrics_prv_add_median_hr_sample (PebbleHRMEvent *hrm_event, time_t now_utc, time_t now_uptime)
 Add a heart rate sample to the median.
 
void activity_metrics_prv_set_hrm_worn_status (time_t now_utc, bool is_offwrist)
 Record the worn status reported by the HRM.
 
bool activity_metrics_prv_is_hrm_offwrist (time_t now_utc)
 Check whether the HRM recently reported the watch off-wrist.
 
uint32_t activity_metrics_prv_get_steps (void)
 Get the steps taken today.
 
ActivityScalarStore activity_metrics_prv_steps_per_minute (void)
 Get the steps taken in the past minute.
 
void activity_metrics_prv_set_metric (ActivityMetric metric, enum pbl_weekday day, int32_t value)
 Set a metric's value, on behalf of the phone (health database).
 
void activity_metrics_set_metric_exact (ActivityMetric metric, int32_t value)
 Force today's value of a metric, possibly decreasing it (QEMU and test injection).
 

Detailed Description

State, storage formats and helpers shared by the activity service sources.

Only for the activity service itself (activity.c, activity_metrics.c, activity_sessions.c, activity_insights.c), the workout service and their tests. Unless noted, functions must be called with the activity state mutex held.


Data Structure Documentation

◆ ActivitySettingsValueHistory

struct ActivitySettingsValueHistory

History of a metric, as stored in the settings file.

Data Fields
uint32_t utc_sec UTC time of the first entry.
ActivityScalarStore values[ACTIVITY_HISTORY_DAYS] One value per day, today at index 0.

◆ ActivityStepData

struct ActivityStepData

Today's step metrics.

Every member must be an ActivityScalarStore (see activity_metrics_prv_get_metric_info()).

Data Fields
ActivityScalarStore active_kcalories Active kcal.
ActivityScalarStore distance_meters Distance, in meters.
ActivityScalarStore resting_kcalories Resting kcal.
ActivityScalarStore step_minutes Active minutes.
ActivityScalarStore steps Steps.

◆ ActivitySleepData

struct ActivitySleepData

Today's sleep metrics.

Every member must be an ActivityScalarStore (see activity_metrics_prv_get_metric_info()).

Data Fields
ActivityScalarStore cur_state Current ActivitySleepState.
ActivityScalarStore cur_state_elapsed_minutes Minutes in the current sleep state.
ActivityScalarStore enter_at_minute Time the user fell asleep, in minutes after midnight.
ActivityScalarStore exit_at_minute Time the user woke up, in minutes after midnight.
ActivityScalarStore restful_minutes Restful sleep, in minutes.
ActivityScalarStore total_minutes Sleep, in minutes.

◆ ActivityHeartRateData

struct ActivityHeartRateData

Heart rate metrics.

Members are ActivityScalarStore except the update times, which are 32-bit metrics without history that are not persisted.

Data Fields
ActivityScalarStore current_bpm Most recent reading, in beats per minute.
ActivityScalarStore current_hr_zone Current HRZone.
ActivityScalarStore current_quality Quality of the most recent reading, an HRMQuality value.
uint32_t current_update_time_utc UTC time of the most recent reading.
bool is_hr_elevated Heart rate is elevated.
ActivityScalarStore last_stable_bpm Last stable (median) heart rate, in beats per minute.
uint32_t last_stable_bpm_update_time_utc UTC time of the last stable heart rate.
ActivityScalarStore minutes_in_zone[HRZoneCount] Minutes in each HRZone today.
ActivityScalarStore previous_median_bpm Median heart rate of the last minute, in beats per minute.
int32_t previous_median_total_weight_x100 Total weight of the last minute's samples, multiplied by 100.
ActivityScalarStore resting_bpm Resting heart rate, in beats per minute.

◆ ActivityMetricInfo

struct ActivityMetricInfo

Storage information of a metric, filled by activity_metrics_prv_get_metric_info().

Data Fields
ActivityMetricConverter converter Converter from storage value to returned value.
bool has_history Metric has history, which sets its size in the settings file.
ActivitySettingsKey settings_key Settings key.
ActivityScalarStore * value_p Value in RAM.
uint32_t * value_u32p Alternative value pointer for 32-bit metrics, which have no history and use ActivitySettingsKeyInvalid.

◆ ActivityFeedSamples

struct ActivityFeedSamples
Data Fields
AccelRawData data[] Samples.
uint16_t num_samples Number of samples in data.

◆ ActivityLegacySleepSessionDataLoggingRecord

struct ActivityLegacySleepSessionDataLoggingRecord

Legacy data logging record of a sleep session.

Data Fields
uint32_t end_utc End time, UTC.
uint32_t restful_secs Seconds of restful sleep.
uint32_t start_utc Start time, UTC.
int32_t utc_to_local Seconds to add to UTC to get local time.
uint16_t version ACTIVITY_SLEEP_SESSION_LOGGING_VERSION.

◆ ActivitySessionDataLoggingRecord

struct ActivitySessionDataLoggingRecord

Data logging record of an activity session.

Changing it requires bumping ACTIVITY_SESSION_LOGGING_VERSION.

Data Fields
union ActivitySessionDataLoggingRecord.__unnamed51__ __unnamed__ Type specific data (version 3).
uint16_t activity ActivitySessionType.
uint32_t elapsed_sec Duration, in seconds.
uint16_t size Size of this record, in bytes.
uint32_t start_utc Start time, UTC.
int32_t utc_to_local Seconds to add to UTC to get local time.
uint16_t version ACTIVITY_SESSION_LOGGING_VERSION.

◆ ActivitySampleCollectionData

struct ActivitySampleCollectionData

Raw accelerometer sample collection state.

Data Fields
char base64_buf[sizeof(ActivityRawSamplesRecord)] Buffer to base64 encode half a record at a time.
DataLoggingSession * dls_session Data logging session of the collection session.
bool first_record The first record is being built.
uint32_t prev_sample Last encoded sample, used to detect runs (see ACTIVITY_RAW_SAMPLES_VERSION).
ActivityRawSamplesRecord record Record being built.
uint8_t run_size Run size of prev_sample.

◆ ActivityHRSupport

struct ActivityHRSupport

Heart rate support state.

Data Fields
bool currently_sampling Sampling is active.
HRMSessionRef hrm_session HRM manager session.
time_t last_quality_event_utc UTC time of the last BPM event, 0 if none.

Used by sleep tracking to detect off-wrist.

bool last_quality_was_offwrist Last BPM event reported off-wrist.
uint32_t last_sample_ts Uptime, in seconds, of the last sample.
ProtobufLogRef log_session Measurements log the samples are sent to.
ActivityHeartRateData metrics Heart rate metrics.
uint16_t num_excellent_samples Excellent quality samples in the past minute.
uint16_t num_good_quality_samples Good quality samples in the past minute.
uint16_t num_samples Samples in the past minute.
uint8_t samples[ACTIVITY_MAX_HR_SAMPLES] Stored samples, in beats per minute.
uint32_t toggled_sampling_at_ts Uptime, in seconds, of the last sampling toggle.
uint8_t weights[ACTIVITY_MAX_HR_SAMPLES] Weights of the stored samples.

◆ ActivitySpO2Support

struct ActivitySpO2Support

Background SpO2 support state.

Data Fields
bool currently_sampling Sampling is active.
HRMSessionRef hrm_session HRM manager session used for SpO2.
uint16_t num_good_quality_samples Good quality samples in the current window.
uint8_t pending_percent Pending saturation for the next minute record, in percent, 0 if none.
uint8_t pending_quality Pending quality on the 0-7 HeartRateQuality scale, 0 if none.
uint32_t toggled_sampling_at_ts Uptime, in seconds, of the last sampling toggle.

◆ ActivitySpO2ActivitySupport

struct ActivitySpO2ActivitySupport

SpO2 reader state during detected activities.

Data Fields
bool got_reading A valid reading arrived during this attempt.
HRMSessionRef hrm_session Dedicated SpO2 session, only sampled during an attempt.
ActivitySpO2ActPhase phase Current phase.
uint32_t phase_started_ts Uptime, in seconds, at which the current phase began.
bool update_pending A KernelBG callback running the state machine is queued.

◆ ActivityState

struct ActivityState

Activity service state.

Data Fields
AccelServiceState * accel_session Accelerometer session.
uint32_t active_calories Active calories today (1/1000 kcal).
DataLoggingSession * activity_dls_session Data logging session for activity sessions.
time_t activity_event_start_utc UTC time of the first active minute of a significant activity event, 0 if none.
ActivitySession activity_sessions[ACTIVITY_MAX_ACTIVITY_SESSIONS_COUNT] Captured sessions.
uint16_t activity_sessions_count Number of valid entries in activity_sessions.
ActivitySpO2ActivitySupport activity_spo2 SpO2 during detected activities.
struct pbl_sem bg_wait_semaphore Semaphore to wait for KernelBG callbacks to finish.
EventServiceInfo charger_subscription Battery state subscription, to track the charger.
uint16_t cur_day_index Current day index.
uint32_t distance_mm Distance today, in millimeters.
bool enabled_charging_state The charging state allows the service.
bool enabled_run_level The run level allows the service (services_set_runlevel()).
ActivityHRSupport hr Heart rate support.
uint16_t last_active_minute Last minute of the day with significant steps, used to compute the time to fall asleep.
uint8_t last_orientation Orientation of the last minute.
ActivityScalarStore last_vmc VMC of the last minute.
time_t logged_restful_sleep_activity_exit_at_utc End time of the last logged restful sleep activity, UTC.
time_t logged_sleep_activity_exit_at_utc End time of the last logged sleep activity, UTC.
time_t logged_step_activity_exit_at_utc End time of the last logged step activity, UTC.
struct pbl_mutex mutex Mutex serializing access to the state.
bool need_activities_saved Sessions need to be persisted.
bool pending_test_cb A test feed callback is pending on KernelBG.
time_t rate_last_update_time UTC time of the last rate update.
uint32_t resting_calories Resting calories today (1/1000 kcal).
ActivitySampleCollectionData * sample_collection_data Raw sample collection state, allocated while collecting.
bool sample_collection_enabled Raw sample collection is enabled.
uint16_t sample_collection_num_samples Samples collected so far.
time_t sample_collection_seconds While collecting, UTC time collection started; otherwise seconds of data in the last session.
uint16_t sample_collection_session_id Raw sample collection session id.
bool should_be_started Tracking should run; kept while disabled so tracking restarts when re-enabled.
ActivitySleepData sleep_data Today's sleep metrics.
bool sleep_sessions_modified A new sleep session was registered.
ActivitySpO2Support spo2 Background SpO2 support.
bool started Tracking is running; only set while enabled.
ActivityStepData step_data Today's step metrics.
ActivityScalarStore steps_per_minute Average steps per minute over the last minute.
ActivityScalarStore steps_per_minute_last_steps Step count when steps_per_minute was last computed.
bool test_mode activity_start_tracking() was called in test mode.
int8_t update_settings_counter Minutes until the next settings file update.

◆ ActivitySessionDataLoggingRecord.__unnamed51__

union ActivitySessionDataLoggingRecord.__unnamed51__

Type specific data (version 3).

Data Fields
ActivitySessionDataSleeping sleep_data Data of sleep sessions.
ActivitySessionDataStepping step_data Data of step based sessions.

Macro Definition Documentation

◆ ACTIVITY_ACTIVE_MINUTE_MIN_STEPS

#define ACTIVITY_ACTIVE_MINUTE_MIN_STEPS   40

Minimum steps in a minute for it to be an active minute.

◆ ACTIVITY_DAG_PER_KG

#define ACTIVITY_DAG_PER_KG   100

Decagrams per kilogram.

◆ ACTIVITY_DEFAULT_HR_ON_TIME_SEC

#define ACTIVITY_DEFAULT_HR_ON_TIME_SEC   (60)

Default length of a background heart rate measurement window, in seconds.

◆ ACTIVITY_DEFAULT_SPO2_ON_TIME_SEC

#define ACTIVITY_DEFAULT_SPO2_ON_TIME_SEC   (90)

Maximum length of a background SpO2 measurement window, in seconds.

Longer than the heart rate window since SpO2 typically needs about 30 s to converge; bounds the high-current red/IR LED on-time when no reading comes.

◆ ACTIVITY_HR_EARLY_ABORT_SEC

#define ACTIVITY_HR_EARLY_ABORT_SEC   (40)

Time into a heart rate window after which it is aborted without any valid reading, in seconds.

The HR model converges in about 9 s, so no reading by then means poor contact, off-wrist or heavy motion. Any reading, even of acceptable quality, keeps the window running.

◆ ACTIVITY_HRM_OFFWRIST_STALE_SEC

#define ACTIVITY_HRM_OFFWRIST_STALE_SEC   (15 * PBL_SEC_PER_MIN)

Age after which the cached off-wrist status is stale, in seconds.

Sleep detection then falls back to its accelerometer based not-worn heuristics. Covers the default 10 minute heart rate interval; with longer intervals the cache expires between measurements.

◆ ACTIVITY_HRM_SUBSCRIPTION_OFF_PERIOD_SEC

#define ACTIVITY_HRM_SUBSCRIPTION_OFF_PERIOD_SEC   (PBL_SEC_PER_DAY)

Heart rate subscription interval while idle, in seconds.

◆ ACTIVITY_HRM_SUBSCRIPTION_ON_PERIOD_SEC

#define ACTIVITY_HRM_SUBSCRIPTION_ON_PERIOD_SEC   (1)

Heart rate subscription interval while sampling, in seconds.

◆ ACTIVITY_LAST_SLEEP_MINUTE_OF_DAY

#define ACTIVITY_LAST_SLEEP_MINUTE_OF_DAY   (21 * PBL_MIN_PER_HOUR)

Minute of the day (9pm) after which an ending sleep session counts as the next day's.

◆ ACTIVITY_MAX_HR_SAMPLES

#define ACTIVITY_MAX_HR_SAMPLES   (3 * PBL_SEC_PER_MIN)

Maximum number of heart rate samples kept to compute the median.

◆ ACTIVITY_MIN_NUM_EXCELLENT_SAMPLES_SHORT_CIRCUIT

#define ACTIVITY_MIN_NUM_EXCELLENT_SAMPLES_SHORT_CIRCUIT   (5)

Excellent quality heart rate samples after which the window ends early.

◆ ACTIVITY_MIN_NUM_GOOD_SAMPLES_SHORT_CIRCUIT

#define ACTIVITY_MIN_NUM_GOOD_SAMPLES_SHORT_CIRCUIT   (10)

Good quality heart rate samples after which the window ends early.

◆ ACTIVITY_MIN_NUM_GOOD_SPO2_SAMPLES_SHORT_CIRCUIT

#define ACTIVITY_MIN_NUM_GOOD_SPO2_SAMPLES_SHORT_CIRCUIT   (2)

Good quality SpO2 samples after which the window ends early.

Kept low: good readings are hard to get on the wrist.

◆ ACTIVITY_MIN_NUM_SAMPLES_FOR_HR_ZONE

#define ACTIVITY_MIN_NUM_SAMPLES_FOR_HR_ZONE   (5)

Minimum heart rate samples in a minute to report a zone above zone 0.

◆ ACTIVITY_SCALAR_MAX

#define ACTIVITY_SCALAR_MAX   UINT32_MAX

Maximum value of ActivityScalarStore.

◆ ACTIVITY_SESSION_LOGGING_VERSION

#define ACTIVITY_SESSION_LOGGING_VERSION   3

Version of the activity session data logging records.

Treated as a bitfield by the mobile app: while bit 0 is set, fields may be appended to ActivitySessionDataLoggingRecord; clearing it marks the record unparseable.

◆ ACTIVITY_SESSION_UPDATE_MIN

#define ACTIVITY_SESSION_UPDATE_MIN   15

Interval between recomputations of the activity sessions, in minutes.

◆ ACTIVITY_SETTINGS_CURRENT_VERSION

#define ACTIVITY_SETTINGS_CURRENT_VERSION   3

Version of the activity settings file.

◆ ACTIVITY_SETTINGS_FILE_LEN

#define ACTIVITY_SETTINGS_FILE_LEN   0x4000

Size of the activity settings file, in bytes.

◆ ACTIVITY_SETTINGS_FILE_NAME

#define ACTIVITY_SETTINGS_FILE_NAME   "activity"

Name of the activity settings file.

◆ ACTIVITY_SETTINGS_UPDATE_MIN

#define ACTIVITY_SETTINGS_UPDATE_MIN   15

Interval between saves of today's metrics to the settings file, in minutes.

◆ ACTIVITY_SLEEP_SESSION_LOGGING_VERSION

#define ACTIVITY_SLEEP_SESSION_LOGGING_VERSION   1

Version of the legacy sleep session data logging records (before FW 3.11).

Treated as a bitfield by the mobile app: while bit 0 is set, fields may be appended to ActivityLegacySleepSessionDataLoggingRecord; clearing it marks the record unparseable.

◆ ACTIVITY_SPO2_ACTIVITY_ATTEMPT_SEC

#define ACTIVITY_SPO2_ACTIVITY_ATTEMPT_SEC   (35)

Duration of a SpO2 attempt during a detected activity, in seconds.

◆ ACTIVITY_SPO2_ACTIVITY_BACKOFF_SEC

#define ACTIVITY_SPO2_ACTIVITY_BACKOFF_SEC   (PBL_SEC_PER_MIN)

Heart rate time after a failed SpO2 attempt before retrying, in seconds.

◆ ACTIVITY_SPO2_ACTIVITY_INTERVAL_SEC

#define ACTIVITY_SPO2_ACTIVITY_INTERVAL_SEC   (5 * PBL_SEC_PER_MIN)

Interval between SpO2 attempts during a detected activity, in seconds.

◆ ACTIVITY_SPO2_EARLY_ABORT_SEC

#define ACTIVITY_SPO2_EARLY_ABORT_SEC   (45)

Time into a SpO2 window after which it is aborted if no sample was accepted, in seconds.

A converging reading gets accepted samples well before; none means poor contact, motion or off-wrist.

◆ ACTIVITY_STEP_AVERAGES_KEYS_PER_DAY

#define ACTIVITY_STEP_AVERAGES_KEYS_PER_DAY    (ACTIVITY_NUM_METRIC_AVERAGES / ACTIVITY_STEP_AVERAGES_PER_KEY)

Settings keys holding one day of step averages.

◆ ACTIVITY_STEP_AVERAGES_MINUTES

#define ACTIVITY_STEP_AVERAGES_MINUTES   (PBL_MIN_PER_DAY / ACTIVITY_NUM_METRIC_AVERAGES)

Minutes covered by each step average.

◆ ACTIVITY_STEP_AVERAGES_PER_KEY

#define ACTIVITY_STEP_AVERAGES_PER_KEY   4

Step averages stored per settings key.

Trades flash writes against the data lost on reset.

Typedef Documentation

◆ ActivityMetricConverter

typedef uint32_t(* ActivityMetricConverter) (ActivityScalarStore storage_value)

Convert a metric from its storage value to the activity_get_metric() value.

For example, minutes to seconds.

Parameters
storage_valueStored value.
Returns
Converted value.

◆ ActivityScalarStore

typedef uint32_t ActivityScalarStore

Storage type of every scalar metric and setting, in RAM and in the settings file.

Wide enough for daily step counts and distances in meters above UINT16_MAX.

◆ ProtobufLogRef

typedef void* ProtobufLogRef

Measurements log handle.

Defined in measurements_log.h, which cannot be included here because of the generated SDK files.

Enumeration Type Documentation

◆ ActivitySettingsKey

Keys of the activity settings file.

Values are persisted: new keys go at the end.

Enumerator
ActivitySettingsKeyInvalid 

Invalid key.

ActivitySettingsKeyVersion 

uint16_t: ACTIVITY_SETTINGS_CURRENT_VERSION.

ActivitySettingsKeyUnused0 

Unused.

ActivitySettingsKeyUnused1 

Unused.

ActivitySettingsKeyUnused2 

Unused.

ActivitySettingsKeyUnused3 

Unused.

ActivitySettingsKeyStepCountHistory 

Steps (ActivitySettingsValueHistory).

ActivitySettingsKeyStepMinutesHistory 

Active minutes (ActivitySettingsValueHistory).

ActivitySettingsKeyUnused4 

Unused.

ActivitySettingsKeyDistanceMetersHistory 

Distance, in meters (ActivitySettingsValueHistory).

ActivitySettingsKeySleepTotalMinutesHistory 

Sleep, in minutes (ActivitySettingsValueHistory).

ActivitySettingsKeySleepDeepMinutesHistory 

Restful sleep, in minutes (ActivitySettingsValueHistory).

ActivitySettingsKeySleepEntryMinutesHistory 

Minutes it took to fall asleep (ActivitySettingsValueHistory).

ActivitySettingsKeySleepEnterAtHistory 

Time the user fell asleep, in minutes after midnight (ActivitySettingsValueHistory).

ActivitySettingsKeySleepExitAtHistory 

Time the user woke up, in minutes after midnight (ActivitySettingsValueHistory).

ActivitySettingsKeySleepState 

ActivitySleepState (ActivityScalarStore).

ActivitySettingsKeySleepStateMinutes 

Minutes in the current sleep state (ActivityScalarStore).

ActivitySettingsKeyStepAveragesWeekdayFirst 

First key of the weekday step averages, ACTIVITY_STEP_AVERAGES_PER_KEY uint16_t each.

ActivitySettingsKeyStepAveragesWeekdayLast 

Last key of the weekday step averages.

ActivitySettingsKeyStepAveragesWeekendFirst 

First key of the weekend step averages, ACTIVITY_STEP_AVERAGES_PER_KEY uint16_t each.

ActivitySettingsKeyStepAveragesWeekendLast 

Last key of the weekend step averages.

ActivitySettingsKeyAgeYears 

uint16_t: age, in years.

ActivitySettingsKeyUnused5 

Unused.

ActivitySettingsKeyInsightSleepRewardTime 

time_t: last time the sleep reward was shown, 0 if never.

ActivitySettingsKeyInsightActivityRewardTime 

time_t: last time the activity reward was shown, 0 if never.

ActivitySettingsKeyInsightActivitySummaryState 

SummaryPinLastState: UUID and last time the activity summary pin was added.

ActivitySettingsKeyInsightSleepSummaryState 

SummaryPinLastState: UUID and last time the sleep summary pin was added.

ActivitySettingsKeyRestingKCaloriesHistory 

Resting kcal (ActivitySettingsValueHistory).

ActivitySettingsKeyActiveKCaloriesHistory 

Active kcal (ActivitySettingsValueHistory).

ActivitySettingsKeyLastSleepActivityUTC 

time_t: UTC time of the last sleep activity logged to analytics.

ActivitySettingsKeyLastRestfulSleepActivityUTC 

time_t: UTC time of the last restful sleep activity logged to analytics.

ActivitySettingsKeyLastStepActivityUTC 

time_t: UTC time of the last step activity logged to analytics.

ActivitySettingsKeyStoredActivities 

ActivitySession[ACTIVITY_MAX_ACTIVITY_SESSIONS_COUNT]: stored sessions.

ActivitySettingsKeyInsightNapSessionTime 

time_t: last time the nap pin was shown.

ActivitySettingsKeyInsightActivitySessionTime 

time_t: last time the activity session pin was shown.

ActivitySettingsKeyLastVMC 

VMC of the last processed minute (ActivityScalarStore).

ActivitySettingsKeyRestingHeartRate 

Resting heart rate (ActivitySettingsValueHistory).

ActivitySettingsKeyHeartRateZone1Minutes 

Minutes in heart rate zone 1 today (ActivityScalarStore).

ActivitySettingsKeyHeartRateZone2Minutes 

Minutes in heart rate zone 2 today (ActivityScalarStore).

ActivitySettingsKeyHeartRateZone3Minutes 

Minutes in heart rate zone 3 today (ActivityScalarStore).

◆ ActivitySpO2ActPhase

Phases of the SpO2 reader during detected activities.

Enumerator
ActivitySpO2ActPhase_Idle 

Not in an eligible activity.

ActivitySpO2ActPhase_Wait 

Sampling heart rate, waiting for the next attempt.

ActivitySpO2ActPhase_Sampling 

Heart rate paused, sampling SpO2 within the attempt budget.

ActivitySpO2ActPhase_Backoff 

Last attempt failed; heart rate resumed before retrying.

Function Documentation

◆ activity_is_hrm_present()

bool activity_is_hrm_present ( void  )

Check whether a heart rate monitor is present.

Returns
true if present.

◆ activity_metrics_prv_add_median_hr_sample()

void activity_metrics_prv_add_median_hr_sample ( PebbleHRMEvent *  hrm_event,
time_t  now_utc,
time_t  now_uptime 
)

Add a heart rate sample to the median.

Parameters
hrm_eventBPM event.
now_utcCurrent UTC time.
now_uptimeCurrent uptime, in seconds.

◆ activity_metrics_prv_get_active_calories()

uint32_t activity_metrics_prv_get_active_calories ( void  )

Get the active calories burned today.

Returns
Calories (1/1000 kcal).

◆ activity_metrics_prv_get_distance_mm()

uint32_t activity_metrics_prv_get_distance_mm ( void  )

Get the distance covered today.

Returns
Distance, in millimeters.

◆ activity_metrics_prv_get_hr_zone()

HRZone activity_metrics_prv_get_hr_zone ( void  )

Get the heart rate zone since the last reset.

Reset every minute by activity_metrics_prv_reset_hr_stats().

Returns
Zone, HRZone_Zone0 if no readings.

◆ activity_metrics_prv_get_median_hr_bpm()

void activity_metrics_prv_get_median_hr_bpm ( int32_t *  median_out,
int32_t *  heart_rate_total_weight_x100_out 
)

Get the median heart rate since the last reset.

Reset every minute by activity_metrics_prv_reset_hr_stats().

Parameters
[out]median_outMedian heart rate, in beats per minute, 0 if no readings.
[out]heart_rate_total_weight_x100_outTotal weight of the readings, multiplied by 100.

◆ activity_metrics_prv_get_metric_info()

void activity_metrics_prv_get_metric_info ( ActivityMetric  metric,
ActivityMetricInfo *  info 
)

Get the storage information of a metric.

Parameters
metricMetric.
[out]infoStorage information.

◆ activity_metrics_prv_get_resting_calories()

uint32_t activity_metrics_prv_get_resting_calories ( void  )

Get the resting calories burned today.

Returns
Calories (1/1000 kcal).

◆ activity_metrics_prv_get_spo2_sample()

void activity_metrics_prv_get_spo2_sample ( uint8_t *  percent_out,
uint8_t *  quality_out 
)

Consume the pending SpO2 reading for the current minute record.

Each reading is logged to exactly one minute.

Parameters
[out]percent_outSaturation, in percent, 0 if none pending.
[out]quality_outQuality on the 0-7 HeartRateQuality scale, 0 if none pending.

◆ activity_metrics_prv_get_steps()

uint32_t activity_metrics_prv_get_steps ( void  )

Get the steps taken today.

Returns
Steps.

◆ activity_metrics_prv_init()

void activity_metrics_prv_init ( SettingsFile *  file,
time_t  utc_now 
)

Initialize all metrics from the settings file.

Parameters
fileActivity settings file.
utc_nowCurrent UTC time.

◆ activity_metrics_prv_is_hrm_offwrist()

bool activity_metrics_prv_is_hrm_offwrist ( time_t  now_utc)

Check whether the HRM recently reported the watch off-wrist.

Parameters
now_utcCurrent UTC time.
Returns
true if the last BPM event was off-wrist and arrived within ACTIVITY_HRM_OFFWRIST_STALE_SEC.

◆ activity_metrics_prv_minute_handler()

void activity_metrics_prv_minute_handler ( time_t  utc_sec)

Run the once a minute metrics maintenance.

Parameters
utc_secCurrent UTC time.

◆ activity_metrics_prv_reset_hr_stats()

void activity_metrics_prv_reset_hr_stats ( void  )

Reset the median heart rate and the heart rate zone.

◆ activity_metrics_prv_set_hrm_worn_status()

void activity_metrics_prv_set_hrm_worn_status ( time_t  now_utc,
bool  is_offwrist 
)

Record the worn status reported by the HRM.

Called on every BPM event.

Parameters
now_utcCurrent UTC time.
is_offwristtrue if the event quality was off-wrist.

◆ activity_metrics_prv_set_metric()

void activity_metrics_prv_set_metric ( ActivityMetric  metric,
enum pbl_weekday  day,
int32_t  value 
)

Set a metric's value, on behalf of the phone (health database).

Today's value is only increased; past days of the last week are overwritten. Takes the activity mutex.

Parameters
metricMetric.
dayDay of the week of the value.
valueValue, in activity_get_metric() units.

◆ activity_metrics_prv_steps_per_minute()

ActivityScalarStore activity_metrics_prv_steps_per_minute ( void  )

Get the steps taken in the past minute.

Returns
Steps.

◆ activity_metrics_set_metric_exact()

void activity_metrics_set_metric_exact ( ActivityMetric  metric,
int32_t  value 
)

Force today's value of a metric, possibly decreasing it (QEMU and test injection).

Takes the activity mutex.

Parameters
metricMetric.
valueValue, in activity_get_metric() units.

◆ activity_private_settings_close()

void activity_private_settings_close ( SettingsFile *  file)

Close the activity settings file.

Only call during init or while holding the activity mutex.

Parameters
fileFile returned by activity_private_settings_open().

◆ activity_private_settings_open()

SettingsFile * activity_private_settings_open ( void  )

Open the activity settings file.

Only call during init or while holding the activity mutex.

Returns
Settings file, NULL on failure.

◆ activity_private_state()

ActivityState * activity_private_state ( void  )

Get the activity state.

Returns
Activity state.

◆ activity_sessions_is_session_type_ongoing()

bool activity_sessions_is_session_type_ongoing ( ActivitySessionType  activity_type)

Check whether a session of a type is ongoing.

Parameters
activity_typeSession type.
Returns
true if one is ongoing.

◆ activity_sessions_prv_add_activity_session()

void activity_sessions_prv_add_activity_session ( ActivitySession *  session)

Register a new session, or update an existing one.

Called by the algorithm when it detects an activity.

Parameters
sessionSession.

◆ activity_sessions_prv_delete_activity_session()

void activity_sessions_prv_delete_activity_session ( ActivitySession *  session)

Delete a session.

Called by the algorithm when it drops a session. Only ongoing sessions can be deleted.

Parameters
sessionSession.

◆ activity_sessions_prv_get_sleep_bounds_utc()

void activity_sessions_prv_get_sleep_bounds_utc ( time_t  now_utc,
time_t *  enter_utc,
time_t *  exit_utc 
)

Get the sleep bounds of the current day.

Parameters
now_utcCurrent UTC time.
[out]enter_utcEarliest sleep entry time, UTC.
[out]exit_utcLatest sleep exit time, UTC.

◆ activity_sessions_prv_get_sleep_window_start_utc()

time_t activity_sessions_prv_get_sleep_window_start_utc ( time_t  now_utc)

Get the start of the sleep day containing a time.

Sleep days start at ACTIVITY_LAST_SLEEP_MINUTE_OF_DAY local time.

Parameters
now_utcUTC time.
Returns
Start of the sleep day, UTC.

◆ activity_sessions_prv_init()

void activity_sessions_prv_init ( SettingsFile *  file,
time_t  utc_now 
)

Load the stored activity sessions.

Parameters
fileActivity settings file.
utc_nowCurrent UTC time.

◆ activity_sessions_prv_is_sleep_activity()

bool activity_sessions_prv_is_sleep_activity ( ActivitySessionType  activity_type)

Check whether a session type is sleep related.

Parameters
activity_typeSession type.
Returns
true for sleep, restful sleep, nap and restful nap.

◆ activity_sessions_prv_minute_handler()

void activity_sessions_prv_minute_handler ( time_t  utc_sec)

Run the once a minute session maintenance.

Parameters
utc_secCurrent UTC time.

◆ activity_sessions_prv_remove_out_of_range_activity_sessions()

void activity_sessions_prv_remove_out_of_range_activity_sessions ( time_t  utc_sec,
bool  remove_ongoing 
)

Remove sessions older than today or in the future.

Parameters
utc_secCurrent UTC time.
remove_ongoingIf true, also remove ongoing sessions.

◆ activity_sessions_prv_send_activity_session_to_data_logging()

void activity_sessions_prv_send_activity_session_to_data_logging ( ActivitySession *  session)

Send a session to data logging.

Parameters
sessionSession.

◆ activity_test_reset()

bool activity_test_reset ( bool  reset_settings,
bool  tracking_on,
const ActivitySettingsValueHistory *  sleep_history,
const ActivitySettingsValueHistory *  step_history 
)

Reinitialize the activity service (test apps).

Parameters
reset_settingsIf true, clear all persistent data.
tracking_onIf true, turn tracking on; otherwise keep the current state.
sleep_historyIf not NULL, sleep history to write.
step_historyIf not NULL, step history to write.
Returns
true on success.