PebbleOS
Loading...
Searching...
No Matches
Data Structures | Macros | Typedefs | Enumerations | Functions
Kraepelin algorithm

Step counting, sleep and activity session detection. More...

Data Structures

struct  KAlgOngoingSleepStats
 Ongoing sleep statistics, returned by kalg_get_sleep_stats(). More...
 

Macros

#define ALG_RAW_LIGHT_SENSOR_DIVIDE_BY   16
 Divisor applied to the raw light sensor reading stored in minute records.
 
#define ALG_PRIMARY_EVENING_MINUTE   (21 * PBL_MIN_PER_HOUR)
 Sleep sessions ending after this minute of the day (9pm) are primary sleep, not naps.
 
#define ALG_PRIMARY_MORNING_MINUTE   (12 * PBL_MIN_PER_HOUR)
 Sleep sessions starting before this minute of the day (12pm) are primary sleep, not naps.
 
#define ALG_MAX_NAP_MINUTES   (3 * PBL_MIN_PER_HOUR)
 Maximum length of a nap, in minutes.
 
#define ALG_SLEEP_HISTORY_HOURS_FOR_TODAY   36
 Hours of past minute data processed to compute today's sleep.
 
#define KALG_SAMPLE_HZ   25
 Accelerometer sampling rate expected by the algorithm, in Hz.
 
#define KALG_GRAMS_PER_KG   1000
 Number of grams per kilogram.
 
#define KALG_ENCODED_VMC_NOT_WORN   0
 Encoded VMC value meaning the watch was not worn.
 
#define KALG_ENCODED_VMC_MIN_WORN_VALUE   1
 Minimum encoded VMC value when the watch was worn.
 
#define KALG_MAX_UNCERTAIN_SLEEP_M   19
 Maximum delay, in minutes, for the sleep algorithm to detect that the user woke up.
 

Typedefs

typedef struct KAlgState KAlgState
 Opaque algorithm state.
 
typedef void(* KAlgActivitySessionCallback) (void *context, KAlgActivityType activity_type, time_t start_utc, uint32_t len_sec, bool ongoing, bool delete, uint32_t steps, uint32_t resting_calories, uint32_t active_calories, uint32_t distance_mm)
 Callback reporting activity sessions, called by kalg_activities_update().
 
typedef void(* KAlgStatsCallback) (uint32_t num_stats, const char **names, int32_t *stats)
 Callback receiving algorithm statistics.
 

Enumerations

enum  KAlgActivityType {
  KAlgActivityType_Sleep , KAlgActivityType_RestfulSleep , KAlgActivityType_Walk , KAlgActivityType_Run ,
  KAlgActivityTypeCount
}
 Activity types reported to KAlgActivitySessionCallback. More...
 

Functions

uint32_t kalg_state_size (void)
 Get the size of the algorithm state.
 
bool kalg_init (KAlgState *state, KAlgStatsCallback stats_cb)
 Initialize the algorithm state.
 
void kalg_deinit (KAlgState *state)
 Release the resources held by the state.
 
uint32_t kalg_analyze_samples (KAlgState *state, AccelRawData *samples, uint32_t num_samples, uint32_t *consumed_samples)
 Analyze accelerometer samples.
 
void kalg_minute_stats (KAlgState *state, uint16_t *vmc, uint8_t *orientation, bool *still)
 Get the last minute's stats and reset them for the next minute.
 
uint32_t kalg_analyze_finish_epoch (KAlgState *state)
 Process the partial epoch not yet processed by kalg_analyze_samples() (unit tests).
 
void kalg_activities_update (KAlgState *state, time_t utc_now, uint16_t steps, uint16_t vmc, uint8_t orientation, bool definitely_not_worn, uint32_t resting_calories, uint32_t active_calories, uint32_t distance_mm, bool shutting_down, KAlgActivitySessionCallback sessions_cb, void *context)
 Feed a minute of data to the walk, run and sleep detectors.
 
time_t kalg_activity_last_processed_time (KAlgState *state, KAlgActivityType activity)
 Get the last minute processed for an activity type.
 
void kalg_get_sleep_stats (KAlgState *state, KAlgOngoingSleepStats *stats)
 Get the ongoing sleep statistics.
 
