Kleidos API Search

In development. It changes without notice.

Topic

Clock & Time Zone

The wall clock and how far it is trusted, what set it last, and the time zones with their daylight-saving rules.

The clock is read and set through one set of functions, over a clock chip (Clock Chip Back End) on the boards that have one and over the ESP32-S3's own clock on the others (kleidos::timex::rtc::soc, how far that clock is trusted and how it wakes the board). It answers with a trust: None while it is not set, Volatile while it holds only as long as the board is powered, and Backed where a clock chip keeps it. What decides by the time asks for the trust it needs. Every module that turns a date into an epoch, or back, does it through one civil calendar (kleidos::timex::calendar).

The clock holds UTC. The owner picks a time zone from a table, and the rules for daylight saving in both hemispheres are computed here, with no zone database. The record of what set the clock last is for a screen to show and is never an input to a decision; whether a precise source still vouches for it is another record, which One-Time Codes reads.

See also
One-Time Codes, Clock Chip Back End, Network Services

Files

file src/time/calendar.h
The civil calendar in UTC: a date and time of day to and from a Unix epoch.
file src/time/clock_source.h
NVS-persisted record of WHO set the clock last (display-only).
file src/time/local_time.h
User timezone + DST preference facade: persistence and local display time.
file src/time/precise_sync.cpp
The precise-sync record: implementation of precise_sync.h.
file src/time/precise_sync.h
Whether the wall clock still holds a time a precise source set.
file src/time/rtc_hal.h
Device-agnostic real-time-clock access (the rtc:: namespace).
file src/time/rtc_hal_soc.h
The SoC clock backend of the rtc:: facade: its trust rule, wake math and clock seam.
file src/time/timezone.h
Pure, host-testable timezone + DST model with an in-house DST engine.
file src/time/wall_clock_epoch.h
Trust-gated wall clock → Unix epoch: the one read every consumer shares.
file src/time/zone_offset_labels.h
Each zone's standard UTC offset as a row label ("UTC+01:00").

Namespaces

namespace kleidos::timex::rtc
The real-time clock behind one interface, a clock chip or the SoC's internal RTC, with how far its time can be trusted.
namespace kleidos::timex::rtc::clock_source
Persistence and labeling for the last clock-set source tag.

Classes

struct kleidos::timex::calendar::DateTime
A calendar date paired with a time of day. More about kleidos::timex::calendar::DateTime
struct kleidos::timex::precise::Status
What the console reports about the record. More about kleidos::timex::precise::Status
struct kleidos::RtcTime
Wall-clock time of day. More about kleidos::RtcTime
struct kleidos::RtcDate
Calendar date. More about kleidos::RtcDate
struct kleidos::RtcAlarm
Alarm match specification. More about kleidos::RtcAlarm
struct kleidos::timex::rtc::soc::TrustEvaluation
Result of a trust evaluation. More about kleidos::timex::rtc::soc::TrustEvaluation
struct kleidos::timex::DstRule
A daylight-saving-time rule as nth-weekday-of-month transitions. More about kleidos::timex::DstRule
struct kleidos::timex::TimeZone
A selectable timezone: a display name, a standard offset, and a rule. More about kleidos::timex::TimeZone
struct kleidos::timex::LocalDateTime
A calendar date paired with a local time of day. More about kleidos::timex::LocalDateTime
struct kleidos::timex::WallClockEpoch
Result of deriving a Unix epoch from the trust-gated wall clock. More about kleidos::timex::WallClockEpoch

Enumerations

enum class kleidos::timex::rtc::ClockSource : uint8_t { kleidos::timex::rtc::ClockSource::Unknown, kleidos::timex::rtc::ClockSource::Manual, kleidos::timex::rtc::ClockSource::WebAdmin, kleidos::timex::rtc::ClockSource::Gps, kleidos::timex::rtc::ClockSource::Ntp }
Provenance of the most recent clock set (display/diagnostics only). More about kleidos::timex::rtc::ClockSource
enum class kleidos::RtcTimerSource : uint8_t { kleidos::RtcTimerSource::Hz4096 , kleidos::RtcTimerSource::Hz64 , kleidos::RtcTimerSource::Hz1 , kleidos::RtcTimerSource::Hz1Over60 }
Countdown-timer source frequency (selects the tick rate the reload value is decremented at). More about kleidos::RtcTimerSource
enum class kleidos::RtcClockOut : uint8_t { kleidos::RtcClockOut::Off, kleidos::RtcClockOut::Hz1, kleidos::RtcClockOut::Hz32, kleidos::RtcClockOut::Hz1024, kleidos::RtcClockOut::Hz32768 }
CLKOUT pin output frequency. More about kleidos::RtcClockOut
enum class kleidos::timex::rtc::ClockTrust : uint8_t { kleidos::timex::rtc::ClockTrust::None , kleidos::timex::rtc::ClockTrust::Volatile , kleidos::timex::rtc::ClockTrust::Backed }
Trust ranking of the running wall clock. More about kleidos::timex::rtc::ClockTrust

Functions

