Loading...
Searching...
No Matches
Core Helpers

Pure maths, clock, text, and unit helpers that need no watch SDK. More...

Files

file  src/c/core/clock/astro.c
 Pure astronomy math, host-testable off-device.
file  src/c/core/clock/astro.h
 Pure astronomy math you can test off the watch. Right now just the Julian Date, worked out from a UTC timestamp with plain integer math, so it needs no Pebble services and no floats.
file  src/c/core/clock/beats.c
 Pure swatch .beats math, host-testable off-device.
file  src/c/core/clock/beats.h
 Pure swatch .beats math, operates on ms since Biel Mean Time (UTC+1) midnight. Also holds the token a date format uses to ask for a .beats reading.
file  src/c/core/clock/date.c
 Pure calendar math, host-testable off-device.
file  src/c/core/clock/date.h
 Pure calendar math you can test off the watch. Week numbers, day counts, and month shapes worked out from plain numbers, so it needs no Pebble services and no struct tm.
file  src/c/core/clock/duration.c
 A minute count turned into a short human duration.
file  src/c/core/clock/duration.h
 A minute count turned into a short human duration, no SDK.
file  src/c/core/clock/hour_latch.c
 The hourly buzz latch, host-testable off-device.
file  src/c/core/clock/hour_latch.h
 Decides when an hourly buzz fires, so it fires once for each real hour.
file  src/c/core/clock/moon.c
 Pure moon-phase math, host-testable off-device.
file  src/c/core/clock/moon.h
 Pure moon-phase math you can test off the watch. It counts from a known new moon using the average length of a moon cycle, so it needs nothing but a UTC timestamp.
file  src/c/core/clock/nightsched.c
 The night window, by containment rather than by edge.
file  src/c/core/clock/nightsched.h
 Whether a night-time window is open right now, from plain clock readings.
file  src/c/core/clock/progress.c
 The progress sums: seconds gone over seconds in the period, as a whole percent.
file  src/c/core/clock/progress.h
 How far through the hour, day, week, and year the wall clock is, as a whole percent.
file  src/c/core/clock/rotate.c
 Working out which one is up from the clock.
file  src/c/core/clock/rotate.h
 Which one of a set to show right now, on a timed rotation.
file  src/c/core/clock/solar.c
 How the day's light is going, worked out from three plain clock readings.
file  src/c/core/clock/solar.h
 How the day's light is going, worked out from three plain clock readings.
file  src/c/core/clock/tide.c
 The rise and fall of a semidiurnal tide, from a plain running minute count.
file  src/c/core/clock/tide.h
 The rise and fall of a semidiurnal tide, from a plain running minute count.
file  src/c/core/clock/time_config.c
 What a time store reconfigure runs, and the check for whether two sets of its rules run the same tickers.
file  src/c/core/clock/time_config.h
 The rules a face hands the time store, what a reconfigure runs of them, and the check for whether two sets of rules run the same tickers.
file  src/c/core/clock/timeband.c
 The window sums: build one, place a moment on it, and clip a span to it.
file  src/c/core/clock/timeband.h
 A stretch of the day as an axis, and the sums that put a moment somewhere along it.
file  src/c/core/clock/weekday.c
 Weekday names, host-testable off-device.
file  src/c/core/clock/weekday.h
 Short weekday names shared by the panels that label a day.
file  src/c/core/clock/zone_setting.c
 Reads a time zone setting the way the phone sends it.
file  src/c/core/clock/zone_setting.h
 Reads a time zone setting the way the phone sends it, the minutes ahead of UTC then a comma and the place's name, as in "60,London". An empty setting means no zone is picked, which is what the phone sends once the wearer clears the picker.
file  src/c/core/health/goal_latch.c
 The goal-met latch, host-testable off-device.
file  src/c/core/health/goal_latch.h
 Decides when a daily movement goal has just been met, so the watch cheers once per goal per day.
file  src/c/core/health/goal_vibe_pattern.c
 The Goal Met Vibration pick and pattern reader, host-testable off-device.
file  src/c/core/health/goal_vibe_pattern.h
 Reads the Goal Met Vibration pick, and turns a comma list of milliseconds into a rhythm the watch can buzz.
file  src/c/core/health/goals.c
 The daily goal tables, host-testable off-device.
file  src/c/core/health/goals.h
 The daily goals a wearer picks on the settings page, turned from a menu choice into the real target.
file  src/c/core/health/hr_day.h
 Today's heart rate by the hour, for a panel that charts the day with its low, average, and high.
file  src/c/core/health/hrv_log.c
 The heart rate variability readings kept for a face's panels.
file  src/c/core/health/hrv_log.h
 The heart rate variability readings kept for a face's panels: the last few with what the wearer was doing, today by the hour, last night's average, and the latest of each kind.
file  src/c/core/health/hrv_motion.c
 Tells whether the wearer kept still while a burst of beat gaps was measured.
file  src/c/core/health/hrv_motion.h
 Tells how much the wearer's wrist moved while a burst of beat gaps was measured.
file  src/c/core/health/hrv_run.c
 Turns the beat gaps the watch reports into heart rate variability, as RMSSD in ms.
file  src/c/core/health/hrv_run.h
 Turns the beat gaps the watch reports into heart rate variability, as RMSSD in ms.
file  src/c/core/health/minute_window.c
 Where a run of minute records lands in a window that ends at a given minute.
file  src/c/core/health/minute_window.h
 Where a run of minute records lands in a window that ends at a given minute.
file  src/c/core/health/step_hours.c
 The hour arithmetic behind the step chart's buckets.
file  src/c/core/health/step_hours.h
 The hour arithmetic behind the step chart's buckets.
file  src/c/core/io/bytes_le.h
 Little-endian byte readers shared by the wire-decoding stores.
file  src/c/core/io/callback_list.c
 Adding to and running a callback list.
file  src/c/core/io/callback_list.h
 A short fixed list of callbacks, run in the order they were added.
file  src/c/core/io/store_live.h
 Whether a store runs live after a reconfigure, the one rule every store with a reconfigure follows.
file  src/c/core/layout/layout_string.c
 Walking a layout wire string far enough to answer whether it holds anything.
file  src/c/core/layout/layout_string.h
 Reading a layout wire string without parsing the whole thing.
file  src/c/core/math/pct.c
 Progress towards a goal, as a percent.
file  src/c/core/math/pct.h
 Progress towards a goal, as a percent.
file  src/c/core/math/scale.c
 The clamp and segment maths a bar or gauge is built from.
file  src/c/core/math/scale.h
 The clamp and segment maths a bar or gauge is built from, no SDK.
file  src/c/core/math/series.c
 Reducing a run of samples to the few numbers a chart draws from.
file  src/c/core/math/series.h
 Reducing a run of samples to the few numbers a chart draws from, no SDK.
file  src/c/core/role/role.c
 The order the day, night, and Quiet Time triggers are asked in.
file  src/c/core/role/role.h
 Which of day, night, and Quiet Time should be on screen right now.
file  src/c/core/text/cstring_fit.c
 Copying text into a fixed buffer, and checking what a buffer holds before it is used.
file  src/c/core/text/cstring_fit.h
 Copying text into a fixed buffer, and checking what a buffer holds before it is used.
file  src/c/core/text/number_format.c
 Pure number formatting, no SDK behind it.
file  src/c/core/text/number_format.h
 Pure number formatting, no SDK behind it.
file  src/c/core/text/text_case.c
 Pure ascii case helpers, no SDK behind them.
file  src/c/core/text/text_case.h
 Pure ascii case helpers, no SDK behind them.
file  src/c/core/ui/font_slots.c
 The decisions behind the font registry: who owns each slot's font, when a swap has nothing to do, and when a font can be freed.
file  src/c/core/ui/font_slots.h
 The decisions behind the font registry: who owns each slot's font, when a swap has nothing to do, and when a font can be freed.
file  src/c/core/units/distance.c
 Pure distance conversions and formatting, no SDK behind them.
file  src/c/core/units/distance.h
 Pure distance conversions and formatting, no SDK behind them.
file  src/c/core/units/wind.c
 Pure wind-speed conversions and unit labels, no SDK behind them.
file  src/c/core/units/wind.h
 Pure wind-speed conversions and unit labels, no SDK behind them.
file  src/c/core/weather/forecast_age.c
 How much of a forecast strip has already gone by.
file  src/c/core/weather/forecast_age.h
 How much of a forecast strip has already gone by, so a strip that stays on the watch after a missed fetch shows what is still to come rather than hours and days already over.
file  src/c/core/weather/uv_band.c
 The risk band a UV index falls in, with a long and a short name for each.
file  src/c/core/weather/uv_band.h
 The risk band a UV index falls in, with a long and a short name for each.
file  src/c/core/weather/weather_reading.c
 Turns one weather message into the reading a store keeps.
file  src/c/core/weather/weather_reading.h
 One weather message off the phone, and the reading it leaves behind.
file  src/c/core/weather/wind_dir.c
 The compass direction a wind is blowing from, as a bearing and as a sideways component.
file  src/c/core/weather/wind_dir.h
 The compass direction a wind is blowing from, as a bearing and as a sideways component.
file  src/c/core/weather/wx_cond.c
 Turns the condition token the phone sends into its WxCond.
file  src/c/core/weather/wx_cond.g.h
 The weather conditions as numbers, in the order of the shared list.
file  src/c/core/weather/wx_cond.h
 The condition token the phone sends, as a number a face can index its own art by.
file  src/c/core/weather/wx_label.c
 The short word a small slot shows for the sky.
file  src/c/core/weather/wx_label.h
 The short word a small slot shows for the sky, from the condition token the phone sends.
file  src/c/core/wire/calendar_wire.c
 The agenda as the phone packs it, and the reader that unpacks it.
file  src/c/core/wire/calendar_wire.h
 The agenda as the phone packs it, and the reader that unpacks it.
file  src/c/core/wire/coords.c
 Telling a real fix from the phone's way of saying it has none.
file  src/c/core/wire/coords.h
 Telling a real fix from the phone's way of saying it has none.
file  src/c/core/wire/music_art.c
 Checking the now playing art the phone sent, and laying its rows into a bitmap.
file  src/c/core/wire/music_art.h
 Now playing art as the phone packs it, and the reader that checks it.
file  src/c/core/wire/music_track.c
 Taking in the track the phone sent.
file  src/c/core/wire/music_track.h
 What the phone is playing, as the watch holds it, and taking a new one in.
file  src/c/core/wire/phone_level.h
 Reads the phone's battery level as the phone sends it.
file  src/c/core/wire/stock_wire.c
 The watchlist as the phone packs it, and the reader that unpacks it.
file  src/c/core/wire/stock_wire.h
 The watchlist as the phone packs it, and the reader that unpacks it.
file  src/c/core/wire/weather_wire.c
 The forecast strips as the phone packs them, and the readers that unpack them.
file  src/c/core/wire/weather_wire.h
 The forecast strips as the phone packs them, and the readers that unpack them.
file  src/c/core/wire/wire_caps.g.h
 Strip caps and marker values shared by the phone and the watch.
file  src/c/core/wire/wire_read.h
 Reads the values the phone packs into a message.

Data Structures

struct  HourLatch
 Remembers the hour that last buzzed. More...
struct  TimeConfig
 The rules a face hands the time store, built from its own settings so the store names no SETTING_*. More...
struct  TimeBand
 The stretch of day a band shows: where it starts and how long it runs. More...
struct  TimeBandSpan
 A span clipped to the window, in minutes past the window's start. More...
struct  GoalLatch
 Remembers which goals were met today. More...
struct  HrHour
 The readings that landed in one hour. More...
struct  HrDay
 Today's heart rate, one entry an hour from midnight. More...
struct  HrvBurst
 One burst, for a readout that shows each burst: what the wearer did and what came of it. More...
struct  HrvLog
 The readings kept, in the shape that goes to flash. Start it with hrv_log_reset. More...
struct  HrvMotion
 The movement seen over one burst. Start it with hrv_motion_reset. More...
struct  HrvRun
 One run of beats being added up. Start it with hrv_run_reset. More...
struct  CallbackList
 A list over storage its owner provides. Start it as {entries, max, 0}. More...
struct  LinkState
 The link as last read. Zeroed is a store that has read nothing yet. More...
struct  FontSlots
 The registry's tables, one entry a slot in each. More...
struct  WeatherMessage
 One weather message as the transport read it, before anything is kept. More...
struct  WeatherState
 The weather a store keeps, laid out as the blob it saves to flash. More...
struct  WeatherClock
 The watch's clock at the moment a message lands, broken apart. More...
struct  CalendarEvent
 One event. start and end are absolute epochs so the readouts stay fresh against the watch's own clock. The phone fills end with a sensible default when the feed omits DTEND. More...
struct  CalendarStrip
 The agenda strip. count is 0 until a reading lands. More...
struct  MusicArt
 Art read off the wire. It points into the bytes it was read from, so it lives only as long as they do. More...
struct  MusicTrack
 One track. Zeroed is nothing playing. More...
struct  StockSlot
 One quote slot. When ok is false the symbol field carries a short status word ("RATE LIMIT" and friends) instead of a ticker so the watch has something to show. More...
struct  StockStrip
 The watchlist strip. count is 0 until a reading lands. More...
struct  WeatherHourCol
 One hourly forecast column: a sky code plus a temperature (WEATHER_NO_TEMP for none). More...
struct  WeatherDayCol
 One daily forecast column: a sky code plus the day's high and low. More...
struct  WeatherHourly
 The hourly strip. count is 0 until a reading lands. More...
struct  WeatherDaily
 The 7-day strip. count is 0 until a reading lands. More...

Macros

#define HOUR_LATCH_EMPTY   {.last_start = -1}
 a latch that has not buzzed yet
#define MOON_SYNODIC_SEC   2551443
 Average length of one moon cycle in seconds (about 29.53 days).
#define MOON_EPOCH_UTC   947182440
 A known new moon to count from: 2000-01-06 18:14 UTC.
#define TIDE_PERIOD_MIN   745
 The lunar semidiurnal period, 12h 25m. Two of these make one tidal day.
#define TIMEBAND_DAY_MINUTES   1440
 Minutes in a day, the modulus every wrap here is taken over.
#define GOAL_LATCH_BIT(goal)
 The bit a goal takes in the mask goal_latch_update hands back.