void kalg_enable_activity_tracking (KAlgState *kalg_state, bool enable)
 Enable or disable automatic activity session detection.
 
bool kalg_activity_hrm_is_active (KAlgState *kalg_state)
 Check whether a continuous heart rate session is active for a detected activity.
 
void kalg_activity_hrm_set_paused (KAlgState *kalg_state, bool paused)
 Pause or resume the heart rate sessions of detected activities.
 

Detailed Description

Step counting, sleep and activity session detection.

The algorithm processes accelerometer samples at KALG_SAMPLE_HZ in 5 second epochs (125 samples). For each epoch it computes the FFT and the VMC (vector magnitude counts, a measure of movement calibrated against the Actigraph) and identifies the stepping frequency, giving the steps of the epoch. Once a minute, the minute stats (VMC, orientation) are fed with the minute's steps, calories and distance to state machines that detect walks, runs, sleep and restful sleep. See the health algorithms page of the architecture documentation for details.

The caller owns the state, of size kalg_state_size():

KAlgState *state = kernel_malloc_check(kalg_state_size());
kalg_init(state, NULL);
// For every batch of 25 Hz samples
uint32_t consumed;
steps += kalg_analyze_samples(state, samples, num_samples, &consumed);
// Once a minute
uint16_t vmc;
uint8_t orientation;
bool still;
kalg_minute_stats(state, &vmc, &orientation, &still);
kalg_activities_update(state, rtc_get_time(), minute_steps, vmc, orientation, not_worn,
resting_cal, active_cal, distance_mm, false, session_cb, ctx);
kalg_deinit(state);
kernel_free(state);
time_t rtc_get_time(void)
Get the current time.
uint32_t kalg_state_size(void)
Get the size of the algorithm state.
uint32_t kalg_analyze_samples(KAlgState *state, AccelRawData *samples, uint32_t num_samples, uint32_t *consumed_samples)
Analyze accelerometer samples.
bool kalg_init(KAlgState *state, KAlgStatsCallback stats_cb)
Initialize the algorithm state.
void kalg_activities_update(KAlgState *state, time_t utc_now, uint16_t steps, uint16_t vmc, uint8_t orientation, bool definitely_not_worn, uint32_t resting_calories, uint32_t active_calories, uint32_t distance_mm, bool shutting_down, KAlgActivitySessionCallback sessions_cb, void *context)
Feed a minute of data to the walk, run and sleep detectors.
void kalg_minute_stats(KAlgState *state, uint16_t *vmc, uint8_t *orientation, bool *still)
Get the last minute's stats and reset them for the next minute.
void kalg_deinit(KAlgState *state)
Release the resources held by the state.
struct KAlgState KAlgState
Opaque algorithm state.
Definition kraepelin_algorithm.h:49

Data Structure Documentation

◆ KAlgOngoingSleepStats

struct KAlgOngoingSleepStats

Ongoing sleep statistics, returned by kalg_get_sleep_stats().

Data Fields
uint16_t sleep_len_m Minutes of that sleep that are certain, 0 if none.
time_t sleep_start_utc Start time of a recent sleep session, UTC; 0 if none was detected in the last 60 minutes (minimum sleep session length).
time_t uncertain_start_utc Start of the uncertain part of the session, which lasts until now, UTC; 0 if none.

Macro Definition Documentation

◆ ALG_MAX_NAP_MINUTES

#define ALG_MAX_NAP_MINUTES   (3 * PBL_MIN_PER_HOUR)

Maximum length of a nap, in minutes.

Longer sleep sessions outside the primary range are primary sleep.

◆ ALG_PRIMARY_EVENING_MINUTE

#define ALG_PRIMARY_EVENING_MINUTE   (21 * PBL_MIN_PER_HOUR)

Sleep sessions ending after this minute of the day (9pm) are primary sleep, not naps.

◆ ALG_PRIMARY_MORNING_MINUTE

#define ALG_PRIMARY_MORNING_MINUTE   (12 * PBL_MIN_PER_HOUR)

Sleep sessions starting before this minute of the day (12pm) are primary sleep, not naps.

◆ ALG_RAW_LIGHT_SENSOR_DIVIDE_BY