DateTimekleidos::timex::calendar::epochToDateTime (uint32_t unixEpoch)
Convert a Unix epoch (UTC seconds since 1970-01-01) to date + time.
uint32_tkleidos::timex::calendar::dateTimeToEpoch (const RtcDate &date, const RtcTime &time)
Convert a UTC calendar date + time of day to a Unix epoch.
uint8_tkleidos::timex::local::zoneIdx ()
The selected zone index into kZones (clamped; 0 = UTC default).
const TimeZone &kleidos::timex::local::zone ()
The selected TimeZone entry (shorthand for kZones[zoneIdx()]).
boolkleidos::timex::local::setZoneIdx (uint8_t idx)
Select a zone by table index: validate, persist, cache, re-export TZ.
boolkleidos::timex::local::dstEnabled ()
The DST option: honor the zone's DST rule (default ON).
boolkleidos::timex::local::setDstEnabled (bool enabled)
Set the DST option: persist, cache, re-export the TZ string in effect.
const char *kleidos::timex::local::posixTz ()
The POSIX TZ string currently in effect (DST-rule or fixed variant).
voidkleidos::timex::local::applyFromStorage ()
Boot hook: load the persisted preference and export TZ to libc.
LocalDateTimekleidos::timex::local::toLocal (uint32_t utcEpoch)
Convert a UTC epoch to local date/time in the active zone.
uint32_tkleidos::timex::local::toUtc (const RtcDate &date, const RtcTime &time)
Convert a local date/time in the active zone to a UTC epoch.
boolkleidos::timex::local::dstActiveAt (uint32_t utcEpoch)
Whether DST is in effect at utcEpoch under the active preference.
boolkleidos::timex::local::localNow (LocalDateTime &out, rtc::ClockTrust minTrust)
Trust-gated "local now": read the clock and convert in one step.
voidkleidos::timex::local::resetForTest ()
Drop the cached preference so the next call re-reads NVS (host tests).
uint32_tkleidos::timex::precise::writeGeneration ()
The clock-write count, to read before a precise write.
voidkleidos::timex::precise::markSynced (uint32_t generationBeforeWrite)
Mark the clock write made after generationBeforeWrite as precise.
voidkleidos::timex::precise::invalidate ()
Clear the record: the clock is about to be written.
boolkleidos::timex::precise::fresh ()
Whether the clock still holds a precise time.
Statuskleidos::timex::precise::status ()
The record, for the console.
voidkleidos::timex::precise::debugMarkSynced ()
Debug only: mark the clock's current value as precise, writing nothing.
voidkleidos::timex::rtc::debugForgetClock ()
Debug only: make the clock read as if it had never been set.
boolkleidos::timex::rtc::debugClockForgotten ()
Whether debugForgetClock is in effect.
voidkleidos::timex::rtc::debugRememberClock ()
Clear debugForgetClock; called by every path that sets the clock.
boolkleidos::timex::rtc::debugMarkClockLost ()
Debug only: make the battery-backed RTC report its time lost.
ClockTrustkleidos::timex::rtc::clockTrust ()
Report the trust level of the clock this board is currently keeping.
boolkleidos::timex::rtc::isAvailable ()
Check if a usable clock is available on this board.
RtcTimekleidos::timex::rtc::getTime ()
Read current time from the RTC.
voidkleidos::timex::rtc::setTime (const RtcTime &t)
Write the time of day to this board's clock, RTC chip or SoC timer.
RtcDatekleidos::timex::rtc::getDate ()
Read current date from the RTC.
voidkleidos::timex::rtc::setDate (const RtcDate &d)
Write the calendar date to this board's clock, RTC chip or SoC timer.
voidkleidos::timex::rtc::setDateTime (const RtcDate &d, const RtcTime &t)
Set the RTC date and time as one combined instant (atomic facade write).
voidkleidos::timex::rtc::getDateTime (RtcDate &date, RtcTime &time)
Read date and time as one coherent single-instant snapshot.
boolkleidos::timex::rtc::getValidTime (RtcDate &date, RtcTime &time, ClockTrust minTrust)
Read the clock only when it meets a minimum trust level.
boolkleidos::timex::rtc::clockIntegrityValid ()
Check whether the RTC still reports valid clock integrity.
boolkleidos::timex::rtc::setAlarm (const RtcAlarm &alarm)
Program the alarm and arm the alarm interrupt.
boolkleidos::timex::rtc::readAlarm (RtcAlarm &alarm)
Read back the currently programmed alarm.
boolkleidos::timex::rtc::clearAlarm ()
Disarm the alarm interrupt and clear a pending alarm flag.
boolkleidos::timex::rtc::alarmTriggered ()
Query whether the alarm has fired (AF flag set).
boolkleidos::timex::rtc::setCountdownTimer (RtcTimerSource src, uint8_t ticks)
Arm the countdown timer with a reload value and source frequency.
boolkleidos::timex::rtc::stopCountdownTimer ()
Stop the countdown timer and clear its interrupt enable and flag.
boolkleidos::timex::rtc::configureClockOut (RtcClockOut freq)
Configure the CLKOUT pin output frequency (or disable it).
boolkleidos::timex::rtc::readCountdownTimerRunning (bool &running)
Query whether the countdown timer is currently armed.
boolkleidos::timex::rtc::readClockOut (RtcClockOut &freq)
Read the current CLKOUT pin configuration.
boolkleidos::timex::rtc::rtcAlarmWakeSupported ()
Report whether this board can wake from deep sleep on an RTC alarm.
boolkleidos::timex::rtc::armAlarmWake (const RtcAlarm &alarm)
Program the alarm and arm a deep-sleep pin wake from the RTC INT line.
TrustEvaluationkleidos::timex::rtc::soc::evaluateTrust (uint32_t floorEpoch, uint32_t derivedNow, bool coldBoot, bool wasEverSet)
Evaluate the running clock's trust and effective epoch.
uint64_tkleidos::timex::rtc::soc::clampWakeMicros (uint64_t micros)
Clamp a raw wake delay to [kleidos::platform::sleep::kMinTimerWakeUs, kleidos::platform::sleep::kMaxTimerWakeUs], the facade's own bounds.
uint64_tkleidos::timex::rtc::soc::computeWakeMicros (uint32_t nowEpoch, uint32_t targetEpoch)
Compute the clamped LP-timer wake delay from now to a target epoch.
uint64_tkleidos::timex::rtc::soc::countdownToMicros (RtcTimerSource src, uint8_t ticks)
Convert a countdown (source frequency, tick count) to microseconds.
uint32_tkleidos::timex::rtc::soc::alarmNextEpoch (uint32_t nowEpoch, const RtcAlarm &alarm)
Next Unix epoch strictly after nowEpoch matching the enabled alarm fields (disabled fields are wildcards).
voidkleidos::timex::rtc::soc::applyEpochToClock (uint32_t epoch)
Set the SoC clock to an epoch.
uint32_tkleidos::timex::rtc::soc::currentEpoch ()
The SoC clock's current Unix epoch.
constexpr uint8_tkleidos::timex::dowOfCivil (int32_t y, uint8_t m, uint8_t d)
Day of week for a proleptic-Gregorian date (0=Sun..6=Sat).
constexpr uint8_tkleidos::timex::nthWeekdayDom (int32_t year, uint8_t month, uint8_t week, uint8_t dow)
Day-of-month of the week-th dow in month of year.
constexpr int32_tkleidos::timex::transitionKey (uint8_t month, uint8_t day, uint8_t hour)
Pack a (month, day, hour) triple into a monotonically comparable key.
constexpr boolkleidos::timex::isDstActive (const TimeZone &tz, const RtcDate &date, const RtcTime &time)
Whether DST is active for a zone at a given local date/time.
constexpr int16_tkleidos::timex::effectiveOffsetMin (const TimeZone &tz, const RtcDate &date, const RtcTime &time, bool dstEnabled)
Effective UTC offset (minutes) for a zone at a given local date/time.
constexpr int16_tkleidos::timex::effectiveOffsetMin (const TimeZone &tz, const RtcDate &date, const RtcTime &time)
Effective UTC offset (minutes), DST rule always honored.
constexpr uint32_tkleidos::timex::localToUtcEpoch (const RtcDate &date, const RtcTime &time, const TimeZone &tz, bool dstEnabled)
Convert a local date/time in tz to a UTC Unix epoch.
constexpr uint32_tkleidos::timex::localToUtcEpoch (const RtcDate &date, const RtcTime &time, const TimeZone &tz)
Convert a local date/time in tz to a UTC Unix epoch (DST honored).
LocalDateTimekleidos::timex::utcEpochToLocal (uint32_t utcEpoch, const TimeZone &tz, bool dstEnabled)
Convert a UTC Unix epoch to local date/time in tz.
LocalDateTimekleidos::timex::utcEpochToLocal (uint32_t utcEpoch, const TimeZone &tz)
Convert a UTC Unix epoch to local date/time in tz (DST honored).
boolkleidos::timex::isDstActiveAtUtc (uint32_t utcEpoch, const TimeZone &tz)
Whether the zone's DST rule is in effect at a given UTC instant.
WallClockEpochkleidos::timex::wallClockEpoch (rtc::ClockTrust minTrust)
Read the trust-gated wall clock as Unix epoch seconds.
const char *const *kleidos::timex::zoneOffsetLabels ()
The offset labels, one per zone of kZones, in its order.