#define GOAL_LATCH_EMPTY   {.day = -1}
 a latch that has not looked yet
#define GOAL_VIBE_PATTERN_MAX   40
 The most steps a pattern plays. Any past it are dropped.
#define GOAL_VIBE_PATTERN_MIN_MS   10
 The shortest step, so a 0 still buzzes or pauses a moment.
#define GOAL_VIBE_PATTERN_MAX_MS   10000
 The longest step the firmware plays.
#define GOALS_STEPS_COUNT   7
 How many step goals the page offers, from 5,000 to 25,000.
#define GOALS_DISTANCE_COUNT   7
 How many distance goals the page offers, from 2 km to 20 km.
#define GOALS_CALORIES_COUNT   6
 How many calorie goals the page offers, from 500 to 3,000 kcal.
#define GOALS_ACTIVE_COUNT   5
 How many active minute goals the page offers, from 15 to 90 minutes.
#define GOALS_SLEEP_COUNT   5
 How many sleep goals the page offers, from 6 to 10 hours.
#define GOALS_HR_COUNT   6
 How many heart rate limits the page offers, from 150 to 200 bpm.
#define HR_DAY_HOURS   24
 Today's hours from midnight.
#define HRV_LOG_SLOTS   24
 How many of the latest readings the history keeps.
#define HRV_LOG_HOURS   24
 Today's readings by the hour from midnight.
#define HRV_LOG_MS_MAX   255
 Readings above this are kept as this, which fits one byte.
#define HRV_LOG_NIGHT_GAP_MIN   720
 Twelve hours awake starts a new night.
#define HRV_LOG_NAP_FROM_MIN   720
 From noon, a reading taken asleep is a nap's.
#define HRV_LOG_NAP_UNTIL_MIN   1260
 Until 21:00, a reading taken asleep is a nap's.
#define HRV_WALK_STEPS_DEFAULT   10
 Steps through a burst that make it a walk, when a face sets none.
#define HRV_RECENT   6
 How many of the latest bursts a readout that shows each burst can see.
#define HRV_LOG_ASLEEP   0x80
 Set in a reading's flags when Pebble said the wearer was asleep.
#define HRV_LOG_STATE_MASK   0x0F
 The bits of a reading's flags that hold its HrvState.
#define HRV_MOTION_STILL_DEFAULT   60
 The top of still a face gets when it sets none, in milli-g a sample.
#define HRV_MOTION_MIN_SAMPLES   20
 Samples needed before the score means anything, two seconds at 10 Hz.
#define HRV_PPI_MIN_MS   300
 The shortest gap kept, a heart rate of 200.
#define HRV_PPI_MAX_MS   2000
 The longest gap kept, a heart rate of 30.
#define HRV_JUMP_PCT   20
 A gap further than this percent from the one before it is dropped.
#define HRV_QUIET_SEC   15
 A pause this long with no gap ends the run.
#define HRV_DIFFS_MIN   20
 Differences a run needs before its answer means anything.
#define HRV_DIFFS_FULL   60
 A run this long is finished, and the next gap starts a new one.
#define HRV_STALE_PERIODS   3
 A reading is stale once this many sample periods pass without a new one.
#define HRV_STALE_MIN_SEC   1800
 A reading is never stale sooner than this, however short the period.
#define HRV_HOLD_PERIOD_SEC   1
 The period asked for while a burst is measured, which keeps the sensor on.
#define HRV_HOLD_MAX_SEC   90
 The longest the sensor is held on for one burst.
#define HRV_SETTLE_GAPS   10
 Gaps left out at the start of each burst while the sensor settles, when a face sets none.
#define HRV_SETTLE_GAPS_MAX   20
 The most gaps a face can have left out, which still leaves a slow heart time for a run.
#define STEP_HOURS_PER_DAY   24
#define LAYOUT_INT_MAX   9999
 The biggest number a layout field holds. Nothing the builder writes comes close.
#define WEATHER_GROUP_CURRENT   (1u << 0)
 The current temperature and sky arrived.
#define WEATHER_GROUP_EXTRA   (1u << 1)
 At least one of the extras (humidity, wind, direction, sunrise, sunset) arrived.
#define WEATHER_GROUP_FORECAST   (1u << 2)
 At least one of today's forecast readings (UV, high, low, rain chance) arrived.
#define WEATHER_GROUP_AIR   (1u << 3)
 At least one of the air readings (feels-like, pressure, dew point) arrived.
#define WX_COND_EACH(X)
 Hands each condition's name to X, in WxCond order.
#define WX_COND_TOKEN_LEN   6
 The room the longest token takes, terminator included.
#define WX_COND_NIGHT_ENDING   "_NIGHT"
 What the phone adds to a token after dark.
#define WX_COND_NIGHT_LEN   6
 The night ending's length, without its terminator.
#define MUSIC_ART_HEADER   3
 The bytes in front of the palette: the width, the height, and how many colours follow.

Typedefs

typedef void(*) CallbackListFn(void)
 One callback in a list.
typedef void *(*) FontSlotLoad(uint32_t resource)
 Loads a font from its resource.
typedef void(*) FontSlotUnload(void *handle)
 Frees a font the app loaded.

Enumerations

enum  NightSchedMode { NIGHT_SCHED_OFF = 0 , NIGHT_SCHED_SOLAR , NIGHT_SCHED_FIXED , NIGHT_SCHED_COUNT }
 What the schedule is following. The caller's own enum should line up with these. More...
enum  GoalLatchGoal {
  GOAL_LATCH_STEPS , GOAL_LATCH_CALORIES , GOAL_LATCH_DISTANCE , GOAL_LATCH_ACTIVE ,
  GOAL_LATCH_COUNT
}
 The goals the latch watches, in the order it reads their readings and targets. More...
enum  GoalVibeKind {
  GOAL_VIBE_KIND_NONE , GOAL_VIBE_KIND_SHORT , GOAL_VIBE_KIND_LONG , GOAL_VIBE_KIND_DOUBLE ,
  GOAL_VIBE_KIND_CUSTOM , GOAL_VIBE_KIND_LIST
}
 What a Goal Met Vibration pick plays. More...
enum  HrvState { HRV_STATE_STILL , HRV_STATE_BUSY , HRV_STATE_WALKING , HRV_STATE_COUNT }
 What the wearer was doing through a reading's burst. More...
enum  HrvCount { HRV_COUNT_NOT_WALKING , HRV_COUNT_STILL , HRV_COUNT_ANY }
 Which bursts count for the main reading. The first is the one a face gets when it sets none. More...
enum  LinkChange { LINK_SAME , LINK_DROPPED , LINK_RECONNECTED }
 What one reading of the link means. More...
enum  Role { ROLE_DAY = 0 , ROLE_NIGHT , ROLE_QUIET , ROLE_COUNT }
 Which of the three is showing. The caller's own storage should line up with these. More...
enum  FontSlotState { FONT_SLOT_UNOWNED , FONT_SLOT_OWNED , FONT_SLOT_LOADED }
 What a slot holds and who frees it. Kept in a uint8_t a slot. More...
enum  WindUnit {
  WIND_UNIT_KMH = 0 , WIND_UNIT_MPH = 1 , WIND_UNIT_KTS = 2 , WIND_UNIT_MS = 3 ,
  WIND_UNIT_COUNT
}
 Which unit a wind speed reads out in. More...
enum  UvBand {
  UV_BAND_NONE , UV_BAND_LOW , UV_BAND_MODERATE , UV_BAND_HIGH ,
  UV_BAND_VERY_HIGH , UV_BAND_EXTREME
}
 The risk bands, lowest first. More...
enum  WxCond {
  WX_COND_CLEAR = 0 , WX_COND_PCLDY = 1 , WX_COND_CLDY = 2 , WX_COND_FOGGY = 3 ,
  WX_COND_DRZL = 4 , WX_COND_FZDZ = 5 , WX_COND_RAIN = 6 , WX_COND_FZRN = 7 ,
  WX_COND_SNOW = 8 , WX_COND_SHWR = 9 , WX_COND_SNSH = 10 , WX_COND_STRM = 11 ,
  WX_COND_COUNT = 12 , WX_COND_UNKNOWN = 255
}
 Each weather condition the phone can send, numbered in the order of the shared list. More...

Functions

int32_t astro_jd_centi (time_t utc)
 The Julian Date multiplied by 100, so the whole part is the day and the last two digits are hundredths. Kept scaled to stay in plain 32-bit integers.
int beats_from_ms (int32_t ms_into_bmt_day)
 Calculates swatch internet time in .beats (0..999) for a given ms.
uint32_t ms_until_next_beat (int32_t ms_into_bmt_day)
 Calculates milliseconds until the next .beats boundary.
int32_t beats_ms_from_hms (int hour, int minute, int second, uint16_t ms)
 Milliseconds into the Biel Mean Time day, from a UTC wall clock.
bool beats_has_token (const char *format)
 Whether a date format asks for a .beats reading.
void beats_expand_token (char *text, int beats)
 Overwrite every BEATS_TOKEN in a string with a three digit .beats reading.
int date_iso_week (int year, int yday, int wday)
 The ISO 8601 week number, which always counts weeks from Monday.
int date_iso_week_year (int year, int yday, int wday)
 The ISO 8601 year the week number belongs to, which is not always the calendar year.
int date_iso_weeks_in_year (int year)
 How many ISO 8601 weeks a year holds, either 52 or 53.
int date_day_of_year (int yday)
 Which day of the year it is, counting January 1st as day 1.
int date_days_left_in_year (int year, int yday)
 How many days are left before the year ends, so December 31st reads 0.
int date_weeks_left_in_year (int year, int yday)
 How many whole weeks are left before the year ends. It is the days left divided by 7 and rounded down, so the last seven days of December, the 25th to the 31st, read 0.
int date_days_in_month (int year, int mon0)
 How many days a month has, with February getting its leap day.
int date_first_wday (int wday, int mday)
 The weekday the 1st of the month lands on, walked back from today's weekday.
void duration_hm (char *out, size_t n, int minutes)
 Format minutes as a clock-style "H:MM", e.g. 445 -> "7:25".
void duration_hm_compact (char *out, size_t n, int minutes)
 Format minutes as "Xh Ym", dropping the hours once it is under one ("45m").
time_t hour_latch_start (time_t now, int tm_min, int tm_sec)
 When the local hour holding a moment began, as seconds since the epoch.
bool hour_latch_take (HourLatch *latch, int tick_min, time_t start)
 Whether a tick should buzz the hour, and if so, marks the hour as buzzed.
void hour_latch_seed (HourLatch *latch, time_t start)
 Marks an hour as buzzed without buzzing it.
int32_t moon_age_sec (time_t utc)
 How far into the current moon cycle we are, in seconds.
int moon_glyph_index (time_t utc, int count)
 Picks one of count evenly spaced phase icons. It wraps back round at the end.
int moon_illumination_pct (time_t utc)
 How lit up the moon looks, from 0 to 100. This is a rough straight-line guess, so it reads 0 at new moon and 100 at full.
const char * moon_phase_name (time_t utc)
 Short name for the current phase (one of the eight main phases).
int moon_days_to_phase (time_t utc, bool to_full)
 How many days until the next full or new moon, rounded to the nearest whole day.
bool clock_window_contains (int start, int end, int now)
 Whether now falls inside a window that may run past midnight.
bool night_schedule_active (int mode, int now, int rise, int set, int fixed_start, int fixed_end, bool have_night)
 Whether the night window is open, whichever way the schedule is set.
int progress_hour_pct (int min, int sec)
 How far through the current hour it is.
int progress_day_pct (int hour, int min, int sec)
 How far through the current day it is.
int progress_week_pct (int wday, int week_start, int hour, int min, int sec)
 How far through the current week it is, counting from the day the week starts on.
int progress_year_pct (int year, int yday, int hour, int min, int sec)
 How far through the current year it is, with February getting its leap day.
int progress_week_day (int wday, int week_start)
 How many days the week has run, counting the first day as day 1.
int rotate_index (int year, int yday, int hour, int minute, int interval_min, int count)
 Which of count is up now, advancing by one every interval_min minutes and wrapping round at the end.
int solar_day_progress (int rise, int set, int now)
 How far through the daylight it is, from 0 at sunrise to 100 at sunset.
int solar_night_progress (int rise, int set, int now)
 How far through the night it is, from 0 at sunset to 100 at the next sunrise.
int solar_next_event (int rise, int set, int now, bool *is_sunrise)
 Minutes until the next sun event, and which one it is.
int tide_level (int32_t minutes)
 How far in the tide is, from 0 at dead low to 100 at high water.
bool tide_rising (int32_t minutes)
 Whether the tide is on its way in.
bool time_config_same_tickers (TimeConfig a, TimeConfig b)
 Whether two sets of rules run the same tickers.
TimeConfig time_config_reconfigured (TimeConfig cfg, bool pinned)
 The rules a reconfigure runs, which are the face's own with live held off on a store init started frozen.
bool time_config_reconfigure (TimeConfig *running, TimeConfig cfg, bool pinned)
 What a reconfigure does to the rules running, in the order the time store needs.
TimeBand timeband_full_day (void)
 A window running midnight to midnight.
TimeBand timeband_rolling (int now_min, int span_min, int lead_min)
 A window that puts a given moment a fixed way into it.
TimeBand timeband_from_hour (int base_hour, int span_min)
 A window starting at the top of a given hour.
int timeband_offset (TimeBand band, int minute_of_day)
 How far into the window a minute of the day falls.
int timeband_pos (TimeBand band, int length, int minute_of_day)
 Where a minute of the day lands along an axis of a given length.
int timeband_pos_offset (TimeBand band, int length, int offset_min)
 The same mapping for a value already measured from the window's start.
bool timeband_clip (TimeBand band, time_t window_epoch, time_t start, time_t end, TimeBandSpan *out)
 Clip an absolute span onto the window.
int timeband_clip_daily (TimeBand band, int from_min, int to_min, TimeBandSpan *out, int max_out)
 Clip a daily span, one that repeats every day like the daylight, onto the window.
time_t timeband_window_epoch (TimeBand band, time_t now, int now_min)
 The epoch the window's first minute sits at.
const char * weekday_short (int wday)
 The two-letter short name for a weekday, indexed like tm_wday and the phone's base_weekday (0 = Sunday through 6 = Saturday).