#define ALG_RAW_LIGHT_SENSOR_DIVIDE_BY   16

Divisor applied to the raw light sensor reading stored in minute records.

◆ ALG_SLEEP_HISTORY_HOURS_FOR_TODAY

#define ALG_SLEEP_HISTORY_HOURS_FOR_TODAY   36

Hours of past minute data processed to compute today's sleep.

A sleep session ending after midnight counts as today's, so it may have started more than 24 hours ago.

◆ KALG_ENCODED_VMC_MIN_WORN_VALUE

#define KALG_ENCODED_VMC_MIN_WORN_VALUE   1

Minimum encoded VMC value when the watch was worn.

◆ KALG_ENCODED_VMC_NOT_WORN

#define KALG_ENCODED_VMC_NOT_WORN   0

Encoded VMC value meaning the watch was not worn.

◆ KALG_GRAMS_PER_KG

#define KALG_GRAMS_PER_KG   1000

Number of grams per kilogram.

◆ KALG_MAX_UNCERTAIN_SLEEP_M

#define KALG_MAX_UNCERTAIN_SLEEP_M   19

Maximum delay, in minutes, for the sleep algorithm to detect that the user woke up.

Needed at compile time by the activity algorithm glue, so it is hard-coded; kalg_init() asserts it matches the sleep parameters.

◆ KALG_SAMPLE_HZ

#define KALG_SAMPLE_HZ   25

Accelerometer sampling rate expected by the algorithm, in Hz.

Typedef Documentation

◆ KAlgActivitySessionCallback

typedef void(* KAlgActivitySessionCallback) (void *context, KAlgActivityType activity_type, time_t start_utc, uint32_t len_sec, bool ongoing, bool delete, uint32_t steps, uint32_t resting_calories, uint32_t active_calories, uint32_t distance_mm)

Callback reporting activity sessions, called by kalg_activities_update().

A session may be reported several times while ongoing, and deleted later.

Parameters
contextContext passed to kalg_activities_update().
activity_typeActivity type.
start_utcStart time, UTC.
len_secLength, in seconds.
ongoingtrue if the activity is still ongoing.
deletetrue to delete this previously reported session.
stepsSteps taken.
resting_caloriesResting calories (1/1000 kcal) burned.
active_caloriesActive calories (1/1000 kcal) burned.
distance_mmDistance covered, in millimeters.

◆ KAlgState

typedef struct KAlgState KAlgState

Opaque algorithm state.

◆ KAlgStatsCallback

typedef void(* KAlgStatsCallback) (uint32_t num_stats, const char **names, int32_t *stats)

Callback receiving algorithm statistics.

Only used during algorithm development, to collect and summarize named statistics.

Parameters
num_statsNumber of elements in names and stats.
namesStatistic names.
statsStatistic values.

Enumeration Type Documentation

◆ KAlgActivityType

Activity types reported to KAlgActivitySessionCallback.

Enumerator
KAlgActivityType_Sleep 

Entire sleep session from falling asleep to waking up, containing both light and restful periods.

KAlgActivityType_RestfulSleep 

Restful period, always inside a KAlgActivityType_Sleep session.

KAlgActivityType_Walk 

Walk of significant length.

KAlgActivityType_Run 

Run.

KAlgActivityTypeCount 

Number of activity types.

Function Documentation

◆ kalg_activities_update()

void kalg_activities_update ( KAlgState *  state,
time_t  utc_now,
uint16_t  steps,
uint16_t  vmc,
uint8_t  orientation,
bool  definitely_not_worn,
uint32_t  resting_calories,
uint32_t  active_calories,
uint32_t  distance_mm,
bool  shutting_down,
KAlgActivitySessionCallback  sessions_cb,
void *  context 
)

Feed a minute of data to the walk, run and sleep detectors.

Does nothing while activity tracking is disabled. A UTC time jump (backwards, or more than 5 minutes forward) resets the detectors.