Variables

constexpr uint32_tkleidos::timex::calendar::kMinValidEpoch
The smallest Unix epoch a clock may hold and count as set.
constexpr int64_tkleidos::timex::calendar::kSecondsPerDay
Seconds in a day.
constexpr const char *kleidos::timex::local::kTzNvsNamespace
NVS namespace holding the timezone preference (the shared device-pref pool).
constexpr const char *kleidos::timex::local::kTzIdxKey
NVS key: selected zone index into kZones (u8; unset ⇒ 0 = UTC).
constexpr const char *kleidos::timex::local::kTzDstKey
NVS key: DST option (bool; unset ⇒ true = DST rules honored).
constexpr uint32_tkleidos::timex::precise::kLightSleepDriftBoundPpm
Worst slow-clock error through a light sleep the budget assumes, ppm.
constexpr uint32_tkleidos::timex::precise::kDriftBudgetMs
constexpr uint64_tkleidos::timex::precise::kMicrosPerMs
Microseconds in one millisecond.
constexpr uint64_tkleidos::timex::precise::kPartsPerMillion
Parts per million.
constexpr uint64_tkleidos::timex::precise::kLightSleepBudgetMicros
Light sleep since the mark that spends kDriftBudgetMs at kLightSleepDriftBoundPpm, microseconds (200 s).
constexpr uint32_tkleidos::timex::rtc::soc::kBackwardJumpMarginSec
How far, in seconds, the clock may step back before it is untrusted.
constexpr autokleidos::timex::kZones
Curated selectable timezones. Index 0 is UTC (the safe default).
constexpr autokleidos::timex::kZoneCount
Number of entries in kZones.

Proleptic-Gregorian civil-calendar core

Howard Hinnant's branch-free days↔civil algorithm, in UTC: exact and time-zone-free.

int64_tkleidos::timex::calendar::daysFromCivil (int32_t year, uint32_t month, uint32_t day)
Days from 1970-01-01 (UTC) to the given proleptic-Gregorian date.
voidkleidos::timex::calendar::civilFromDays (int64_t days, int32_t &yearOut, uint32_t &monthOut, uint32_t &dayOut)
Inverse of daysFromCivil — split a day count into a date.

Back to the top

Enumeration Type Documentation

ClockSource #

enum class kleidos::timex::rtc::ClockSource : uint8_t

Provenance of the most recent clock set (display/diagnostics only).

Enumerator
Unknown 

Never recorded, or a corrupt stored byte.

Manual 

On-device "Set clock" screen commit.

WebAdmin 

Admin-portal time-sync handler.

Gps 

GPS NMEA time sync.

Ntp 

NTP clock sync over a WiFi station link.

ClockTrust #

enum class kleidos::timex::rtc::ClockTrust : uint8_t

Trust ranking of the running wall clock.

SECURITY: this enum ranks how much a consumer may rely on the clock the device is currently keeping, specifically its survival across a power cycle and its resistance to trivial tampering. Higher is stronger; the ordering is meaningful and comparable with the relational operators.

  • None — No clock is running (no RTC backend, or the running clock is unset / integrity-flagged). Time must not be trusted at all.
  • Volatile — A software/internal clock that keeps time while powered but is lost on power-off and offers no tamper resistance.
  • Backed — A battery-backed hardware RTC whose time survives power-off and is the only level suitable for security-relevant timing (e.g. brute-force lockout windows).
Warning
Backed is the maximum by design: only a battery-backed hardware RTC survives power-off and resists tampering. Never introduce a trust level above Backed — nothing on these boards can honestly claim more.
Enumerator
None 

No trustworthy clock is running.

Volatile 

Volatile clock: kept while powered, lost on power-off.

Backed 

Battery-backed hardware RTC: survives power-off.

RtcClockOut #

enum class kleidos::RtcClockOut : uint8_t

CLKOUT pin output frequency.

Enumerator
Off 

CLKOUT disabled (FE = 0).

Hz1 

1 Hz output.

Hz32 

32 Hz output.

Hz1024 

1024 Hz output.

Hz32768 

32768 Hz output.

RtcTimerSource #

enum class kleidos::RtcTimerSource : uint8_t

Countdown-timer source frequency (selects the tick rate the reload value is decremented at).

Enumerator
Hz4096 

4096 Hz source (fine-grained, short intervals).

Hz64 

64 Hz source.

Hz1 

1 Hz source (one tick per second).

Hz1Over60 

1/60 Hz source (one tick per minute).

Back to the top

Function Documentation

alarmNextEpoch() #

uint32_t kleidos::timex::rtc::soc::alarmNextEpoch(uint32_t nowEpoch, const RtcAlarm & alarm)
inline

Next Unix epoch strictly after nowEpoch matching the enabled alarm fields (disabled fields are wildcards).