bool zone_setting_is_set (const char *value)
 Whether the setting holds a zone at all.
int16_t zone_setting_offset (const char *value)
 How many minutes the zone is ahead of UTC, negative for one behind.
const char * zone_setting_label (const char *value)
 The place's name, everything after the first comma.
uint8_t goal_latch_update (GoalLatch *latch, int day, const int readings[GOAL_LATCH_COUNT], const int targets[GOAL_LATCH_COUNT])
 Takes the latest readings and says which goals they just met.
GoalVibeKind goal_vibe_pattern_kind (const char *pick)
 What a pick plays, read from its first character.
int goal_vibe_pattern_parse (const char *text, uint32_t *out, int capacity)
 Reads a list of milliseconds such as "100,80,300" into the caller's buffer.
int goals_steps (uint8_t index)
 The step goal for a menu choice.
int goals_distance_m (uint8_t index)
 The distance goal for a menu choice, in metres.
int goals_calories (uint8_t index)
 The active calorie goal for a menu choice.
int goals_active_min (uint8_t index)
 The active minutes goal for a menu choice.
int goals_sleep_min (uint8_t index)
 The sleep goal for a menu choice, in minutes.
int goals_hr_limit (uint8_t index)
 The heart rate limit for a menu choice, the top of a heart rate bar.
void hr_day_clear (HrDay *day)
 Empties the day, for a new day or a fresh start.
void hr_day_add (HrDay *day, int hour, int bpm)
 Adds one reading to its hour.
int hr_day_hour_avg (const HrDay *day, int hour)
 The average of one hour's readings.
void hr_day_stats (const HrDay *day, int *low, int *avg, int *high)
 The day's lowest and highest readings, and the average of every reading so far.
void hrv_log_reset (HrvLog *log)
 Empties the log.
HrvState hrv_log_state_of (int motion_score, int steps, uint16_t still_mg, uint16_t walk_steps)
 Works out what a burst was from its steps and its movement score.
bool hrv_log_counts (HrvState state, HrvCount count)
 Whether a burst in one state counts for the main reading.
void hrv_log_add (HrvLog *log, int ms, uint32_t now_min, int32_t day, int minute_of_day, HrvState state, bool asleep)
 Files one finished reading.
bool hrv_log_roll_day (HrvLog *log, int32_t day)
 Moves the hours on to a new day without a reading, so a day chart drawn after midnight does not show yesterday as today.
int hrv_log_count (const HrvLog *log)
 How many readings the history holds, up to HRV_LOG_SLOTS.
bool hrv_log_get (const HrvLog *log, int back, int *ms, uint32_t *at_min, uint8_t *flags)
 One reading from the history, newest first.
int hrv_log_hour_avg (const HrvLog *log, int hour)
 Today's average of the resting readings in one hour.
void hrv_log_today (const HrvLog *log, int *low_ms, int *avg_ms, int *high_ms)
 Today's resting readings summed up.
int hrv_log_night_avg (const HrvLog *log)
 The average of the readings taken asleep in the latest night.
bool hrv_log_last (const HrvLog *log, HrvState state, int *ms, uint32_t *at_min)
 The latest reading of one kind.
void hrv_motion_reset (HrvMotion *motion)
 Empties the movement, ready for the next burst.
void hrv_motion_push (HrvMotion *motion, int16_t x_mg, int16_t y_mg, int16_t z_mg)
 Adds one accelerometer sample.
int hrv_motion_score (const HrvMotion *motion)
 The average movement per sample so far.
bool hrv_motion_over (const HrvMotion *motion, uint16_t max_mg)
 Whether the wrist has moved more than a limit through the burst so far.
bool hrv_motion_cannot_pass (const HrvMotion *motion, uint16_t max_mg, uint32_t max_samples)
 Whether the burst can no longer finish under a limit, however still the wrist stays.
void hrv_run_reset (HrvRun *run)
 Empties a run, so the next gap starts it.
int hrv_run_push (HrvRun *run, uint16_t ppi_ms, uint32_t now_sec)
 Adds one gap from the watch.
bool hrv_run_quiet (const HrvRun *run, uint32_t now_sec)
 Whether a run has gone quiet, so it is finished and waiting to be read.
int hrv_run_finish (HrvRun *run)
 Ends a run and empties it. How many differences it held stays in finished_diffs, so a caller can say how much of the burst went into the reading.
bool hrv_reading_stale (uint32_t measured_at, uint32_t now_sec, uint16_t period_sec)
 Whether a reading is too old to show.
bool hrv_should_ask (bool sampling, uint32_t gap_at, uint32_t asked_at, uint32_t now_sec, uint16_t period_sec)
 Whether to ask the watch for beat gaps again.
bool hrv_hold_over (uint32_t held_since, uint32_t now_sec)
 Whether the sensor has been held on for a burst as long as it may be.
uint8_t hrv_settle_gaps (uint16_t asked)
 How many gaps to leave out at the start of a burst, from the count a face asked for.
int minute_window_first_slot (time_t first_min, time_t end_min, int minutes)
 Where the first of a run of back to back minute records lands in a window.
int step_hours_settled (int cur_hour, int cur_min)
 How many whole hours have settled, meaning they can never gain another step.
static int16_t read_i16_le (const uint8_t *p)
 Reads a little-endian signed 16-bit value out of a byte pair.
static int32_t read_i32_le (const uint8_t *p)
 Reads a little-endian signed 32-bit value out of four bytes.
bool callback_list_add (CallbackList *list, CallbackListFn cb)
 Adds a callback to the end of the list. Adding one that is already there does nothing.
void callback_list_remove (CallbackList *list, CallbackListFn cb)
 Takes a callback off the list. The ones after it move up, so the rest keep their order. Removing one that is not there does nothing.
void callback_list_fire (const CallbackList *list)
 Runs every callback in the order it was added.
static LinkChange link_change_read (LinkState *state, bool connected)
 Takes one reading of the link and says what it means.
static bool store_live_after_reconfigure (bool live, bool pinned)
 Whether a store runs live once a reconfigure has asked for live.
int layout_parse_int (const char **cursor)
 Reads a run of digits and moves the cursor past them.
bool layout_has_any_block (const char *layout, int type_count)
 Whether a layout string holds at least one placeable block.
int pct_of (int value, int goal)
 How far along a goal is, from 0 to 100.
int clamp_int (int value, int lo, int hi)
 Pin a value into a range, so it lands on the nearer end when it falls outside.
int segment_width (int total, int gap, int count)
 The width of one cell when a strip is carved into evenly spaced segments.
int fraction_px (int total, int num, int den)
 A fraction of a length in pixels, e.g. how far along a bar a moment sits.
int segments_filled (int level, int segments)
 How many cells of a gauge a percentage lights, rounding up so any charge lights one.
int plot_y (int y0, int height, int lo, int hi, int value)
 Map a reading to its pixel row in a plot, with the low end at the bottom.
int series_range (const uint8_t *samples, int count, uint8_t no_sample, int *lo, int *hi, int *last)
 Walk a series of samples for its low, high, and most recent reading.
int series_max_u16 (const uint16_t *values, int count)
 The largest value in a series, for scaling a bar strip against its busiest slot.
Role role_pick (bool quiet_on, bool quiet_set, bool night_on, bool night_set)
 Which role wins, given what is firing and what has something behind it.
static void cstring_fit (char *dst, const char *src, size_t size)
 Copy a string into a fixed buffer, keeping only what fits and always terminating it.
static bool cstring_fit_same (const char *current, const char *value, size_t size)
 Whether copying value into a buffer would leave it reading exactly as it does now.
void copy_bounded (char *dst, uint8_t cap, const uint8_t *src, uint8_t len)
 Copy bytes into a fixed buffer, taking what fits and terminating it.
bool cstring_is_clean (const char *s, uint16_t size)
 Whether a byte range holds a string worth keeping.
bool cstring_setting_is_clean (const char *s, uint16_t size, const char *default_str)
 Whether a saved text setting reads as one, where an empty setting can be the real value.
void number_group (char *buffer, size_t size, int value)
 Format an integer with apostrophe thousands separators (e.g. 20358 -> "20'358").
void fmt_int_or_dash (char *buffer, size_t size, int value, const char *fmt)
 Format an integer, or "--" when there is no reading yet.
void fmt_hundredths (char *buffer, size_t size, int value)
 Format hundredths as a two-decimal number, e.g. 26174 -> "261.74".
void fmt_pct_signed (char *buffer, size_t size, int value)
 Format hundredths as a signed two-decimal percent, e.g. 125 -> "+1.25%".
void text_to_upper (char *s)
 Uppercase an ascii string in place.
void font_slots_put (const FontSlots *slots, int id, void *handle, bool owned)
 Puts a font in a slot, overwriting whatever it held without freeing it.
bool font_slots_load (const FontSlots *slots, uint32_t *resources, int id, uint32_t resource, FontSlotLoad load)
 Loads a font into a slot and records the resource it came from.
bool font_slots_swap (const FontSlots *slots, uint32_t *resources, int id, uint32_t resource, FontSlotLoad load, FontSlotUnload unload)
 Swaps a slot's font for another resource, freeing the old one when nothing else holds it.
void font_slots_unload_all (const FontSlots *slots, FontSlotUnload unload)
 Frees every font the app owns, each one once, and empties every slot.
const char * distance_unit (bool miles)
 Unit label for the current distance mode ("MI" or "KM").
void distance_format_value (char *buffer, size_t size, int meters, bool miles)
 Format meters as "N.N" (rounded to tenth), no unit suffix.
void distance_format (char *buffer, size_t size, int meters, bool miles)
 Format meters as "N.N MI" or "N.N KM" (rounded to tenth).
int wind_from_kmh (int kmh, WindUnit unit)
 Convert a km/h wind speed into the chosen unit.
const char * wind_unit_label (WindUnit unit)
 The short label for a wind unit.
uint8_t forecast_hours_past (int32_t seconds_into_strip, uint8_t step_hours, uint8_t count)
 How many of an hourly strip's columns are over.
uint8_t forecast_days_past (int days_since_first, uint8_t count)
 How many of a daily strip's columns are days before today.
UvBand uv_band (int uv)
 The band a UV index falls in.
const char * uv_band_name (UvBand band)
 The band's full name in capitals, such as "MODERATE" or "VERY HIGH".
const char * uv_band_short_name (UvBand band)
 The band's short name in capitals, at most six letters, such as "MOD" or "V.HIGH".
bool weather_reading_apply (WeatherState *state, const WeatherMessage *msg, const WeatherClock *clock)
 Put a message's readings into the kept weather.
int weather_reading_convert_temp (int value, bool to_fahrenheit)
 Converts one temperature to the other unit, rounded to the nearest degree and held to the range the weather keeps. No data stays no data.
void weather_reading_convert (WeatherState *state, bool to_fahrenheit)
 Convert every temperature in the kept weather to the other unit.
int wind_bearing (const char *dir)
 The bearing a 16-point compass abbreviation stands for.
int wind_lean (int bearing)
 The east-west component of a wind, as a signed proportion.
WxCond wx_cond_parse (const char *token, bool *night)
 Finds the condition for a token, with or without its "_NIGHT" ending.
void wx_label_short (char *out, size_t n, const char *condition)
 Writes the short word for a condition token, without its "_NIGHT" suffix.
bool calendar_wire_decode (const uint8_t *buf, uint16_t len, CalendarStrip *out)
 Unpacks an agenda off the wire.
bool coords_look_real (const char *lat, const char *lon)
 Whether a pair of coordinates is a place rather than the phone shrugging.
bool music_art_read (const uint8_t *buf, uint16_t len, MusicArt *out)
 Reads art off the wire.
void music_art_copy_rows (const MusicArt *art, uint8_t *dst, uint16_t dst_row_bytes)
 Copies the art's rows into a bitmap's own rows.
bool music_track_set (MusicTrack *track, const char *title, const char *artist, bool playing)
 Takes in the track the phone sent, and says whether anything changed.
bool music_track_has (const MusicTrack *track)
 Whether there is a track to show, which is a title or an artist.
static int phone_level_read (int32_t sent)
 Reads one level off the wire.
bool stock_wire_decode (const uint8_t *buf, uint16_t len, StockStrip *out)
 Unpacks a watchlist off the wire.
bool weather_hourly_decode (const uint8_t *buf, uint16_t len, WeatherHourly *out)
 Unpacks an hourly forecast off the wire.
bool weather_daily_decode (const uint8_t *buf, uint16_t len, WeatherDaily *out)
 Unpacks a 7-day forecast off the wire.
static int32_t wire_int_or (bool is_signed, uint16_t length, const uint8_t *value, int32_t fallback)
 Reads a little-endian integer of exactly length bytes.
static bool wire_cstring_terminated (const char *s, uint16_t length)
 Whether a string of length bytes carries its terminator inside itself.
static int32_t wire_digits_or (const char *text, int32_t fallback)
 Reads text holding only digits as the whole number it spells, such as a select's "3".

Detailed Description

Pure maths, clock, text, and unit helpers that need no watch SDK.

Needing no SDK is what lets them be tested off the watch. Think .beats time, moon phase, weekday names, number formatting, and unit conversions.

Macro Definition Documentation

◆ GOAL_LATCH_BIT

#define GOAL_LATCH_BIT ( goal)
Value:
((uint8_t)(1u << (goal)))

The bit a goal takes in the mask goal_latch_update hands back.

◆ STEP_HOURS_PER_DAY

#define STEP_HOURS_PER_DAY   24

How many hourly buckets a day holds.

◆ WX_COND_EACH

#define WX_COND_EACH ( X)
Value:
X(CLEAR) \
X(PCLDY) \
X(CLDY) \
X(FOGGY) \
X(DRZL) \
X(FZDZ) \
X(RAIN) \
X(FZRN) \
X(SNOW) \
X(SHWR) \
X(SNSH) \
X(STRM)

Hands each condition's name to X, in WxCond order.

A face builds its art table from this rather than writing the rows out, so a condition added to the list needs art of its own or the build stops on the missing name:

#define SKY_ART(name) [WX_COND_##name] = RESOURCE_ID_SKY_##name,
static const uint32_t s_art[WX_COND_COUNT] = {WX_COND_EACH(SKY_ART)};
#define WX_COND_EACH(X)
Hands each condition's name to X, in WxCond order.
Definition wx_cond.g.h:60
@ WX_COND_COUNT
How many conditions there are. Not a condition itself.
Definition wx_cond.g.h:45