Parameters
stateState passed to kalg_init().
utc_nowCurrent UTC time.
stepsSteps taken in the last minute.
vmcVMC of the last minute.
orientationAverage orientation of the last minute.
definitely_not_worntrue if the watch is definitely not worn this minute (on the charger, or a recent off-wrist heart rate reading); a hard not-worn signal for sleep detection.
resting_caloriesResting calories (1/1000 kcal) burned in the last minute.
active_caloriesActive calories (1/1000 kcal) burned in the last minute.
distance_mmDistance covered in the last minute, in millimeters.
shutting_downtrue to force all ongoing activities to end.
sessions_cbCalled for every session found.
contextPassed to sessions_cb.

◆ kalg_activity_hrm_is_active()

bool kalg_activity_hrm_is_active ( KAlgState *  kalg_state)

Check whether a continuous heart rate session is active for a detected activity.

Parameters
kalg_stateState passed to kalg_init().
Returns
true if a walk or run heart rate session is active.

◆ kalg_activity_hrm_set_paused()

void kalg_activity_hrm_set_paused ( KAlgState *  kalg_state,
bool  paused 
)

Pause or resume the heart rate sessions of detected activities.

Pausing sets their update interval to a day, freeing the shared optical path for a SpO2 reading; resuming restores the 1 second interval.

Parameters
kalg_stateState passed to kalg_init().
pausedtrue to pause, false to resume.

◆ kalg_activity_last_processed_time()

time_t kalg_activity_last_processed_time ( KAlgState *  state,
KAlgActivityType  activity 
)

Get the last minute processed for an activity type.

Parameters
stateState passed to kalg_init().
activityActivity type.
Returns
UTC time of the minute.

◆ kalg_analyze_finish_epoch()

uint32_t kalg_analyze_finish_epoch ( KAlgState *  state)

Process the partial epoch not yet processed by kalg_analyze_samples() (unit tests).

Parameters
stateState passed to kalg_init().
Returns
Steps counted.

◆ kalg_analyze_samples()

uint32_t kalg_analyze_samples ( KAlgState *  state,
AccelRawData *  samples,
uint32_t  num_samples,
uint32_t *  consumed_samples 
)

Analyze accelerometer samples.

Samples are buffered until a full epoch is available.

Parameters
stateState passed to kalg_init().
samplesSamples, in mG, at KALG_SAMPLE_HZ.
num_samplesNumber of samples in samples.
[out]consumed_samplesNumber of samples just processed to compute steps: an epoch (125) when one completed, 0 otherwise.
Returns
Steps counted.

◆ kalg_deinit()

void kalg_deinit ( KAlgState *  state)

Release the resources held by the state.

Must be called before freeing the state, otherwise the activity heart rate subscriptions outlive it.

Parameters
stateState passed to kalg_init().

◆ kalg_enable_activity_tracking()

void kalg_enable_activity_tracking ( KAlgState *  kalg_state,
bool  enable 
)

Enable or disable automatic activity session detection.

Resets the detectors.

Parameters
kalg_stateState passed to kalg_init().
enabletrue to detect sessions, false to stop.

◆ kalg_get_sleep_stats()

void kalg_get_sleep_stats ( KAlgState *  state,
KAlgOngoingSleepStats *  stats 
)

Get the ongoing sleep statistics.

Parameters
stateState passed to kalg_init().
[out]statsSleep statistics.

◆ kalg_init()

bool kalg_init ( KAlgState *  state,
KAlgStatsCallback  stats_cb 
)

Initialize the algorithm state.

Parameters
stateState, of kalg_state_size() bytes.
stats_cbIf not NULL, called with statistics while analyzing samples.
Returns
true on success.

◆ kalg_minute_stats()

void kalg_minute_stats ( KAlgState *  state,
uint16_t *  vmc,
uint8_t *  orientation,
bool *  still 
)

Get the last minute's stats and reset them for the next minute.

The minute stats are logged and used to compute sleep.

Parameters
stateState passed to kalg_init().
[out]vmcVMC (vector magnitude counts) of the minute.
[out]orientationAverage orientation: upper 4 bits are the angle to the Z axis, lower 4 bits the angle in the X-Y plane, each quantized to 16 steps.
[out]stilltrue if no movement above the noise threshold was detected (currently always false).

◆ kalg_state_size()

uint32_t kalg_state_size ( void  )

Get the size of the algorithm state.

Returns
Size of KAlgState, in bytes.