Hour/minute default to 0 when their field is a wildcard; day-of-month and weekday are matched via a bounded forward day scan.

Parameters
NameDirectionMeaning
nowEpochinCurrent epoch (seconds).
alarminAlarm match specification.
Returns
The next matching epoch, or 0 when no match falls inside the scan window.

alarmTriggered() #

bool kleidos::timex::rtc::alarmTriggered()

Query whether the alarm has fired (AF flag set).

Returns
True when the alarm flag is set; false when it is clear, on bus error, or when no RTC backend is available.

applyEpochToClock() #

void kleidos::timex::rtc::soc::applyEpochToClock(uint32_t epoch)
inline

Set the SoC clock to an epoch.

On the device it writes the SoC RTC through settimeofday. Defined in the !HAS_BM8563_RTC backend translation unit (rtc_hal_soc.cpp). It is a seam rather than a direct call because the same translation unit is compiled for the host, where that syscall sets the clock of the machine running the tests rather than a SoC peripheral.

A host build defines it inline instead and records the epoch in memory, since settimeofday there is the machine's own clock, a global side effect that has repeatedly moved the clock of the machine running the suite. The seed-floor cache, the NVS write and the generation bump are then exercised exactly as on the device with nothing outside the process observing it.

Parameters
NameDirectionMeaning
epochinUnix epoch to apply to the SoC RTC (on a host build, to record in memory).

applyFromStorage() #

void kleidos::timex::local::applyFromStorage()

Boot hook: load the persisted preference and export TZ to libc.

Call once early in setup() (after NVS is usable, before any time display). Conversions would lazy-load anyway; this makes the libc TZ export deterministic from the first frame.

armAlarmWake() #

bool kleidos::timex::rtc::armAlarmWake(const RtcAlarm & alarm)

Program the alarm and arm a deep-sleep pin wake from the RTC INT line.

Writes the alarm via setAlarm, then configures the SoC to wake from deep sleep when the RTC asserts its INT line. The BM8563/PCF8563 INT output is active-low and open-drain, so the wake is armed on a LOW level (enablePinWakeup with wakeOnHigh == false). Only functional on boards where rtcAlarmWakeSupported returns true; elsewhere it writes nothing, not even the alarm, and returns false.

Note
The alarm arrives as a pin wake, so kleidos::platform::sleep::wakeCause() reports WakeCause::Ext0 or WakeCause::Gpio (whichever enablePinWakeup selected) — not WakeCause::Timer. WakeCause::Timer denotes the ESP32's own internal RTC timer, an unrelated source; there is no dedicated RTC-alarm wake cause.
Parameters
NameDirectionMeaning
alarminAlarm match specification (disabled fields are wildcards).
Return values
ValueMeaning
trueAlarm programmed and the pin wake source armed.
falseUnsupported board, or the alarm write / wake config failed.

civilFromDays() #

void kleidos::timex::calendar::civilFromDays(int64_t days, int32_t & yearOut, uint32_t & monthOut, uint32_t & dayOut)
inline

Inverse of daysFromCivil — split a day count into a date.

Parameters
NameDirectionMeaning
daysinSigned day count relative to the Unix epoch day.
yearOutoutReceives the full year.
monthOutoutReceives the month, 1..12.
dayOutoutReceives the day of month, 1..31.

clampWakeMicros() #

uint64_t kleidos::timex::rtc::soc::clampWakeMicros(uint64_t micros)
inline

Clamp a raw wake delay to [kleidos::platform::sleep::kMinTimerWakeUs, kleidos::platform::sleep::kMaxTimerWakeUs], the facade's own bounds.

Parameters
NameDirectionMeaning
microsinRaw wake delay in microseconds.
Returns
The clamped wake delay in microseconds.

clearAlarm() #

bool kleidos::timex::rtc::clearAlarm()

Disarm the alarm interrupt and clear a pending alarm flag.

Returns
True on success; false on bus error or when no RTC backend is available.

clockIntegrityValid() #

bool kleidos::timex::rtc::clockIntegrityValid()

Check whether the RTC still reports valid clock integrity.

The VL (voltage-low) flag latches on power loss; when it is set the calendar contents are unreliable until the clock is re-set.

Returns
True when the clock integrity is intact; false when VL is set or no RTC backend is available.

clockTrust() #

ClockTrust kleidos::timex::rtc::clockTrust()

Report the trust level of the clock this board is currently keeping.

SECURITY: consumers gate security-relevant timing decisions on this value. Only a present, integrity-valid, battery-backed hardware RTC returns ClockTrust::Backed; a volatile internal clock returns ClockTrust::Volatile; an absent or unset/invalid clock returns ClockTrust::None. The SoC clock backend decides it by kleidos::timex::rtc::soc::evaluateTrust; the BM8563 backend by the chip's voltage-low flag.

Returns
The current ClockTrust of the active backend.

computeWakeMicros() #

uint64_t kleidos::timex::rtc::soc::computeWakeMicros(uint32_t nowEpoch, uint32_t targetEpoch)
inline

Compute the clamped LP-timer wake delay from now to a target epoch.

A target at or before now arms the minimum wake — never 0 / underflow.

Parameters
NameDirectionMeaning
nowEpochinCurrent epoch (seconds).
targetEpochinTarget wake epoch (seconds).
Returns
The clamped wake delay in microseconds.

configureClockOut() #

bool kleidos::timex::rtc::configureClockOut(RtcClockOut freq)

Configure the CLKOUT pin output frequency (or disable it).

Parameters
NameDirectionMeaning
freqinDesired CLKOUT frequency, or RtcClockOut::Off to disable.
Returns
True on success; false on bus error or when no RTC backend is available.

countdownToMicros() #

uint64_t kleidos::timex::rtc::soc::countdownToMicros(RtcTimerSource src, uint8_t ticks)
inline

Convert a countdown (source frequency, tick count) to microseconds.

Parameters
NameDirectionMeaning
srcinCountdown source frequency.
ticksinReload value at the source rate; 0 disables (maps to 0).
Returns
The countdown duration in microseconds (0 when ticks is 0).

currentEpoch() #

uint32_t kleidos::timex::rtc::soc::currentEpoch()
inline

The SoC clock's current Unix epoch.

On the device it reads the SoC RTC through gettimeofday. Defined in the !HAS_BM8563_RTC backend translation unit (rtc_hal_soc.cpp). A host build defines it inline instead: the epoch an installed test epoch source returns, else the last one applyEpochToClock recorded in memory.