Typedef Documentation

◆ FontSlotLoad

typedef void *(*) FontSlotLoad(uint32_t resource)

Loads a font from its resource.

Parameters
resourceThe font's resource id.
Returns
The loaded font, or NULL when it did not load.

◆ FontSlotUnload

typedef void(*) FontSlotUnload(void *handle)

Frees a font the app loaded.

Parameters
handleThe font to free.

Enumeration Type Documentation

◆ FontSlotState

What a slot holds and who frees it. Kept in a uint8_t a slot.

Enumerator
FONT_SLOT_UNOWNED 

Empty, or a system font the firmware owns and the app never frees.

FONT_SLOT_OWNED 

A font the app loaded and registered itself, freed by the registry.

FONT_SLOT_LOADED 

A font loaded from the resource the slot records, freed by the registry.

◆ GoalLatchGoal

The goals the latch watches, in the order it reads their readings and targets.

Enumerator
GOAL_LATCH_STEPS 

Steps so far today.

GOAL_LATCH_CALORIES 

Active calories so far today.

GOAL_LATCH_DISTANCE 

Walked distance so far today, in metres.

GOAL_LATCH_ACTIVE 

Active minutes so far today.

GOAL_LATCH_COUNT 

How many goals the latch watches.

◆ GoalVibeKind

What a Goal Met Vibration pick plays.

Enumerator
GOAL_VIBE_KIND_NONE 

Nothing, the pick is empty.

GOAL_VIBE_KIND_SHORT 

The watch's short pulse, from S.

GOAL_VIBE_KIND_LONG 

The watch's long pulse, from L.

GOAL_VIBE_KIND_DOUBLE 

The watch's double pulse, from D.

GOAL_VIBE_KIND_CUSTOM 

The wearer's own pattern, from C.

GOAL_VIBE_KIND_LIST 

The pick itself, as a comma list of milliseconds.

◆ HrvCount

enum HrvCount

Which bursts count for the main reading. The first is the one a face gets when it sets none.

Enumerator
HRV_COUNT_NOT_WALKING 

Still and busy bursts count, walking ones do not.

HRV_COUNT_STILL 

Only still bursts count.

HRV_COUNT_ANY 

Every burst counts.

◆ HrvState

enum HrvState

What the wearer was doing through a reading's burst.

Enumerator
HRV_STATE_STILL 

The wrist moved no more than the face's still limit, and no walk.

HRV_STATE_BUSY 

The wrist moved more, such as eating or a mouse and keyboard, but no walk.

HRV_STATE_WALKING 

The face's walking step count or more through the burst.

◆ LinkChange

enum LinkChange

What one reading of the link means.

Enumerator
LINK_SAME 

The first reading, or one that matches the last. Nothing to act on.

LINK_DROPPED 

The phone link just went down.

LINK_RECONNECTED 

The phone link just came back.

◆ NightSchedMode

What the schedule is following. The caller's own enum should line up with these.

Enumerator
NIGHT_SCHED_OFF 

Never night.

NIGHT_SCHED_SOLAR 

Sunset to sunrise, falling back to the fixed pair with no reading.

NIGHT_SCHED_FIXED 

The fixed pair only.

◆ Role

enum Role

Which of the three is showing. The caller's own storage should line up with these.

Enumerator
ROLE_DAY 

The everyday look, and what everything else falls back to.

ROLE_NIGHT 

The one the night schedule brings in after dark.

ROLE_QUIET 

The one Quiet Time brings in, whatever the hour.

◆ UvBand

enum UvBand

The risk bands, lowest first.

Enumerator
UV_BAND_NONE 

No reading, from a negative index.

UV_BAND_LOW 

0 to 2

UV_BAND_MODERATE 

3 to 5

UV_BAND_HIGH 

6 and 7

UV_BAND_VERY_HIGH 

8 to 10

UV_BAND_EXTREME 

11 and up

◆ WindUnit

enum WindUnit

Which unit a wind speed reads out in.

The values are the choices the settings page's wind unit row saves, so a saved byte maps straight across. KMH is zero, so no unsigned range check ever compares below zero. KNOWN_WIND_UNIT takes its count from WIND_UNIT_COUNT.

Enumerator
WIND_UNIT_KMH 

kilometres per hour

WIND_UNIT_MPH 

miles per hour

WIND_UNIT_KTS 

knots

WIND_UNIT_MS 

metres per second

WIND_UNIT_COUNT 

how many units there are, not a unit itself

◆ WxCond

enum WxCond

Each weather condition the phone can send, numbered in the order of the shared list.

A value is also the condition's code on the forecast strips, so a column's code with WX_FORECAST_NIGHT_BIT masked off compares straight against these.

Enumerator
WX_COND_CLEAR 

Clear.

WX_COND_PCLDY 

Partly Cloudy.

WX_COND_CLDY 

Cloudy.

WX_COND_FOGGY 

Fog.

WX_COND_DRZL 

Drizzle.

WX_COND_FZDZ 

Freezing Drizzle.

WX_COND_RAIN 

Rain.

WX_COND_FZRN 

Freezing Rain.

WX_COND_SNOW 

Snow.

WX_COND_SHWR 

Showers.

WX_COND_SNSH 

Snow Showers.

WX_COND_STRM 

Thunderstorm.

WX_COND_COUNT 

How many conditions there are. Not a condition itself.

WX_COND_UNKNOWN 

A token the list does not hold, or none at all.

Function Documentation

◆ astro_jd_centi()

int32_t astro_jd_centi ( time_t utc)

The Julian Date multiplied by 100, so the whole part is the day and the last two digits are hundredths. Kept scaled to stay in plain 32-bit integers.

Parameters
utcThe time to read, as a UTC timestamp.
Returns
The Julian Date times 100 (e.g. 245154500 for JD 2451545.00).

◆ beats_expand_token()

void beats_expand_token ( char * text,
int beats )

Overwrite every BEATS_TOKEN in a string with a three digit .beats reading.

Works in place because the token and the reading are the same width, so the string neither grows nor needs its tail shifted. A reading outside 0 to 999 is clamped rather than written, which is what keeps that width promise true.

Parameters
textThe string to fill in, NUL terminated. Left alone if NULL or tokenless.
beatsThe reading to write, 0 to 999.

◆ beats_from_ms()

int beats_from_ms ( int32_t ms_into_bmt_day)

Calculates swatch internet time in .beats (0..999) for a given ms.

Parameters
ms_into_bmt_dayMilliseconds elapsed since Biel Mean Time (UTC+1) midnight.
Returns
The current time in .beats (0 to 999).

◆ beats_has_token()

bool beats_has_token ( const char * format)

Whether a date format asks for a .beats reading.

The face asks this to decide whether to run the .beats ticker. A beat is 86.4 seconds and the date line otherwise redraws on the minute, so without the ticker the reading sits stale and reports every rollover up to a minute late.

Parameters
formatThe date format string, or NULL.
Returns
true if the format carries BEATS_TOKEN.

◆ beats_ms_from_hms()

int32_t beats_ms_from_hms ( int hour,
int minute,
int second,
uint16_t ms )

Milliseconds into the Biel Mean Time day, from a UTC wall clock.

Takes the clock already broken apart rather than a time_t, because breaking one apart means gmtime, and on the watch gmtime and struct tm belong to the SDK rather than to time.h. Reaching for either here would drag the whole SDK into a file whose point is not needing it. The caller holds the clock and this holds the sum.

The two above want ms rather than seconds because a beat boundary falls mid-second, so flooring to whole seconds reads a beat behind at exactly the moment a timer fires to redraw.

Parameters
hourThe UTC hour (0 to 23).
minuteThe UTC minute (0 to 59).
secondThe UTC second (0 to 59).
msThe milliseconds within that second.
Returns
Milliseconds into the current BMT day (0 to 86,399,999).

◆ calendar_wire_decode()

bool calendar_wire_decode ( const uint8_t * buf,
uint16_t len,
CalendarStrip * out )

Unpacks an agenda off the wire.

Layout is [count] then per event [start int32 LE][end int32 LE][flags bit0=allDay][titleLen] [title bytes][locLen][loc bytes]. A count past what the strip holds is pinned to it rather than walking off the end.

Nothing is written to out until the whole run reads clean, so a message that stops halfway leaves the caller's last good agenda alone rather than half replacing it.

Parameters
bufThe raw wire bytes.
lenHow many bytes there are.
[out]outReceives the agenda. Untouched unless this returns true.
Returns
Whether the run read clean.

◆ callback_list_add()

bool callback_list_add ( CallbackList * list,
CallbackListFn cb )

Adds a callback to the end of the list. Adding one that is already there does nothing.

Parameters
listThe list.
cbThe callback. NULL is ignored.
Returns
False only when the list is full and cb was dropped, so the owner can say so.

◆ callback_list_fire()

void callback_list_fire ( const CallbackList * list)

Runs every callback in the order it was added.

Parameters
listThe list.

◆ callback_list_remove()

void callback_list_remove ( CallbackList * list,
CallbackListFn cb )

Takes a callback off the list. The ones after it move up, so the rest keep their order. Removing one that is not there does nothing.

A callback that removes itself or another from inside callback_list_fire makes that run skip the one that moves into its place, so remove from outside a run.

Parameters
listThe list.
cbThe callback.

◆ clamp_int()

int clamp_int ( int value,
int lo,
int hi )

Pin a value into a range, so it lands on the nearer end when it falls outside.

Parameters
valueThe value to pin.
loThe low end, returned when the value is below it.
hiThe high end, returned when the value is above it.
Returns
The value, or whichever end it sat outside.

◆ clock_window_contains()

bool clock_window_contains ( int start,
int end,
int now )

Whether now falls inside a window that may run past midnight.

The start is inclusive and the end exclusive, so two windows that meet at the same minute never both claim it. A window that starts and ends at the same minute is empty rather than eternal, which is the reading that does not surprise anyone who set both dials the same by accident.

Parameters
startFirst minute inside the window, 0 to 1439, or -1 for no reading.
endFirst minute past it, same range.
nowMinutes past midnight.
Returns
True while now is inside. False if any reading is missing.

◆ coords_look_real()

bool coords_look_real ( const char * lat,
const char * lon )

Whether a pair of coordinates is a place rather than the phone shrugging.

The phone sends coordinates as text and says "no fix" by sending something that is not one: an empty string, or a word like "NO LOCK". A coordinate always carries digits and those never do, which is the whole of the test.

Both halves have to hold up. Half a fix is not half a place. It is not a place, and keeping one is how a longitude goes missing and stays missing.

Parameters
latThe latitude as the phone sent it.
lonThe longitude as the phone sent it.
Returns
Whether the pair is worth keeping.

◆ copy_bounded()

void copy_bounded ( char * dst,
uint8_t cap,
const uint8_t * src,
uint8_t len )

Copy bytes into a fixed buffer, taking what fits and terminating it.

For the length-prefixed text the phone sends, where the length is the phone's word and the room is ours. What does not fit is dropped rather than written past the end.

Parameters
[out]dstWhere to write. Ends terminated whenever cap is at least 1.
capHow much room dst has, terminator included. A cap of 0 has no room even for the terminator, so dst is left untouched and not terminated.
srcThe bytes to copy.
lenHow many bytes there are.

◆ cstring_fit()

void cstring_fit ( char * dst,
const char * src,
size_t size )
inlinestatic

Copy a string into a fixed buffer, keeping only what fits and always terminating it.

The cut counts bytes, so a character that takes more than one byte can be split at it. The fonts carry only the characters a face shows, which a character past ASCII is not, so it draws as a box whether it is cut or whole, and walking back to a character boundary would cost bytes for nothing.

Parameters
dstThe buffer to write into.
srcThe string to copy, or NULL to empty the buffer.
sizeThe buffer's size, terminator included.

◆ cstring_fit_same()

bool cstring_fit_same ( const char * current,
const char * value,
size_t size )
inlinestatic

Whether copying value into a buffer would leave it reading exactly as it does now.

The copy keeps only what fits, so the incoming string is measured the same way. Comparing it in full instead would call a value longer than the buffer a change every single time, which for a settings field means re-reacting to a setting nobody touched.

Parameters
currentWhat the buffer holds now.
valueThe string that would be copied in. Must not be NULL.
sizeThe buffer's size, terminator included.
Returns
True when the copy would leave the buffer unchanged.

◆ cstring_is_clean()

bool cstring_is_clean ( const char * s,
uint16_t size )

Whether a byte range holds a string worth keeping.

Worth keeping means it ends inside its own room, it says something, and it carries no control bytes. Everything from 0x20 up counts as text, UTF-8 included, so a place name spelled with an umlaut is text and not damage. Getting that wrong is how a saved city turns back into the default one on the next boot.

Parameters
sThe bytes to look at.
sizeHow much room they have.
Returns
Whether it reads as a string.

◆ cstring_setting_is_clean()

bool cstring_setting_is_clean ( const char * s,
uint16_t size,
const char * default_str )

Whether a saved text setting reads as one, where an empty setting can be the real value.

A setting whose default is empty, such as a picker whose "None" is "", holds nothing on purpose, so empty is a value for it and not damage. Any other setting keeps the cstring_is_clean rule, since an empty one there is what a wiped blob reads like.

Parameters
sThe bytes to look at.
sizeHow much room they have.
default_strThe setting's default, or NULL for none.
Returns
Whether the setting is worth keeping.

◆ date_day_of_year()

int date_day_of_year ( int yday)

Which day of the year it is, counting January 1st as day 1.

Parameters
ydayThe day of the year counting January 1st as 0 (like tm_yday).
Returns
The day number from 1 to 366.

◆ date_days_in_month()

int date_days_in_month ( int year,
int mon0 )

How many days a month has, with February getting its leap day.

Parameters
yearThe full year (2026, not 126).
mon0The month indexed like tm_mon (0 January to 11 December).
Returns
The day count, or 0 for a month index that does not exist.

◆ date_days_left_in_year()

int date_days_left_in_year ( int year,
int yday )

How many days are left before the year ends, so December 31st reads 0.

Parameters
yearThe full year (2026, not 126).
ydayThe day of the year counting January 1st as 0 (like tm_yday).
Returns
The days remaining from 0 to 365.

◆ date_first_wday()

int date_first_wday ( int wday,
int mday )

The weekday the 1st of the month lands on, walked back from today's weekday.

Parameters
wdayToday's weekday, 0 Sunday to 6 Saturday.
mdayToday's day of the month, 1 to 31.
Returns
The weekday of the 1st, 0 Sunday to 6 Saturday.

◆ date_iso_week()

int date_iso_week ( int year,
int yday,
int wday )

The ISO 8601 week number, which always counts weeks from Monday.

A week near a year boundary can belong to the neighbouring year, so the number this returns is not always counted within the year you passed in. Pair it with date_iso_week_year to find out which year it belongs to, and total it against that year rather than this one.

Parameters
yearThe full year (2026, not 126).
ydayThe day of the year counting January 1st as 0 (like tm_yday).
wdayThe weekday, 0 Sunday to 6 Saturday.
Returns
The week number from 1 to 53.

◆ date_iso_week_year()

int date_iso_week_year ( int year,
int yday,
int wday )

The ISO 8601 year the week number belongs to, which is not always the calendar year.

Early January can fall in the previous ISO year and late December in the next one. Feeding this to date_iso_weeks_in_year gives the total that matches what date_iso_week returned, so a "week of total" readout can't end up with a number bigger than its own total.

Parameters
yearThe full year (2026, not 126).
ydayThe day of the year counting January 1st as 0 (like tm_yday).
wdayThe weekday, 0 Sunday to 6 Saturday.
Returns
The ISO year, either year, year - 1, or year + 1.

◆ date_iso_weeks_in_year()

int date_iso_weeks_in_year ( int year)

How many ISO 8601 weeks a year holds, either 52 or 53.

Parameters
yearThe full year (2026, not 126).
Returns
The week count, 52 or 53.

◆ date_weeks_left_in_year()

int date_weeks_left_in_year ( int year,
int yday )

How many whole weeks are left before the year ends. It is the days left divided by 7 and rounded down, so the last seven days of December, the 25th to the 31st, read 0.

Parameters
yearThe full year (2026, not 126).
ydayThe day of the year counting January 1st as 0 (like tm_yday).
Returns
The weeks remaining from 0 to 52.

◆ distance_format()

void distance_format ( char * buffer,
size_t size,
int meters,
bool miles )

Format meters as "N.N MI" or "N.N KM" (rounded to tenth).

Parameters
[out]bufferOutput buffer.
sizeBuffer size.
metersDistance in meters.
milesFormat as miles if true, otherwise km.

◆ distance_format_value()

void distance_format_value ( char * buffer,
size_t size,
int meters,
bool miles )

Format meters as "N.N" (rounded to tenth), no unit suffix.

Parameters
[out]bufferOutput buffer.
sizeBuffer size.
metersDistance in meters.
milesFormat as miles if true, otherwise km.

◆ distance_unit()

const char * distance_unit ( bool miles)

Unit label for the current distance mode ("MI" or "KM").

Parameters
milesMiles if true, otherwise km.
Returns
Static unit string.

◆ duration_hm()

void duration_hm ( char * out,
size_t n,
int minutes )

Format minutes as a clock-style "H:MM", e.g. 445 -> "7:25".

The minutes are zero-padded, so seven hours and five minutes reads "7:05" and not "7:5". A negative count is nothing and reads "0:00".

Parameters
outOutput buffer.
nBuffer size.
minutesThe duration in minutes.

◆ duration_hm_compact()

void duration_hm_compact ( char * out,
size_t n,
int minutes )

Format minutes as "Xh Ym", dropping the hours once it is under one ("45m").

For a countdown, where the hours are only worth showing once there is at least one. A negative count is nothing and reads "0m".

Parameters
outOutput buffer.
nBuffer size.
minutesThe duration in minutes.

◆ fmt_hundredths()

void fmt_hundredths ( char * buffer,
size_t size,
int value )

Format hundredths as a two-decimal number, e.g. 26174 -> "261.74".

Prices and the like ride the wire as whole hundredths so they never touch a float. The sign is written out front rather than left to the whole part, which is what makes -50 read as "-0.50" instead of losing its minus to a whole part of zero.

Parameters
[out]bufferOutput buffer.
sizeBuffer size.
valueThe number times 100.

◆ fmt_int_or_dash()

void fmt_int_or_dash ( char * buffer,
size_t size,
int value,
const char * fmt )

Format an integer, or "--" when there is no reading yet.

A negative value is the no-data marker the readouts share, so this is the one place that turns "I have nothing" into something to draw. The format takes exactly one int, so "%d" or "%d%%".

Parameters
[out]bufferOutput buffer.
sizeBuffer size.
valueThe reading, or a negative number for no data yet.
fmtThe printf format applied when the value is there.

◆ fmt_pct_signed()

void fmt_pct_signed ( char * buffer,
size_t size,
int value )

Format hundredths as a signed two-decimal percent, e.g. 125 -> "+1.25%".

A gain takes a plus, a loss a minus, and flat takes neither. Same reason as fmt_hundredths for writing the sign out front: a change under one percent has a whole part of zero and would lose it otherwise.

Parameters
[out]bufferOutput buffer.
sizeBuffer size.
valueThe percent times 100, signed.

◆ font_slots_load()

bool font_slots_load ( const FontSlots * slots,
uint32_t * resources,
int id,
uint32_t resource,
FontSlotLoad load )

Loads a font into a slot and records the resource it came from.

Like font_slots_put, it overwrites the slot without freeing what it held. A load that fails leaves the slot empty.

Parameters
slotsThe registry's tables.
resourcesOne resource id a slot. Only this and font_slots_swap read or write it, so a face that never calls either keeps the table out of its build.
idThe slot.
resourceThe font's resource id.
loadThe call that loads a font.
Returns
true when the font loaded, false when it did not or the slot is outside the tables.

◆ font_slots_put()

void font_slots_put ( const FontSlots * slots,
int id,
void * handle,
bool owned )

Puts a font in a slot, overwriting whatever it held without freeing it.

Parameters
slotsThe registry's tables.
idThe slot. One outside the tables is ignored.
handleThe font.
ownedtrue for a font the app loaded, which the registry frees, false for a system font.

◆ font_slots_swap()

bool font_slots_swap ( const FontSlots * slots,
uint32_t * resources,
int id,
uint32_t resource,
FontSlotLoad load,
FontSlotUnload unload )

Swaps a slot's font for another resource, freeing the old one when nothing else holds it.

It does nothing when the slot holds a font it loaded from that same resource. Otherwise it lets go of the old font and loads the new one as font_slots_load does. Letting go frees the old font only when the app owns it and no other slot holds it. When another slot the app owns holds it too, that slot keeps it. When the only other holders were put in as system fonts, the first of them takes over owning it, so it is still freed once at the end and never while one is drawing with it.

Parameters
slotsThe registry's tables.
resourcesOne resource id a slot.
idThe slot.
resourceThe font's resource id.
loadThe call that loads a font.
unloadThe call that frees a font.
Returns
true when the slot holds a font from that resource afterwards, false when the load failed or the slot is outside the tables.

◆ font_slots_unload_all()

void font_slots_unload_all ( const FontSlots * slots,
FontSlotUnload unload )

Frees every font the app owns, each one once, and empties every slot.

Parameters
slotsThe registry's tables.
unloadThe call that frees a font.

◆ forecast_days_past()

uint8_t forecast_days_past ( int days_since_first,
uint8_t count )

How many of a daily strip's columns are days before today.

Parameters
days_since_firstWhole days from the strip's first day to today. Zero or less means the strip starts today or later.
countHow many columns the strip holds.
Returns
How many columns from the front are before today, at most count.

◆ forecast_hours_past()

uint8_t forecast_hours_past ( int32_t seconds_into_strip,
uint8_t step_hours,
uint8_t count )

How many of an hourly strip's columns are over.

A column is over once its whole step has gone by, so the column holding the current hour stays.

Parameters
seconds_into_stripSeconds from the start of the first column to now. Zero or less means the strip has not started yet.
step_hoursHours between columns.
countHow many columns the strip holds.
Returns
How many columns from the front are over, at most count.

◆ fraction_px()

int fraction_px ( int total,
int num,
int den )

A fraction of a length in pixels, e.g. how far along a bar a moment sits.

Parameters
totalThe full length.
numThe numerator of the fraction.
denThe denominator of the fraction.
Returns
total * num / den, or 0 for a denominator of zero so there is no divide by it.

◆ goal_latch_update()

uint8_t goal_latch_update ( GoalLatch * latch,
int day,
const int readings[GOAL_LATCH_COUNT],
const int targets[GOAL_LATCH_COUNT] )

Takes the latest readings and says which goals they just met.

A new day clears the marks first. A reading of 0 or less is no reading yet, since the health store reads -1 for a missing step, calorie, or active minutes total and 0 for a missing distance. A target of 0 or less is no goal, for a face that does not keep one. Either way the goal waits.

Parameters
latchThe latch to check and update.
dayThe day of the readings, as tm_yday.
readingsToday's readings, one per GoalLatchGoal in its order.
targetsThe goals, one per GoalLatchGoal in its order.
Returns
A GOAL_LATCH_BIT for each goal met since the last ask, or 0 when none was.

◆ goal_vibe_pattern_kind()

GoalVibeKind goal_vibe_pattern_kind ( const char * pick)

What a pick plays, read from its first character.

Only the first character counts, so anything that opens on S, L, D, or C plays that, and anything else is read as a list of milliseconds.

Parameters
pickThe Goal Met Vibration setting, or NULL.
Returns
What the pick plays. Empty or NULL is GOAL_VIBE_KIND_NONE.

◆ goal_vibe_pattern_parse()

int goal_vibe_pattern_parse ( const char * text,
uint32_t * out,
int capacity )

Reads a list of milliseconds such as "100,80,300" into the caller's buffer.

Any character that is not a digit ends a number, so commas, spaces, and anything else all work as separators, and a run of them adds nothing. Each number is held to GOAL_VIBE_PATTERN_MIN_MS and GOAL_VIBE_PATTERN_MAX_MS, and a run of digits too long for a number reads as the longest step rather than wrapping round. Numbers past the buffer's room are dropped.

Parameters
textThe list, or NULL.
[out]outWhere the steps go, starting on a buzz and then turning between pause and buzz.
capacityHow many steps out holds, normally GOAL_VIBE_PATTERN_MAX.
Returns
How many steps it wrote, 0 for a list with no numbers in it.

◆ goals_active_min()

int goals_active_min ( uint8_t index)

The active minutes goal for a menu choice.

Parameters
indexThe saved choice, 0 for the first option.
Returns
The goal in minutes.

◆ goals_calories()

int goals_calories ( uint8_t index)

The active calorie goal for a menu choice.

Parameters
indexThe saved choice, 0 for the first option.
Returns
The goal in kilocalories.

◆ goals_distance_m()

int goals_distance_m ( uint8_t index)

The distance goal for a menu choice, in metres.

The goals are always kilometres, whatever unit the wearer reads distance in. The unit only matters when the goal is drawn.

Parameters
indexThe saved choice, 0 for the first option.
Returns
The goal in metres.

◆ goals_hr_limit()

int goals_hr_limit ( uint8_t index)

The heart rate limit for a menu choice, the top of a heart rate bar.

Parameters
indexThe saved choice, 0 for the first option.
Returns
The limit in beats per minute.

◆ goals_sleep_min()

int goals_sleep_min ( uint8_t index)

The sleep goal for a menu choice, in minutes.

The page offers whole hours, and this hands back minutes, the unit the health store reads sleep in.

Parameters
indexThe saved choice, 0 for the first option.
Returns
The goal in minutes.

◆ goals_steps()

int goals_steps ( uint8_t index)

The step goal for a menu choice.

Parameters
indexThe saved choice, 0 for the first option.
Returns
The goal in steps.

◆ hour_latch_seed()

void hour_latch_seed ( HourLatch * latch,
time_t start )

Marks an hour as buzzed without buzzing it.

Parameters
latchThe latch to update.
startWhen the hour began, from hour_latch_start.

◆ hour_latch_start()

time_t hour_latch_start ( time_t now,
int tm_min,
int tm_sec )

When the local hour holding a moment began, as seconds since the epoch.

The minute and second have to come from breaking apart the same reading as now. Taking them from an older tick gives one hour two starts whenever a second turns over between the two reads, and the hour buzzes twice.

Parameters
nowThe moment, as seconds since the epoch.
tm_minThe local minute of now.
tm_secThe local second of now.
Returns
The start of the hour holding now.

◆ hour_latch_take()

bool hour_latch_take ( HourLatch * latch,
int tick_min,
time_t start )

Whether a tick should buzz the hour, and if so, marks the hour as buzzed.

Parameters
latchThe latch to check and update.
tick_minThe minute of the tick that is asking. Only minute 0 can buzz.
startWhen the current hour began, from hour_latch_start.
Returns
True the first time minute 0 of an hour asks, false otherwise.

◆ hr_day_add()

void hr_day_add ( HrDay * day,
int hour,
int bpm )

Adds one reading to its hour.

A reading of 0 or less means the watch had none and is left out, and one over 255 is kept as

  1. An hour that has taken 255 readings stops taking more, which a reading a minute never reaches.
Parameters
dayThe day to add to.
hourThe hour of the day the reading was taken in, 0 to 23. Anything else is left out.
bpmThe reading in beats per minute.

◆ hr_day_clear()

void hr_day_clear ( HrDay * day)

Empties the day, for a new day or a fresh start.

Parameters
dayThe day to empty.

◆ hr_day_hour_avg()

int hr_day_hour_avg ( const HrDay * day,
int hour )

The average of one hour's readings.

Parameters
dayThe day to read.
hourThe hour of the day, 0 to 23.
Returns
The average rounded to the nearest beat, or -1 for an hour with no readings.

◆ hr_day_stats()

void hr_day_stats ( const HrDay * day,
int * low,
int * avg,
int * high )

The day's lowest and highest readings, and the average of every reading so far.

The average weighs each reading the same, so an hour with more readings counts for more than a quiet one.

Parameters
dayThe day to read.
lowWhere the lowest goes, or -1 with no readings yet.
avgWhere the average goes, or -1 with no readings yet.
highWhere the highest goes, or -1 with no readings yet.