Returns
The current Unix epoch (seconds, UTC) from the SoC RTC; on a host build the injected epoch, the last applied one, or 0 when neither exists.

dateTimeToEpoch() #

uint32_t kleidos::timex::calendar::dateTimeToEpoch(const RtcDate & date, const RtcTime & time)
inline

Convert a UTC calendar date + time of day to a Unix epoch.

Parameters
NameDirectionMeaning
dateinCalendar date (UTC).
timeinTime of day (UTC).
Returns
Seconds since the Unix epoch (UTC).

daysFromCivil() #

int64_t kleidos::timex::calendar::daysFromCivil(int32_t year, uint32_t month, uint32_t day)
inline

Days from 1970-01-01 (UTC) to the given proleptic-Gregorian date.

Parameters
NameDirectionMeaning
yearinFull year (e.g. 2026); may be negative (proleptic).
monthinMonth, 1..12.
dayinDay of month, 1..31.
Returns
Signed day count relative to the Unix epoch day (negative before it).

debugClockForgotten() #

bool kleidos::timex::rtc::debugClockForgotten()
inline

Whether debugForgetClock is in effect.

Returns
True while the clock is being reported as never set.

debugForgetClock() #

void kleidos::timex::rtc::debugForgetClock()
inline

Debug only: make the clock read as if it had never been set.

A board with a battery-backed RTC cannot be talked out of knowing the time, and a test cannot wait for its cell to die, but several screens exist only for a device whose clock is not set (the TOTP page's empty state, the lock face without its clock, setup's clock step). This latch lets a console reach them: while it is set, clockTrust reports None on every backend, and the next time the clock is set it clears itself.

SECURITY: this only ever lowers trust, so a lockout window can never be shortened by it: the lockout fails closed on an untrusted clock. Compiled only into debug builds, never into a production image.

debugMarkClockLost() #

bool kleidos::timex::rtc::debugMarkClockLost()

Debug only: make the battery-backed RTC report its time lost.

Unlike debugForgetClock, which a reboot forgets, this raises the RTC chip's own integrity flag, as a drained cell does, so every later boot reads the clock as untrusted until the clock is set. The bench's way to reach a lock armed on a battery-backed clock that then lost it.

SECURITY: it only ever lowers trust. Compiled only into debug builds.

Return values
ValueMeaning
trueThe flag was raised (a board with a battery-backed RTC chip).
falseNo such chip, or the write failed.

debugMarkSynced() #

void kleidos::timex::precise::debugMarkSynced()

Debug only: mark the clock's current value as precise, writing nothing.

The console's stand-in for a precise sync, so a test can set a fixed instant (which clears the record) and still reach the screens a code needs.

dowOfCivil() #

uint8_t kleidos::timex::dowOfCivil(int32_t y, uint8_t m, uint8_t d)
constexpr

Day of week for a proleptic-Gregorian date (0=Sun..6=Sat).

Reuses the calendar core in calendar.h — the WS-A weekday expression (daysFromCivil+4)%7 with the C++ remainder made non-negative.

Parameters
NameDirectionMeaning
yinFull year (e.g. 2026).
minMonth, 1..12.
dinDay of month, 1..31.
Returns
Day of week, 0=Sunday .. 6=Saturday.

dstActiveAt() #

bool kleidos::timex::local::dstActiveAt(uint32_t utcEpoch)
nodiscard

Whether DST is in effect at utcEpoch under the active preference.

Parameters
NameDirectionMeaning
utcEpochinUTC Unix epoch (seconds since 1970-01-01).
Returns
True only when the DST option is on and the zone's rule is active.

dstEnabled() #

bool kleidos::timex::local::dstEnabled()
nodiscard

The DST option: honor the zone's DST rule (default ON).

Returns
True when conversions apply the zone's DST rule.

effectiveOffsetMin() [1/2] #

int16_t kleidos::timex::effectiveOffsetMin(const TimeZone & tz, const RtcDate & date, const RtcTime & time)
constexpr

Effective UTC offset (minutes), DST rule always honored.

Parameters
NameDirectionMeaning
tzinThe timezone.
dateinLocal calendar date.
timeinLocal time of day.
Returns
Standard offset plus the DST offset when DST is active.

effectiveOffsetMin() [2/2] #

int16_t kleidos::timex::effectiveOffsetMin(const TimeZone & tz, const RtcDate & date, const RtcTime & time, bool dstEnabled)
constexpr

Effective UTC offset (minutes) for a zone at a given local date/time.

dstEnabled is the user's DST option (default ON): when false the zone behaves as its fixed standard offset and the rule is never evaluated.

Parameters
NameDirectionMeaning
tzinThe timezone.
dateinLocal calendar date.
timeinLocal time of day.
dstEnabledinHonor the zone's DST rule (false ⇒ fixed offset).
Returns
Standard offset plus the DST offset when DST is enabled and active.

epochToDateTime() #

DateTime kleidos::timex::calendar::epochToDateTime(uint32_t unixEpoch)
inline

Convert a Unix epoch (UTC seconds since 1970-01-01) to date + time.

Parameters
NameDirectionMeaning
unixEpochinSeconds since the Unix epoch (UTC).
Returns
The calendar date and time of day.

evaluateTrust() #

TrustEvaluation kleidos::timex::rtc::soc::evaluateTrust(uint32_t floorEpoch, uint32_t derivedNow, bool coldBoot, bool wasEverSet)
inline

Evaluate the running clock's trust and effective epoch.

SECURITY: this is the SoC clock's equivalent of the BM8563 voltage-low flag. A never-set clock, a cold start (power-on reset), or a backward jump beyond the drift margin (time tamper) all yield None; the lockout (Task 3) fails closed on anything below Backed. A seeded, clean-booted, forward/equal clock is Volatile. The returned effectiveEpoch is floored up to the last known floor so a caller that opts to use it never sees wall-clock time run backward; it is a convenience output only — the wired rtc::getTime / rtc::getDate return the raw reading and do not apply this floor, and no security decision depends on it (the lockout uses a separate monotonic source, not this wall clock).

Parameters
NameDirectionMeaning
floorEpochinPersisted NVS floor (last known good epoch), 0 if none.
derivedNowinRTC-derived current epoch.
coldBootinTrue on a power-on reset with no fresh set this session.
wasEverSetinTrue once the clock has ever been seeded/set.
Returns
The clock trust and the monotonic-floored effective epoch.