◆ hrv_hold_over()

bool hrv_hold_over ( uint32_t held_since,
uint32_t now_sec )

Whether the sensor has been held on for a burst as long as it may be.

The watch turns the sensor off once it has a good heart rate, which is only a handful of beats in. So a burst is held on with a short period until its run fills, and this caps that hold in case the run never does, such as with the watch loose on the wrist.

Parameters
held_sinceWhen the hold started, in seconds.
now_secThe time now, in seconds.
Returns
True once HRV_HOLD_MAX_SEC have passed. A clock set back reads as no time passed.

◆ hrv_log_add()

void hrv_log_add ( HrvLog * log,
int ms,
uint32_t now_min,
int32_t day,
int minute_of_day,
HrvState state,
bool asleep )

Files one finished reading.

A reading taken walking goes into the history and the latest walking reading, but not into today's hours or the night, since a walking reading is not a resting one. A new day clears the hours first. A reading taken asleep twelve hours or more after the last one starts a new night, and one taken asleep between noon and 21:00 is a nap's, which stays out of the night.

Parameters
logThe log to add to.
msThe reading in ms.
now_minThe time now, in whole minutes.
dayThe day now, counting from any fixed day, so the hours know when to start over.
minute_of_dayThe minute of the day now, 0 to 1439.
stateWhat the wearer was doing.
asleepWhether Pebble said the wearer was asleep.

◆ hrv_log_count()

int hrv_log_count ( const HrvLog * log)

How many readings the history holds, up to HRV_LOG_SLOTS.

Parameters
logThe log to read.
Returns
The count.

◆ hrv_log_counts()

bool hrv_log_counts ( HrvState state,
HrvCount count )

Whether a burst in one state counts for the main reading.

Parameters
stateWhat the wearer was doing.
countWhich bursts count.
Returns
True when it counts.

◆ hrv_log_get()

bool hrv_log_get ( const HrvLog * log,
int back,
int * ms,
uint32_t * at_min,
uint8_t * flags )

One reading from the history, newest first.

Parameters
logThe log to read.
back0 for the newest, 1 for the one before, and so on.
[out]msThe reading in ms.
[out]at_minWhen it was taken, in minutes.
[out]flagsIts state, plus HRV_LOG_ASLEEP.
Returns
False when there is no reading that far back.

◆ hrv_log_hour_avg()

int hrv_log_hour_avg ( const HrvLog * log,
int hour )

Today's average of the resting readings in one hour.

Parameters
logThe log to read.
hourThe hour from midnight, 0 to 23.
Returns
The average in ms, or -1 for an hour with none.

◆ hrv_log_last()

bool hrv_log_last ( const HrvLog * log,
HrvState state,
int * ms,
uint32_t * at_min )

The latest reading of one kind.

Parameters
logThe log to read.
stateWhich kind.
[out]msThe reading in ms.
[out]at_minWhen it was taken, in minutes.
Returns
False when there has been none of that kind.

◆ hrv_log_night_avg()

int hrv_log_night_avg ( const HrvLog * log)

The average of the readings taken asleep in the latest night.

Parameters
logThe log to read.
Returns
The average in ms, or -1 before any reading taken asleep.

◆ hrv_log_reset()

void hrv_log_reset ( HrvLog * log)

Empties the log.

Parameters
logThe log to empty.

◆ hrv_log_roll_day()

bool hrv_log_roll_day ( HrvLog * log,
int32_t day )

Moves the hours on to a new day without a reading, so a day chart drawn after midnight does not show yesterday as today.

Parameters
logThe log to check.
dayThe day now.
Returns
True when the day changed and the hours were cleared.

◆ hrv_log_state_of()

HrvState hrv_log_state_of ( int motion_score,
int steps,
uint16_t still_mg,
uint16_t walk_steps )

Works out what a burst was from its steps and its movement score.

Steps decide walking, since Pebble's step counter only counts a stepping rhythm and leaves out a busy wrist that is not walking. The score then splits still from busy.

Parameters
motion_scoreThe burst's score from hrv_motion_score, or -1 when there was none.
stepsThe steps taken through the burst, or a negative number when they are not known.
still_mgThe most the wrist may move for the burst to be still, in milli-g a sample.
walk_stepsThe steps through a burst that make it a walk.
Returns
The state. A burst with no score and no steps known counts as still, since nothing said it moved.

◆ hrv_log_today()

void hrv_log_today ( const HrvLog * log,
int * low_ms,
int * avg_ms,
int * high_ms )

Today's resting readings summed up.

Parameters
logThe log to read.
[out]low_msThe lowest hour's average, or -1 with none.
[out]avg_msThe average of every resting reading today, or -1 with none.
[out]high_msThe highest hour's average, or -1 with none.

◆ hrv_motion_cannot_pass()

bool hrv_motion_cannot_pass ( const HrvMotion * motion,
uint16_t max_mg,
uint32_t max_samples )

Whether the burst can no longer finish under a limit, however still the wrist stays.

The score is an average, so a scratch early in a burst lifts it for a while and stillness after brings it back down. Dropping a burst the moment the average crosses the limit would throw away one that ends up well under it. This only says yes once the movement already added up is more than the limit allows over the longest burst there can be.

Parameters
motionThe movement to read.
max_mgThe limit, in milli-g a sample.
max_samplesThe most samples a burst can hold, such as 90 seconds at 10 Hz.
Returns
True when no amount of stillness in the rest of the burst brings it under.

◆ hrv_motion_over()

bool hrv_motion_over ( const HrvMotion * motion,
uint16_t max_mg )

Whether the wrist has moved more than a limit through the burst so far.

Too few samples counts as not over, so a burst is not judged before the accelerometer has said anything.

Parameters
motionThe movement to read.
max_mgThe limit, in milli-g a sample.
Returns
True once the score is over the limit.

◆ hrv_motion_push()

void hrv_motion_push ( HrvMotion * motion,
int16_t x_mg,
int16_t y_mg,
int16_t z_mg )

Adds one accelerometer sample.

Parameters
motionThe movement to add to.
x_mgThe x reading, in milli-g.
y_mgThe y reading, in milli-g.
z_mgThe z reading, in milli-g.

◆ hrv_motion_reset()

void hrv_motion_reset ( HrvMotion * motion)

Empties the movement, ready for the next burst.

Parameters
motionThe movement to empty.

◆ hrv_motion_score()

int hrv_motion_score ( const HrvMotion * motion)

The average movement per sample so far.

Parameters
motionThe movement to read.
Returns
The average in milli-g, or -1 before HRV_MOTION_MIN_SAMPLES moves are in.

◆ hrv_reading_stale()

bool hrv_reading_stale ( uint32_t measured_at,
uint32_t now_sec,
uint16_t period_sec )

Whether a reading is too old to show.

A reading only comes once a run finishes, so with the watch off the wrist the last one would sit on screen for good. This puts it down once a few sample periods pass with nothing new.

Parameters
measured_atWhen the reading was taken, in seconds.
now_secThe time now, in seconds.
period_secHow often the watch samples, in seconds.
Returns
True when the reading should go back to no reading.

◆ hrv_run_finish()

int hrv_run_finish ( HrvRun * run)

Ends a run and empties it. How many differences it held stays in finished_diffs, so a caller can say how much of the burst went into the reading.

Parameters
runThe run to finish.
Returns
Its RMSSD in ms, rounded, or -1 when it had fewer than HRV_DIFFS_MIN differences.

◆ hrv_run_push()

int hrv_run_push ( HrvRun * run,
uint16_t ppi_ms,
uint32_t now_sec )

Adds one gap from the watch.

A gap of 0, the watch's no reading, is dropped like a gap out of range and breaks the chain. A gap after a quiet pause ends the run before it and starts the next one. A run reaching HRV_DIFFS_FULL ends there. Each ending hands back the finished run's answer, when it had enough beats to give one.

Parameters
runThe run to add to.
ppi_msThe gap between two beats in ms, or 0 when the watch has none for this beat.
now_secThe time now, in seconds.
Returns
The RMSSD of a run this gap finished, or -1 when no run finished with an answer.

◆ hrv_run_quiet()

bool hrv_run_quiet ( const HrvRun * run,
uint32_t now_sec )

Whether a run has gone quiet, so it is finished and waiting to be read.

The watch only samples now and then, so the last run of a burst is followed by silence rather than another gap. This lets the caller finish it on a timer instead of a whole period later.

Parameters
runThe run to look at.
now_secThe time now, in seconds.
Returns
True when the run holds beats and none has arrived for HRV_QUIET_SEC.

◆ hrv_run_reset()

void hrv_run_reset ( HrvRun * run)

Empties a run, so the next gap starts it.

Parameters
runThe run to empty.

◆ hrv_settle_gaps()

uint8_t hrv_settle_gaps ( uint16_t asked)

How many gaps to leave out at the start of a burst, from the count a face asked for.

The first gaps of a burst can swap between two values while the sensor settles, so the store leaves some out. A face can tune how many, and this holds its ask to 1 to HRV_SETTLE_GAPS_MAX.

Parameters
askedThe gaps the face asked for, or 0 for HRV_SETTLE_GAPS.
Returns
HRV_SETTLE_GAPS for 0, otherwise the ask, held to HRV_SETTLE_GAPS_MAX.

◆ hrv_should_ask()

bool hrv_should_ask ( bool sampling,
uint32_t gap_at,
uint32_t asked_at,
uint32_t now_sec,
uint16_t period_sec )

Whether to ask the watch for beat gaps again.

The watch is asked again when it turned the last request down, or when no gap has come for as long as a reading takes to go stale, which is how a dropped request shows. The asks are spaced by that same wait, so a watch with no sensor is asked about twice an hour rather than every turn.

Parameters
samplingWhether the watch took the last request.
gap_atWhen the last gap arrived, or the watch took a request, in seconds.
asked_atWhen the watch was last asked, in seconds.
now_secThe time now, in seconds.
period_secHow often the watch takes a burst, in seconds.
Returns
True when the watch should be asked now.

◆ layout_has_any_block()

bool layout_has_any_block ( const char * layout,
int type_count )

Whether a layout string holds at least one placeable block.

One test covers the ways a layout can be nothing: the "0" marker a cleared grid is sent as, an empty string, and whatever a corrupt blob left behind. A record naming a module the catalogue does not have is not placeable either, so it does not count.

Parameters
layoutThe wire string, or NULL.
type_countHow many module numbers the caller's catalogue has, so anything at or past it is junk.
Returns
True when at least one record names a real module.

◆ layout_parse_int()

int layout_parse_int ( const char ** cursor)

Reads a run of digits and moves the cursor past them.

A number past LAYOUT_INT_MAX comes back as -1 rather than overflowing, since only a corrupt string holds one. Its digits are still skipped, so the cursor lands on the next field either way.

Parameters
cursorThe cursor, moved past the digits.
Returns
The value read, 0 when there are no digits, or -1 when it is too big.

◆ link_change_read()

LinkChange link_change_read ( LinkState * state,
bool connected )
inlinestatic

Takes one reading of the link and says what it means.

The new reading is kept whatever it means, so a store reading the state from inside a buzz or a catch-up sees the link as it is now.

Parameters
stateThe link as last read. Updated to this reading.
connectedTrue when the phone link is up now.
Returns
LINK_DROPPED or LINK_RECONNECTED for a real change, and LINK_SAME for the first reading or a repeat.

◆ minute_window_first_slot()

int minute_window_first_slot ( time_t first_min,
time_t end_min,
int minutes )

Where the first of a run of back to back minute records lands in a window.

The window's last slot holds end_min and each slot before it holds the minute before. A record older than the window lands below zero, one newer than its end lands past the last slot, and the caller skips both.

Parameters
first_minThe minute the first record belongs to, as minutes since the epoch.
end_minThe minute the window's last slot holds, the same way.
minutesHow many slots the window has.
Returns
The slot for the first record, which can fall outside 0 to minutes - 1.

◆ moon_age_sec()

int32_t moon_age_sec ( time_t utc)

How far into the current moon cycle we are, in seconds.

Parameters
utcThe time to read, as a UTC timestamp.
Returns
Seconds since the last new moon (0 means new moon, up to MOON_SYNODIC_SEC).

◆ moon_days_to_phase()

int moon_days_to_phase ( time_t utc,
bool to_full )

How many days until the next full or new moon, rounded to the nearest whole day.

Within half a day of the moon, before or after, it counts as now.

Parameters
utcThe time to read, as a UTC timestamp.
to_fullTrue counts to the next full moon, false to the next new moon.
Returns
The days to wait, 0 to 29, where 0 means it is about now.

◆ moon_glyph_index()

int moon_glyph_index ( time_t utc,
int count )

Picks one of count evenly spaced phase icons. It wraps back round at the end.

Parameters
utcThe time to read, as a UTC timestamp.
countHow many phase icons there are.
Returns
The icon to show (0 means new moon, or when count is not positive).

◆ moon_illumination_pct()

int moon_illumination_pct ( time_t utc)

How lit up the moon looks, from 0 to 100. This is a rough straight-line guess, so it reads 0 at new moon and 100 at full.

Parameters
utcThe time to read, as a UTC timestamp.
Returns
The lit fraction from 0 to 100.

◆ moon_phase_name()

const char * moon_phase_name ( time_t utc)

Short name for the current phase (one of the eight main phases).

Parameters
utcThe time to read, as a UTC timestamp.
Returns
The phase name.

◆ ms_until_next_beat()

uint32_t ms_until_next_beat ( int32_t ms_into_bmt_day)

Calculates milliseconds until the next .beats boundary.

A single beat is exactly 86,400 milliseconds. This is useful for scheduling timers to trigger exactly when the beat rolls over.

Parameters
ms_into_bmt_dayMilliseconds elapsed since Biel Mean Time (UTC+1) midnight.
Returns
Milliseconds remaining until the next beat boundary (1 to 86400).

◆ music_art_copy_rows()

void music_art_copy_rows ( const MusicArt * art,
uint8_t * dst,
uint16_t dst_row_bytes )

Copies the art's rows into a bitmap's own rows.

A bitmap can pad each row past what the art needs, so each row goes to its own start.

Parameters
artThe art read off the wire.
[out]dstThe bitmap's first row.
dst_row_bytesHow far apart the bitmap's rows sit, at least art->row_bytes.

◆ music_art_read()

bool music_art_read ( const uint8_t * buf,
uint16_t len,
MusicArt * out )

Reads art off the wire.

Parameters
bufThe raw wire bytes.
lenHow many bytes there are.
[out]outReceives the art. Untouched unless this returns true.
Returns
True for art the watch can draw. False for no art, and for a run that is short, long, or past either cap, which the store clears to as well.

◆ music_track_has()

bool music_track_has ( const MusicTrack * track)

Whether there is a track to show, which is a title or an artist.

A paused track still counts, so a face can show it with a pause glyph.

Parameters
trackThe track the store holds.
Returns
False only for nothing playing.

◆ music_track_set()

bool music_track_set ( MusicTrack * track,
const char * title,
const char * artist,
bool playing )

Takes in the track the phone sent, and says whether anything changed.

A message holding the same track as before changes nothing, so the face is not woken to redraw what it already shows.

Parameters
trackThe track the store holds. Updated to the new one.
titleThe title as sent, or NULL for none.
artistThe artist as sent, or NULL for none.
playingTrue while it plays.
Returns
True when the track reads differently now.

◆ night_schedule_active()

bool night_schedule_active ( int mode,
int now,
int rise,
int set,
int fixed_start,
int fixed_end,
bool have_night )

Whether the night window is open, whichever way the schedule is set.

Following the sun needs both a sunrise and a sunset to work from. When either is missing this falls back to the fixed pair rather than giving up, so a watch that has never been told where it is still does something sensible, and the two dials the user set earn their keep twice.

Parameters
modeA NightSchedMode. Anything out of range reads as off.
nowMinutes past midnight.
riseSunrise, or -1 for no reading.
setSunset, same.
fixed_startThe user's own start, used by the fixed mode and as the solar fallback.
fixed_endAnd their end.
have_nightTrue when there is actually a night look to switch to.
Returns
True when the night look should be the one showing.

◆ number_group()

void number_group ( char * buffer,
size_t size,
int value )

Format an integer with apostrophe thousands separators (e.g. 20358 -> "20'358").

Negative values keep their leading sign. The Swiss-style apostrophe keeps big counts readable on the small display.

Parameters
[out]bufferOutput buffer.
sizeBuffer size.
valueThe value to format.

◆ pct_of()

int pct_of ( int value,
int goal )

How far along a goal is, from 0 to 100.

Caps at 100 so a beaten goal fills a bar rather than overflowing it, and answers 0 rather than dividing by a goal of zero.

Parameters
valueHow much is done so far.
goalWhat is being aimed at.
Returns
The progress from 0 to 100.
Note
A value below zero is the readouts' no-data marker, and this answers 0 for it, same as it does for a real zero. A caller that needs to tell "nothing yet" apart from "none of it done" has to check before it asks.

◆ phone_level_read()

int phone_level_read ( int32_t sent)
inlinestatic

Reads one level off the wire.

Parameters
sentThe number the phone sent.
Returns
The level from 0 to 100, WIRE_NO_PLUGIN while no plugin serves the battery, or PHONE_NO_LEVEL for no reading.

◆ plot_y()

int plot_y ( int y0,
int height,
int lo,
int hi,
int value )

Map a reading to its pixel row in a plot, with the low end at the bottom.

The window runs from lo at the bottom row to hi at the top, so a bigger reading sits higher up the panel. A reading outside the window is pinned to the nearer edge first, so it never lands on a row outside the plot area.

Parameters
y0The top row of the plot area.
heightThe plot area's height in rows.
loThe value at the bottom of the window.
hiThe value at the top of the window.
valueThe reading to place.
Returns
The pixel row for the reading. A window with no height (hi <= lo) gives the bottom row.

◆ progress_day_pct()

int progress_day_pct ( int hour,
int min,
int sec )

How far through the current day it is.

Parameters
hourThe hour, 0 to 23.
minThe minute, 0 to 59.
secThe second, 0 to 59.
Returns
Whole percent from 0 to 99.

◆ progress_hour_pct()

int progress_hour_pct ( int min,
int sec )

How far through the current hour it is.

Parameters
minThe minute, 0 to 59.
secThe second, 0 to 59.
Returns
Whole percent from 0 to 99.

◆ progress_week_day()

int progress_week_day ( int wday,
int week_start )

How many days the week has run, counting the first day as day 1.

Parameters
wdayToday's weekday, 0 Sunday to 6 Saturday.
week_startThe weekday the week begins on, 0 Sunday to 6 Saturday. A value outside that wraps round, so 7 is Sunday and -1 is Saturday.
Returns
The day number from 1 to 7.

◆ progress_week_pct()

int progress_week_pct ( int wday,
int week_start,
int hour,
int min,
int sec )

How far through the current week it is, counting from the day the week starts on.

Parameters
wdayToday's weekday, 0 Sunday to 6 Saturday.
week_startThe weekday the week begins on, 0 Sunday to 6 Saturday. A value outside that wraps round, so 7 is Sunday and -1 is Saturday.
hourThe hour, 0 to 23.
minThe minute, 0 to 59.
secThe second, 0 to 59.
Returns
Whole percent from 0 to 99.

◆ progress_year_pct()

int progress_year_pct ( int year,
int yday,
int hour,
int min,
int sec )

How far through the current year it is, with February getting its leap day.

Parameters
yearThe full year (2026, not 126).
ydayThe day of the year counting January 1st as 0 (like tm_yday).
hourThe hour, 0 to 23.
minThe minute, 0 to 59.
secThe second, 0 to 59.
Returns
Whole percent from 0 to 99.

◆ read_i16_le()

int16_t read_i16_le ( const uint8_t * p)
inlinestatic

Reads a little-endian signed 16-bit value out of a byte pair.

Parameters
pThe first of the two bytes.
Returns
The value the pair encodes.

◆ read_i32_le()

int32_t read_i32_le ( const uint8_t * p)
inlinestatic

Reads a little-endian signed 32-bit value out of four bytes.

Parameters
pThe first of the four bytes.
Returns
The value the four bytes encode.

◆ role_pick()

Role role_pick ( bool quiet_on,
bool quiet_set,
bool night_on,
bool night_set )

Which role wins, given what is firing and what has something behind it.

Quiet Time sits above the night schedule on purpose. Someone who has set both is saying they want a quieter screen while the watch is quiet, and that holds whether it happens to be dark out or not.

A trigger with nothing assigned is skipped rather than honoured, so the answer walks down to the next one that has something to show and lands on the day role if nothing else does. That is what lets someone use one of these without filling in the other.

Parameters
quiet_onTrue while Quiet Time is on.
quiet_setTrue when something is assigned to Quiet Time.
night_onTrue while the night schedule says it is night.
night_setTrue when something is assigned to night.
Returns
The role whose look should be drawn.

◆ rotate_index()

int rotate_index ( int year,
int yday,
int hour,
int minute,
int interval_min,
int count )

Which of count is up now, advancing by one every interval_min minutes and wrapping round at the end.

The answer holds steady through a slot and steps to the next when the slot turns over, so a screen drawn from it only changes on a boundary. It is 0 for a count of one, and for an interval or a count that is not positive, which is the safe nothing-to-rotate answer.

It counts the year as a round 366 days, so the one boundary at a non-leap new year jumps by more than a single step and can, for a count that divides the jump, land on the same one twice. For a shuffle that one ragged boundary a year does not matter.

The time comes in as the same fields a struct tm carries, so the caller hands them straight from its broken-apart clock.

Parameters
yearYears since 1900, as tm_year.
ydayDays into the year, 0 to 365, as tm_yday.
hourThe hour, 0 to 23, as tm_hour.
minuteThe minute, 0 to 59, as tm_min.
interval_minHow many minutes each one is shown for.
countHow many there are to rotate through.
Returns
The index that is up, from 0 to count - 1.

◆ segment_width()

int segment_width ( int total,
int gap,
int count )

The width of one cell when a strip is carved into evenly spaced segments.

The gaps sit between the cells, so there is one fewer gap than there are cells. The division truncates, which leaves a few pixels of remainder for the caller to centre or absorb.

Parameters
totalThe strip's full width.
gapThe space between two cells.
countHow many cells there are.
Returns
The width of one cell, or 0 for a count of zero so there is no divide by it. Can come back below 1 when the cells do not fit, which the caller is expected to notice.

◆ segments_filled()

int segments_filled ( int level,
int segments )

How many cells of a gauge a percentage lights, rounding up so any charge lights one.

The level is pinned to 0..100 first, so a stray reading cannot light more cells than there are. Rounding up means 1% still shows a cell and 100% fills them all.

Parameters
levelThe fill from 0 to 100.
segmentsHow many cells the gauge has.
Returns
The number of lit cells, from 0 to segments.

◆ series_max_u16()

int series_max_u16 ( const uint16_t * values,
int count )

The largest value in a series, for scaling a bar strip against its busiest slot.

Parameters
valuesThe readings.
countHow many there are.
Returns
The largest value, or 0 for an empty series.

◆ series_range()

int series_range ( const uint8_t * samples,
int count,
uint8_t no_sample,
int * lo,
int * hi,
int * last )

Walk a series of samples for its low, high, and most recent reading.

A slot holding the no-sample value is skipped, so a gappy history still reads its real values. The outputs are filled only when there is at least one real sample. With none they are left as the caller set them, so a caller that seeds them and checks the count first cannot read a value that was never there.

Parameters
samplesThe readings, oldest first so the last real one is the most recent.
countHow many slots there are.
no_sampleThe value that marks an empty slot.
[out]loReceives the lowest real reading.
[out]hiReceives the highest real reading.
[out]lastReceives the most recent real reading.
Returns
How many real samples there were.

◆ solar_day_progress()

int solar_day_progress ( int rise,
int set,
int now )

How far through the daylight it is, from 0 at sunrise to 100 at sunset.

Parameters
riseSunrise, minutes past midnight, or -1 for no data.
setSunset, minutes past midnight, or -1 for no data.
nowThe clock, minutes past midnight, or -1 for no data.
Returns
The progress from 0 to 100, or -1 when it is night or there is no data, so the caller can hide the sun rather than pin it to an end.

◆ solar_next_event()

int solar_next_event ( int rise,
int set,
int now,
bool * is_sunrise )

Minutes until the next sun event, and which one it is.

Sunrise while it is dark, sunset while the sun is up, and tomorrow's sunrise once it has set, wrapping midnight the same way the night progress does.

Parameters
riseSunrise, minutes past midnight, or -1 for no data.
setSunset, minutes past midnight, or -1 for no data.
nowThe clock, minutes past midnight, or -1 for no data.
is_sunriseReceives whether the next event is a sunrise. Untouched when there is no data.
Returns
Minutes until the event, or -1 when there is no data.

◆ solar_night_progress()

int solar_night_progress ( int rise,
int set,
int now )

How far through the night it is, from 0 at sunset to 100 at the next sunrise.

The night usually straddles midnight, so the span runs from sunset round to the next sunrise.

Parameters
riseSunrise, minutes past midnight, or -1 for no data.
setSunset, minutes past midnight, or -1 for no data.
nowThe clock, minutes past midnight, or -1 for no data.
Returns
The progress from 0 to 100, or -1 when it is day or there is no data, so the caller knows to draw the sun instead of the moon.

◆ step_hours_settled()

int step_hours_settled ( int cur_hour,
int cur_min )

How many whole hours have settled, meaning they can never gain another step.

The hour in progress never counts, nor does the hour just gone while the clock is on its first minute: the watch writes a minute's record at the top of the minute after it, below the watchface in priority, so on the rollover turn that last record is usually not there yet.

Parameters
cur_hourThe hour now, 0 to 23.
cur_minThe minute within that hour, 0 to 59.
Returns
How many hours have settled, so buckets below it are final.

◆ stock_wire_decode()

bool stock_wire_decode ( const uint8_t * buf,
uint16_t len,
StockStrip * out )

Unpacks a watchlist off the wire.

Layout is [count] then per slot [ok][price int32 LE cents][pct int16 LE hundredths][symLen] [sym bytes]. A count past what the strip holds is pinned to it rather than walking off the end.

Nothing is written to out until the whole run reads clean, so a message that stops halfway leaves the caller's last good watchlist alone rather than half replacing it.

Parameters
bufThe raw wire bytes.
lenHow many bytes there are.
[out]outReceives the watchlist. Untouched unless this returns true.
Returns
Whether the run read clean.

◆ store_live_after_reconfigure()

bool store_live_after_reconfigure ( bool live,
bool pinned )
inlinestatic

Whether a store runs live once a reconfigure has asked for live.

Parameters
liveWhat the reconfigure asked for.
pinnedTrue when init started the store with live false.
Returns
True only when the reconfigure asked for live and the store is not pinned.

◆ text_to_upper()

void text_to_upper ( char * s)

Uppercase an ascii string in place.

Parameters
sThe string to uppercase.

◆ tide_level()

int tide_level ( int32_t minutes)

How far in the tide is, from 0 at dead low to 100 at high water.

Eased at both ends rather than run at a constant rate, because a real tide stands almost still around the turn and moves fastest halfway through. Water creeping up the sand and then pausing is the part that reads as tidal.

Parameters
minutesA running minute count, e.g. the epoch in minutes. Negative values are fine.
Returns
The level from 0 to 100.

◆ tide_rising()

bool tide_rising ( int32_t minutes)

Whether the tide is on its way in.

Parameters
minutesA running minute count, on the same base as tide_level.
Returns
True while it is flooding, false while it ebbs.

◆ time_config_reconfigure()

bool time_config_reconfigure ( TimeConfig * running,
TimeConfig cfg,
bool pinned )

What a reconfigure does to the rules running, in the order the time store needs.

The face's rules go through time_config_reconfigured first, and only then are they compared with the ones running. Compared the other way round, a pinned clock handed live true would read as a change and start the tickers it is held off from running.

Parameters
[in,out]runningThe rules running now. Replaced with the rules the reconfigure runs.
cfgThe rules the face passed.
pinnedTrue when init started the store with live false, or never started it.
Returns
True when the new rules run different tickers, so the store has to swap them.

◆ time_config_reconfigured()

TimeConfig time_config_reconfigured ( TimeConfig cfg,
bool pinned )

The rules a reconfigure runs, which are the face's own with live held off on a store init started frozen.