fresh() #

bool kleidos::timex::precise::fresh()
nodiscard

Whether the clock still holds a precise time.

Return values
ValueMeaning
trueA precise write was marked this boot, no clock write followed, and the light sleep since is within kLightSleepBudgetMicros.
falseOtherwise.

getDate() #

RtcDate kleidos::timex::rtc::getDate()

Read current date from the RTC.

Returns
Current calendar date from the hardware clock.

getDateTime() #

void kleidos::timex::rtc::getDateTime(RtcDate & date, RtcTime & time)

Read date and time as one coherent single-instant snapshot.

Unlike a getDate + getTime pair — two independent backend reads that can straddle a second/midnight rollover in the sub-second window between them — both outputs here come from the same instant: the internal backend derives them from a single gettimeofday, and the BM8563 backend reads all seven time/date registers in one I2C burst (the PCF8563-class chip latches the counters for the duration of a sequential read).

On a backend read failure both outputs are zero-filled (matching the getTime / getDate failure behavior).

Parameters
NameDirectionMeaning
dateoutReceives the calendar date (UTC).
timeoutReceives the time of day (UTC).

getTime() #

RtcTime kleidos::timex::rtc::getTime()

Read current time from the RTC.

Returns
Current time-of-day from the hardware clock.

getValidTime() #

bool kleidos::timex::rtc::getValidTime(RtcDate & date, RtcTime & time, ClockTrust minTrust)
inline

Read the clock only when it meets a minimum trust level.

SECURITY: a single trust gate for consumers that must not act on an untrustworthy clock. The output is filled and true returned only when the running clock is present and at least as trusted as minTrust, i.e. clockTrust() != None and clockTrust() >= minTrust. A board with clockTrust() == None therefore never yields a valid time, regardless of minTrust. On failure date and time are left untouched.

Backend-agnostic by construction: it derives its answer purely from clockTrust and getDateTime, so both the hardware and the fallback backends share this one definition. The read goes through getDateTime, so on success date and time are guaranteed to describe the same instant — they can never straddle a second/midnight rollover the way an independent getDate() + getTime() pair could.

Parameters
NameDirectionMeaning
dateoutReceives the calendar date on success; untouched on failure.
timeoutReceives the time of day on success; untouched on failure.
minTrustinMinimum trust the running clock must meet.
Return values
ValueMeaning
trueThe clock met minTrust; date and time were filled.
falseThe clock was absent or below minTrust; outputs untouched.

invalidate() #

void kleidos::timex::precise::invalidate()

Clear the record: the clock is about to be written.

Every clock write calls this first, before the clock moves, in both rtc:: backends. Also the console's way to drop a sync.

isAvailable() #

bool kleidos::timex::rtc::isAvailable()

Check if a usable clock is available on this board.

Shim over clockTrust — a clock is available when the running clock is anything other than ClockTrust::None. Callers that need to distinguish a power-off-surviving hardware clock from a volatile one must inspect clockTrust directly.

Return values
ValueMeaning
trueclockTrust returns Volatile or Backed.
falseclockTrust returns None (no/absent/unset clock).

isDstActive() #

bool kleidos::timex::isDstActive(const TimeZone & tz, const RtcDate & date, const RtcTime & time)
constexpr

Whether DST is active for a zone at a given local date/time.

Resolves the rule from the entered local instant alone: builds the concrete start/end days for date's year, forms comparable (month, day, hour) keys, and compares. Northern rules (start month < end month) are active on start <= now < end; southern rules (start month > end month, DST wraps the new year) are active on now >= start || now < end.

Local-anchored transition approximation (deliberate)
The rule hours are compared against the local wall clock on both sides of a transition, while real-world rules may anchor elsewhere (the EU rule fires at 01:00 UTC, i.e. at a different wall hour in each member zone). Within the one-hour window around each of the two yearly transitions this engine can therefore flip up to 1–2 hours away from the legal instant; everywhere else in the year it is exact. The trade is deliberate: the decision needs no UTC pre-pass and stays self-consistent in both conversion directions (localToUtcEpoch / utcEpochToLocal).

Inside the window the behavior is a plain half-open key comparison, pinned by the host tests: a local instant at/after the rule hour takes the post-transition offset. A local time in the spring-forward gap (the skipped wall hour) therefore resolves via the DST offset, and a fall-back ambiguous time (the repeated wall hour) resolves via the standard offset — i.e. its second, post-transition occurrence.

Parameters
NameDirectionMeaning
tzinThe timezone (its dst rule drives the decision).
dateinLocal calendar date.
timeinLocal time of day.
Returns
True when DST is in effect at that local instant.

isDstActiveAtUtc() #

bool kleidos::timex::isDstActiveAtUtc(uint32_t utcEpoch, const TimeZone & tz)
inline

Whether the zone's DST rule is in effect at a given UTC instant.

Resolves the rule against the standard-offset-shifted local instant (the same first pass utcEpochToLocal uses), so the answer is consistent with the conversion functions. Approximate within the one-hour transition window like the rest of the engine.

Parameters
NameDirectionMeaning
utcEpochinUTC Unix epoch (seconds since 1970-01-01).
tzinThe timezone whose rule is evaluated.
Returns
True when DST is in effect at that instant.

localNow() #

bool kleidos::timex::local::localNow(LocalDateTime & out, rtc::ClockTrust minTrust)
nodiscard

Trust-gated "local now": read the clock and convert in one step.

Reads the RTC through rtc::getValidTime at minTrust (the RTC stores UTC) and converts to the active zone. On failure out is untouched.

Parameters
NameDirectionMeaning
outoutReceives the local date/time on success.
minTrustinMinimum trust the running clock must meet.
Return values
ValueMeaning
trueThe clock met minTrust; out holds local time.
falseThe clock was absent or below minTrust.

localToUtcEpoch() [1/2] #

uint32_t kleidos::timex::localToUtcEpoch(const RtcDate & date, const RtcTime & time, const TimeZone & tz)
constexpr

Convert a local date/time in tz to a UTC Unix epoch (DST honored).

Parameters
NameDirectionMeaning
dateinLocal calendar date.
timeinLocal time of day.
tzinThe timezone the local instant is expressed in.
Returns
The corresponding UTC Unix epoch (seconds since 1970-01-01).