Only init decides whether the clock runs at all. A store started with live false stays on its pinned time through every settings save, so a screenshot build never has the real time back at the next tick. A store started live can still be stopped by a reconfigure and started again.

Parameters
cfgThe rules the face passed.
pinnedTrue when init started the store with live false, or never started it.
Returns
The rules to run.

◆ time_config_same_tickers()

bool time_config_same_tickers ( TimeConfig a,
TimeConfig b )

Whether two sets of rules run the same tickers.

It compares what the store would run rather than the fields one by one. With live false nothing runs whatever the other fields say, and with the minute tick on, hourly changes nothing, since the minute tick already lands on the hour.

Parameters
aOne set of rules.
bThe other.
Returns
True when both run the same tickers.

◆ timeband_clip()

bool timeband_clip ( TimeBand band,
time_t window_epoch,
time_t start,
time_t end,
TimeBandSpan * out )

Clip an absolute span onto the window.

Both ends are epochs, which is what an agenda carries, and the window's own first minute is given as one too, so an event from yesterday or from next week falls outside rather than being wrapped onto today.

A span with no length still comes back a minute wide, so a moment someone pinned to their calendar still draws instead of vanishing.

Parameters
bandThe window.
window_epochThe epoch of the window's first minute.
startThe span's start.
endThe span's end. An end before the start is read as having no length.
outReceives the clipped span. Untouched unless this returns true.
Returns
Whether any of the span landed inside the window.

◆ timeband_clip_daily()

int timeband_clip_daily ( TimeBand band,
int from_min,
int to_min,
TimeBandSpan * out,
int max_out )

Clip a daily span, one that repeats every day like the daylight, onto the window.

A window running past midnight can see the same daily span at both of its ends, which is why this hands back pieces rather than one span. A span whose end is at or before its start is read as wrapping midnight itself, so a polar winter's short daylight and a midsummer night's short darkness both work without the caller knowing which it has.

Parameters
bandThe window.
from_minThe daily span's start, minutes past midnight, or -1 for no reading.
to_minIts end, same. A -1 on either side gives no pieces.
outReceives the pieces, earliest first.
max_outHow many out holds. Two is enough for any window of a day or less.
Returns
How many pieces were written, 0 to 2.

◆ timeband_from_hour()

TimeBand timeband_from_hour ( int base_hour,
int span_min )

A window starting at the top of a given hour.

The hourly forecast carries its own base hour, so feeding it in here lands the strip's columns on even fractions of the axis instead of somewhere arbitrary along it.

Parameters
base_hourThe hour the window opens on, wrapped into 0..23.
span_minHow long it runs, pinned to 1..1440.
Returns
The window.

◆ timeband_offset()

int timeband_offset ( TimeBand band,
int minute_of_day )

How far into the window a minute of the day falls.

Parameters
bandThe window.
minute_of_dayThe moment, minutes past midnight.
Returns
Minutes past the window's start, 0 to span_min - 1, or -1 when it sits outside. The far end is outside: a window is half open so two of them laid end to end share no minute.

◆ timeband_pos()

int timeband_pos ( TimeBand band,
int length,
int minute_of_day )

Where a minute of the day lands along an axis of a given length.

Parameters
bandThe window.
lengthThe axis length in whatever the caller measures it in.
minute_of_dayThe moment, minutes past midnight.
Returns
0 to length - 1, or -1 when the moment sits outside the window or the length is not positive.

◆ timeband_pos_offset()

int timeband_pos_offset ( TimeBand band,
int length,
int offset_min )

The same mapping for a value already measured from the window's start.

This is the one the drawing uses, since everything clipped comes back as an offset. It takes the far end too, so a span ending exactly at the window's end reaches the end of the axis rather than stopping a unit short.

Parameters
bandThe window.
lengthThe axis length.
offset_minMinutes past the window's start, 0 to span_min.
Returns
0 to length, or -1 when the offset is outside 0..span_min or the length is not positive.

◆ timeband_rolling()

TimeBand timeband_rolling ( int now_min,
int span_min,
int lead_min )

A window that puts a given moment a fixed way into it.

Parameters
now_minThe moment to place, minutes past midnight.
span_minHow long the window runs, pinned to 1..1440.
lead_minHow far into it the moment sits, pinned to 0..span_min - 1. The window's last minute is the furthest in, since its far end belongs to whatever comes next.
Returns
The window, its start wrapped into 0..1439.

◆ timeband_window_epoch()

time_t timeband_window_epoch ( TimeBand band,
time_t now,
int now_min )

The epoch the window's first minute sits at.

It counts back from now rather than forward from midnight. A day the clocks change on is an hour short or long, so midnight plus the window's start would land an hour off, while the minutes between the window's start and now are the same real minutes on any day. A rolling window that crossed midnight opened yesterday, which counting back finds without being told.

A window that has not opened yet, such as a forecast strip starting at the next hour, is the one coming up later today.

The clock is handed over both ways rather than worked out here, so this needs no localtime and tests off the watch.

Parameters
bandThe window.
nowThe clock as an epoch.
now_minThe same moment on the wall clock, minutes past midnight.
Returns
The epoch of the window's first minute.

◆ uv_band()

UvBand uv_band ( int uv)

The band a UV index falls in.

Parameters
uvThe index, such as weather_store_uv(). Anything below 0 is no reading.
Returns
The band, or UV_BAND_NONE for a negative index.

◆ uv_band_name()

const char * uv_band_name ( UvBand band)

The band's full name in capitals, such as "MODERATE" or "VERY HIGH".

Parameters
bandThe band.
Returns
The name, or an empty string for UV_BAND_NONE or a value outside the enum.

◆ uv_band_short_name()

const char * uv_band_short_name ( UvBand band)

The band's short name in capitals, at most six letters, such as "MOD" or "V.HIGH".

For a slot that has the number in front of the band and little room left after it.

Parameters
bandThe band.
Returns
The name, or an empty string for UV_BAND_NONE or a value outside the enum.

◆ weather_daily_decode()

bool weather_daily_decode ( const uint8_t * buf,
uint16_t len,
WeatherDaily * out )

Unpacks a 7-day forecast off the wire.

Layout is [count][base_weekday] then per column [code][max int16 LE][min int16 LE]. A count past what the strip holds is pinned to it rather than walking off the end.

Parameters
bufThe raw wire bytes.
lenHow many bytes there are.
[out]outReceives the strip. Untouched unless this returns true: everything that can turn a message away is settled before the first byte of it is written.
Returns
Whether the run read clean.

◆ weather_hourly_decode()

bool weather_hourly_decode ( const uint8_t * buf,
uint16_t len,
WeatherHourly * out )

Unpacks an hourly forecast off the wire.

Layout is [count][base_hour][step_hours] then per column [code][temp int16 LE]. A count past what the strip holds is pinned to it rather than walking off the end.

Parameters
bufThe raw wire bytes.
lenHow many bytes there are.
[out]outReceives the strip. Untouched unless this returns true: everything that can turn a message away is settled before the first byte of it is written.
Returns
Whether the run read clean.

◆ weather_reading_apply()

bool weather_reading_apply ( WeatherState * state,
const WeatherMessage * msg,
const WeatherClock * clock )

Put a message's readings into the kept weather.

A group that did not arrive leaves its readings alone. One that did replaces all of them, and a reading it left out becomes that reading's no-data value, -1 or WEATHER_NO_TEMP for the temperatures. The current temperature, the high and low, the feels-like, and the dew point are held to -99 to 199, and one sent as WEATHER_NO_TEMP stays no data. A failed fetch keeps the last good temperature and sky. A strip that does not read clean keeps the last good row, and a strip's temperatures are kept as they arrive until weather_reading_convert holds them to the same range.

Each strip that reads clean records where its first column starts, and the high, low, UV, and rain chance record the day they came, so the store can tell later what has gone by.

Parameters
stateThe kept weather, updated in place.
msgThe message.
clockThe watch's clock as the message landed. Its time is stamped as the last sync when anything was kept.
Returns
Whether anything was kept, which is when the face needs a redraw and a save.

◆ weather_reading_convert()

void weather_reading_convert ( WeatherState * state,
bool to_fahrenheit )

Convert every temperature in the kept weather to the other unit.

Runs when the wearer switches units, so the reading in hand matches the new letter until the phone's fetch in the new unit lands. Each value rounds to the nearest degree, and a reading with no data stays that way.

Parameters
stateThe kept weather, converted in place.
to_fahrenheitTrue to go from Celsius to Fahrenheit, false for the other way.

◆ weather_reading_convert_temp()

int weather_reading_convert_temp ( int value,
bool to_fahrenheit )

Converts one temperature to the other unit, rounded to the nearest degree and held to the range the weather keeps. No data stays no data.

Parameters
valueThe temperature, or WEATHER_NO_TEMP for none.
to_fahrenheitTrue to go from Celsius to Fahrenheit, false for the other way.
Returns
The temperature in the other unit, or WEATHER_NO_TEMP.

◆ weekday_short()

const char * weekday_short ( int wday)

The two-letter short name for a weekday, indexed like tm_wday and the phone's base_weekday (0 = Sunday through 6 = Saturday).

Parameters
wdayThe weekday, 0 (Sunday) through 6 (Saturday).
Returns
The short name ("SU".."SA"), or "" when the index is out of range.

◆ wind_bearing()

int wind_bearing ( const char * dir)

The bearing a 16-point compass abbreviation stands for.

Meteorological convention: the bearing is where the wind is coming from, so "N" is 0 and a northerly blows towards the south.

Parameters
dirThe abbreviation, e.g. "N", "ESE", "NW". Case insensitive.
Returns
Degrees from 0 to 337, or -1 when the string is not one of the sixteen points.

◆ wind_from_kmh()

int wind_from_kmh ( int kmh,
WindUnit unit )

Convert a km/h wind speed into the chosen unit.

Integer maths, rounded to the nearest whole number. The phone sends a plugin's wind as whole km/h, so rounding brings a speed such as 10 mph back to 10 rather than 9. An unknown unit falls back to km/h.

Parameters
kmhThe wind speed in km/h.
unitThe unit to convert into.
Returns
The wind speed in the chosen unit.

◆ wind_lean()

int wind_lean ( int bearing)

The east-west component of a wind, as a signed proportion.

Anything drawn from the side only shows the part of a wind that runs across the view: one blowing straight towards or away from the viewer has no sideways component at all, and one blowing along the view has the whole of it. Positive is eastward, which is the way a wind out of the west goes.

Parameters
bearingDegrees, or -1 for no data.
Returns
-100 (full westward) to 100 (full eastward), or 0 when there is no reading.

◆ wind_unit_label()

const char * wind_unit_label ( WindUnit unit)

The short label for a wind unit.

Parameters
unitThe unit to label.
Returns
"KM/H" / "MPH" / "KTS" / "M/S", km/h for an unknown unit.

◆ wire_cstring_terminated()

bool wire_cstring_terminated ( const char * s,
uint16_t length )
inlinestatic

Whether a string of length bytes carries its terminator inside itself.

A sender is supposed to include the terminator and nothing re-checks that it did. A string without one is not a string: reading it runs on past the end looking for a zero byte that belongs to something else, or to nothing at all.

Parameters
sThe first byte of the string.
lengthHow many bytes the string occupies, terminator included.
Returns
Whether it is safe to read as a C string.

◆ wire_digits_or()

int32_t wire_digits_or ( const char * text,
int32_t fallback )
inlinestatic

Reads text holding only digits as the whole number it spells, such as a select's "3".

Clay sends a select's value as text, so a choice of 3 arrives as "3". One or more digits and nothing else is a number. A sign, a space at either end, or anything after the digits gives the fallback, so "3a" is turned away rather than read as 3.

A run of digits too big for an int32_t is still a number, just a big one, so it reads as INT32_MAX. That keeps it apart from the fallback, and a choice then takes it the way it takes "300", as past the end of its list.

Parameters
textThe text, already checked to end inside its own length, or NULL.
fallbackReturned when there is no text, or it holds anything but digits.
Returns
The number, INT32_MAX for digits past it, or fallback.

◆ wire_int_or()

int32_t wire_int_or ( bool is_signed,
uint16_t length,
const uint8_t * value,
int32_t fallback )
inlinestatic

Reads a little-endian integer of exactly length bytes.

Parameters
is_signedWhether the value is signed. Decides only what the top bit means.
lengthHow many bytes the value occupies. 1, 2, and 4 are the widths a sender may use, and anything else is refused rather than guessed at.
valueThe first byte of the value.
fallbackReturned when the width is not one a sender may use, or there is no value.
Returns
The value, or fallback.

◆ wx_cond_parse()

WxCond wx_cond_parse ( const char * token,
bool * night )

Finds the condition for a token, with or without its "_NIGHT" ending.

The match is exact and minds case, the same as the icon lookup, so "rain" or "RAINY" reads as unknown.

Parameters
tokenThe token, such as "RAIN" or "RAIN_NIGHT". NULL or empty reads as unknown.
nightSet to whether the token ended in "_NIGHT", and false for an unknown one. May be NULL.
Returns
The condition, or WX_COND_UNKNOWN for a token the list does not hold.

◆ wx_label_short()

void wx_label_short ( char * out,
size_t n,
const char * condition )

Writes the short word for a condition token, without its "_NIGHT" suffix.

Parameters
outWhere the word goes.
nThe room in out, terminator included.
conditionThe token, such as "PCLDY_NIGHT". NULL or empty writes "UNKNOWN".

◆ zone_setting_is_set()

bool zone_setting_is_set ( const char * value)

Whether the setting holds a zone at all.

An empty one is no zone rather than UTC with no name, so a panel shows dashes for it rather than a clock for a place nobody picked.

Parameters
valueThe setting, or NULL.
Returns
True when a zone is set.

◆ zone_setting_label()

const char * zone_setting_label ( const char * value)

The place's name, everything after the first comma.

A name can carry commas of its own, as in "Paris, Ile-de-France, France", so a caller that wants only the city cuts it at the next comma itself.

Parameters
valueThe setting, or NULL.
Returns
The name, or an empty string when the setting has none.

◆ zone_setting_offset()

int16_t zone_setting_offset ( const char * value)

How many minutes the zone is ahead of UTC, negative for one behind.

Parameters
valueThe setting, or NULL.
Returns
The offset in minutes, or 0 when no zone is set.