localToUtcEpoch() [2/2] #

uint32_t kleidos::timex::localToUtcEpoch(const RtcDate & date, const RtcTime & time, const TimeZone & tz, bool dstEnabled)
constexpr

Convert a local date/time in tz to a UTC Unix epoch.

dateTimeToEpoch treats its fields as UTC; subtracting the (DST-aware, possibly negative) local→UTC offset yields the true UTC epoch. Signed math is used throughout; the result is returned as a uint32_t epoch.

Parameters
NameDirectionMeaning
dateinLocal calendar date.
timeinLocal time of day.
tzinThe timezone the local instant is expressed in.
dstEnabledinHonor the zone's DST rule (false ⇒ fixed offset).
Returns
The corresponding UTC Unix epoch (seconds since 1970-01-01).

markSynced() #

void kleidos::timex::precise::markSynced(uint32_t generationBeforeWrite)

Mark the clock write made after generationBeforeWrite as precise.

Call right after the clock write, with what writeGeneration returned just before it. The mark holds while that write stays the last one: a write that raced it, or any later one, leaves the record clear.

Parameters
NameMeaning
generationBeforeWritewriteGeneration read before the write.

nthWeekdayDom() #

uint8_t kleidos::timex::nthWeekdayDom(int32_t year, uint8_t month, uint8_t week, uint8_t dow)
constexpr

Day-of-month of the week-th dow in month of year.

Parameters
NameDirectionMeaning
yearinFull year (e.g. 2026).
monthinMonth, 1..12.
weekinOrdinal week, 1..4, or 5 for "last".
dowinTarget weekday, 0=Sun..6=Sat.
Returns
The matching day of month, 1..31.

posixTz() #

const char * kleidos::timex::local::posixTz()
nodiscard

The POSIX TZ string currently in effect (DST-rule or fixed variant).

Returns
zone().posixDst when the DST option is on, else zone().posixStd.

readAlarm() #

bool kleidos::timex::rtc::readAlarm(RtcAlarm & alarm)

Read back the currently programmed alarm.

Parameters
NameDirectionMeaning
alarmoutReceives the decoded alarm on success.
Returns
True on success; false on bus error or when no RTC backend is available.

readClockOut() #

bool kleidos::timex::rtc::readClockOut(RtcClockOut & freq)

Read the current CLKOUT pin configuration.

Parameters
NameDirectionMeaning
freqoutReceives the decoded CLKOUT frequency (Off when disabled).
Returns
True on success; false on bus error or when no RTC backend is available.

readCountdownTimerRunning() #

bool kleidos::timex::rtc::readCountdownTimerRunning(bool & running)

Query whether the countdown timer is currently armed.

Parameters
NameDirectionMeaning
runningoutSet true when the timer-enable (TE) bit is set.
Returns
True on success; false on bus error or when no RTC backend is available.

rtcAlarmWakeSupported() #

bool kleidos::timex::rtc::rtcAlarmWakeSupported()

Report whether this board can wake from deep sleep on an RTC alarm.

True only where the variant names the GPIO that reads the RTC INT line (RTC_INT_PIN), a real RTC backend is present (HAS_BM8563_RTC) and that GPIO can wake a deep sleep (sleep::pinWakesDeepSleep). The CoreInk names GPIO19, which is no RTC GPIO, so it answers false there too. On a variant with no RTC_INT_PIN this is false and no pin is referenced.

Return values
ValueMeaning
truearmAlarmWake can arm a deep-sleep wake on this board.
falseNo GPIO that can wake a deep sleep reads RTC INT here; armAlarmWake refuses.

setAlarm() #

bool kleidos::timex::rtc::setAlarm(const RtcAlarm & alarm)

Program the alarm and arm the alarm interrupt.

Parameters
NameDirectionMeaning
alarminAlarm match specification (disabled fields are wildcards).
Returns
True when the alarm was written and armed; false on bus error or when no RTC backend is available.

setCountdownTimer() #

bool kleidos::timex::rtc::setCountdownTimer(RtcTimerSource src, uint8_t ticks)

Arm the countdown timer with a reload value and source frequency.

Parameters
NameDirectionMeaning
srcinCountdown source frequency.
ticksinReload value decremented at the source rate (0 disables).
Returns
True when the timer was programmed and armed; false on bus error or when no RTC backend is available.

setDate() #

void kleidos::timex::rtc::setDate(const RtcDate & d)

Write the calendar date to this board's clock, RTC chip or SoC timer.

Clears the precise-sync record first (precise_sync.h). Prefer setDateTime when the time is known too.

Parameters
NameDirectionMeaning
dinDate value to write to the hardware clock.

setDateTime() #

void kleidos::timex::rtc::setDateTime(const RtcDate & d, const RtcTime & t)

Set the RTC date and time as one combined instant (atomic facade write).

Preferred over a setDate + setTime pair when both halves of an instant are known: the backend applies the combined instant in a single operation, so the write can never be observed half-applied and the cost is paid once. On the internal-RTC backend this is one settimeofday + one NVS floor write (a setDate + setTime pair pays two of each); on the BM8563 backend it is one sequential I2C burst over all seven time/date registers (the PCF8563-class register file supports a single auto-incrementing write from the seconds register).

Parameters
NameDirectionMeaning
dinDate value to write to the hardware clock (UTC).
tinTime value to write to the hardware clock (UTC).

setDstEnabled() #

bool kleidos::timex::local::setDstEnabled(bool enabled)
nodiscard

Set the DST option: persist, cache, re-export the TZ string in effect.

Parameters
NameDirectionMeaning
enabledinTrue to honor DST rules; false for fixed standard offsets.
Return values
ValueMeaning
trueThe option is active and stored.
falseIt is active in RAM only and reverts at the next boot.

setTime() #

void kleidos::timex::rtc::setTime(const RtcTime & t)

Write the time of day to this board's clock, RTC chip or SoC timer.

Clears the precise-sync record first (precise_sync.h). Prefer setDateTime when the date is known too.

Parameters
NameDirectionMeaning
tinTime value to write to the hardware clock.

setZoneIdx() #

bool kleidos::timex::local::setZoneIdx(uint8_t idx)
nodiscard

Select a zone by table index: validate, persist, cache, re-export TZ.

Parameters
NameDirectionMeaning
idxinIndex into kZones.
Return values
ValueMeaning
trueThe index was valid and the preference is active and stored.
falseidx >= kZoneCount (nothing changed), or the zone is active in RAM but was not stored — the clock reads right now and reverts at the next boot, which a surface must not report as saved.

status() #

Status kleidos::timex::precise::status()
nodiscard

The record, for the console.

Returns
A snapshot; the figures since the mark are 0 while everMarked is false.

stopCountdownTimer() #

bool kleidos::timex::rtc::stopCountdownTimer()

Stop the countdown timer and clear its interrupt enable and flag.

Returns
True on success; false on bus error or when no RTC backend is available.

toLocal() #

LocalDateTime kleidos::timex::local::toLocal(uint32_t utcEpoch)
nodiscard

Convert a UTC epoch to local date/time in the active zone.

Honors the DST option (dstEnabled). Display-only — never feed the result back into epoch math.

Parameters
NameDirectionMeaning
utcEpochinUTC Unix epoch (seconds since 1970-01-01).
Returns
The local calendar date and time of day.

toUtc() #

uint32_t kleidos::timex::local::toUtc(const RtcDate & date, const RtcTime & time)
nodiscard

Convert a local date/time in the active zone to a UTC epoch.

Honors the DST option (dstEnabled). The inverse edit-boundary conversion for screens where the user types local wall time.

Parameters
NameDirectionMeaning
dateinLocal calendar date.
timeinLocal time of day.
Returns
The corresponding UTC Unix epoch (seconds since 1970-01-01).

transitionKey() #

int32_t kleidos::timex::transitionKey(uint8_t month, uint8_t day, uint8_t hour)
constexpr

Pack a (month, day, hour) triple into a monotonically comparable key.

Parameters
NameDirectionMeaning
monthinMonth, 1..12.
dayinDay of month, 1..31.
hourinHour of day, 0..23.
Returns
A single integer that orders instants within a year.

utcEpochToLocal() [1/2] #

LocalDateTime kleidos::timex::utcEpochToLocal(uint32_t utcEpoch, const TimeZone & tz)
inline

Convert a UTC Unix epoch to local date/time in tz (DST honored).

Parameters
NameDirectionMeaning
utcEpochinUTC Unix epoch (seconds since 1970-01-01).
tzinThe target timezone.
Returns
The local calendar date and time of day.

utcEpochToLocal() [2/2] #

LocalDateTime kleidos::timex::utcEpochToLocal(uint32_t utcEpoch, const TimeZone & tz, bool dstEnabled)
inline

Convert a UTC Unix epoch to local date/time in tz.

The effective offset itself depends on the local instant near a transition, so the offset is first computed from the standard-offset-shifted instant and then applied. One iteration is sufficient for civil use; results within the one-hour transition window are approximate.

Parameters
NameDirectionMeaning
utcEpochinUTC Unix epoch (seconds since 1970-01-01).
tzinThe target timezone.
dstEnabledinHonor the zone's DST rule (false ⇒ fixed offset).
Returns
The local calendar date and time of day.

wallClockEpoch() #

WallClockEpoch kleidos::timex::wallClockEpoch(rtc::ClockTrust minTrust)
inline

Read the trust-gated wall clock as Unix epoch seconds.

Reads the clock once via rtc::getValidTime at minTrust and, on success, converts the UTC calendar reading to Unix epoch seconds via calendar::dateTimeToEpoch (exact UTC conversion — no libc time-zone dependence). On failure (clock absent or below minTrust) the conversion is skipped.

Parameters
NameDirectionMeaning
minTrustinMinimum trust the running clock must meet.
Returns
{epoch, true} when the clock met minTrust; {0, false} otherwise — the caller must not persist a stamp on a false result.

writeGeneration() #

uint32_t kleidos::timex::precise::writeGeneration()
nodiscard

The clock-write count, to read before a precise write.

Every clock write bumps it (invalidate). A precise writer reads it just before its own write and hands it to markSynced after.

Returns
The count of clock writes this boot.

zone() #

const TimeZone & kleidos::timex::local::zone()
nodiscard

The selected TimeZone entry (shorthand for kZones[zoneIdx()]).

Returns
Reference to the active zone-table entry.

zoneIdx() #

uint8_t kleidos::timex::local::zoneIdx()
nodiscard

The selected zone index into kZones (clamped; 0 = UTC default).

Returns
The cached (lazily NVS-loaded) zone index, always < kZoneCount.

zoneOffsetLabels() #

const char *const * kleidos::timex::zoneOffsetLabels()

The offset labels, one per zone of kZones, in its order.

Returns
kZoneCount pointers to "UTC+HH:MM" strings; valid for the program's lifetime.

Back to the top

Variable Documentation

kBackwardJumpMarginSec #

uint32_t kleidos::timex::rtc::soc::kBackwardJumpMarginSec
inlineconstexpr

How far, in seconds, the clock may step back before it is untrusted.

A lower "now" within this margin is benign RC-oscillator drift on a clean wake; a larger step back is treated as time tamper.

kDriftBudgetMs #

uint32_t kleidos::timex::precise::kDriftBudgetMs
inlineconstexpr

How far the clock may move from the precise time before it no longer counts as precise, milliseconds.

kLightSleepDriftBoundPpm #

uint32_t kleidos::timex::precise::kLightSleepDriftBoundPpm
inlineconstexpr

Worst slow-clock error through a light sleep the budget assumes, ppm.

Measured on the three boards without an RTC chip, on the RC_FAST/256 slow clock with ESP-IDF's own calibration: -6033 to +2300 ppm over 66 sleeps of 1 minute to 3 hours (deep sleeps, light sleeps with the crystal off and on, sleeps right after a 10-minute load at 240 MHz), the sign shifting with the crystal and the die temperature. The bound rounds the worst case up, with room for temperature.

kMinValidEpoch #

uint32_t kleidos::timex::calendar::kMinValidEpoch
inlineconstexpr

The smallest Unix epoch a clock may hold and count as set.

2001-09-09T01:46:40Z, the smallest valid persisted seed. It matches the admin portal's set-time request check (epoch >= 1e9), so a zero/garbage NVS value never counts as "clock was set".

kZones #

auto kleidos::timex::kZones
inlineconstexpr

Curated selectable timezones. Index 0 is UTC (the safe default).

Warning
APPEND-ONLY: the selected zone persists in NVS as an index into this table, so entries must never be reordered or removed — new zones go at the end. Every UTC whole-hour offset from -12 to +14 is covered by at least one entry.

Back to the top