Kleidos API Search

In development. It changes without notice.

Topic

Power, Sleep & System Control

Deep and light sleep and what ends them, the CPU clock, the slow clock that counts through a sleep, and the record of a crash.

Deep sleep does not return: the chip starts again when it wakes. One key can end it, or several as one set under one condition. A line that nothing else holds high while its key is released gets its pull-up for the length of the sleep. On the ESP32-S3 the USB pads are isolated first, so a cable left in does not feed the chip through them.

Light sleep of a fixed time returns to its caller. The automatic one, between two ticks with nothing to do, is ESP-IDF's, on the boards that build it.

The CPU clock has one function that changes it. A job that needs the full speed, such as a key derivation, holds it for as long as it runs. On the ESP32 the two ranges of clocks (80 and 160 MHz, or 240 MHz) need different settings of the circuit that also feeds the radios, so while Wi-Fi or Bluetooth is up a change stays in the range in force: 240 MHz asked from 80 or 160 gives 160. Before a radio starts, the clock is brought to its base. The ESP32-S3 has no such limit.

The slow clock counts the time of a sleep where there is no clock chip. Its readings are raw here; what they mean is decided in Clock & Time Zone.

The crash record keeps, in memory that outlives a restart, where the firmware was when it failed, and none of what it held.

See also
Power, Battery & Parking, RTOS Facade, Clock & Time Zone

Files

file src/platform/power/boot_wake_logic.h
How the current boot started, read once and kept for the whole boot, with no ESP-IDF in it.
file src/platform/power/cpu_boost.h
The base core clock of the boards, the RAII guard that temporarily boosts the CPU to its maximum frequency for crypto, and the one that raises it to the frame clock while a heavy frame is drawn.
file src/platform/power/cpu_pll.h
Which core clock a classic ESP32 may move to while a radio is up.
file src/platform/power/crash_record.cpp
Panic-time capture, RTC ring and NVS mirror for the crash record.
file src/platform/power/crash_record.h
Address-only crash ring that survives a reboot.
file src/platform/power/crash_reset_logic.h
Which watchdog reset is a power-up the crash ring must not record, with no ESP-IDF in it.
file src/platform/power/light_sleep.cpp
Automatic light sleep: the hold, the idle wait and the wake pins.
file src/platform/power/light_sleep.h
Automatic light sleep: the application's hold on it, the idle wait that lets go of the hold, and the pins that end the wait.
file src/platform/power/sleep.cpp
Deep-sleep entry and wake-source configuration implementation.
file src/platform/power/sleep.h
Deep-sleep entry and wake-source configuration facade.
file src/platform/power/sleep_count.cpp
The slow-clock sleep record declared in sleep.h.
file src/platform/power/slow_clock.cpp
RTC slow-clock facade implementation.
file src/platform/power/slow_clock.h
The SoC's RTC slow clock: its source, raw ticks, calibration, the period ESP-IDF takes into a deep sleep, and the regulator operating point it runs at.
file src/platform/power/system.cpp
System-control implementation: CPU clock, heap, MAC, restart.
file src/platform/power/system.h
System-control facade: CPU clock, heap stats, image/MAC info, restart.
file src/platform/power/timer_wake_logic.h
The deep-sleep timer wake's shared record and arithmetic, with no ESP-IDF in it.
file src/platform/power/usb_pad_sleep.h
Which USB PHY pads a deep sleep may isolate, and why.
file src/platform/power/wake_cause.h
The deep-sleep wake causes the sleep facade reports.

Namespaces

namespace kleidos::platform::cpu_boost
The one boost that outlives the scope which raised it.

Classes

struct kleidos::platform::sleep::WakeReading
What the chip says about the start of the current boot, read at one moment. More about kleidos::platform::sleep::WakeReading
struct kleidos::platform::sleep::BootWake
How the current boot started. More about kleidos::platform::sleep::BootWake
class kleidos::platform::sleep::BootWakeLatch
The current boot's start, from the first reading taken. More about kleidos::platform::sleep::BootWakeLatch
class kleidos::platform::CpuBoostGuard
RAII guard: boost the CPU to ::kCpuBoostMhz, restore on destruction. More about kleidos::platform::CpuBoostGuard
class kleidos::platform::FrameBoostGuard
RAII guard: hold the core at least at ::kCpuFrameMhz while a heavy frame is drawn. More about kleidos::platform::FrameBoostGuard
class kleidos::platform::MaxClockGuard
RAII guard: hold the core at ::kCpuBoostMhz for a whole phase, across the FSM transitions inside it. More about kleidos::platform::MaxClockGuard
struct kleidos::platform::system::CpuClockSource
A core clock and the PLL setting it is divided from. More about kleidos::platform::system::CpuClockSource
struct kleidos::platform::crash_record::Frame
One captured call frame: a program counter and a stack pointer, nothing else. More about kleidos::platform::crash_record::Frame
struct kleidos::platform::crash_record::Firmware
Which firmware image produced a record. More about kleidos::platform::crash_record::Firmware
struct kleidos::platform::crash_record::Record
One retained crash. More about kleidos::platform::crash_record::Record
struct kleidos::platform::light_sleep::Stats
Idle-wait counters since boot. More about kleidos::platform::light_sleep::Stats
struct kleidos::platform::slow_clock::EntryRecord
What the deep-sleep hook recorded as the last deep sleep began. More about kleidos::platform::slow_clock::EntryRecord
struct kleidos::platform::slow_clock::OperatingPoint
The regulator operating point the slow clock runs at (ESP32-S3 only). More about kleidos::platform::slow_clock::OperatingPoint
struct kleidos::platform::system::ChipInfo
Read-only SoC identity snapshot (silicon model, cores, revision, radios). More about kleidos::platform::system::ChipInfo
struct kleidos::platform::system::FirmwareInfo
Identity of the running application image, as baked into it at link time. More about kleidos::platform::system::FirmwareInfo
struct kleidos::platform::system::HeapStats
Per-region heap accounting snapshot (leak / fragmentation monitoring). More about kleidos::platform::system::HeapStats
struct kleidos::platform::system::ClockInfo
Read-only clock-source snapshot (CPU / APB / crystal frequencies). More about kleidos::platform::system::ClockInfo
struct kleidos::platform::system::PartitionInfo
Read-only descriptor for one flash partition-table entry (see partitionCount). More about kleidos::platform::system::PartitionInfo
struct kleidos::platform::sleep::TimerWakeAtSleep
What a deep sleep does with ESP-IDF's timer wake source. More about kleidos::platform::sleep::TimerWakeAtSleep
class kleidos::platform::sleep::TimerWakeRecord
The timer wake every caller of the sleep facade shares. More about kleidos::platform::sleep::TimerWakeRecord

Typedefs

usingkleidos::platform::system::TextSink
Receiver of text that a statistics dump writes piece by piece.

Enumerations

enum class kleidos::platform::crash_record::Reason : uint8_t { kleidos::platform::crash_record::Reason::Unknown, kleidos::platform::crash_record::Reason::Fault, kleidos::platform::crash_record::Reason::Abort, kleidos::platform::crash_record::Reason::IntWdt, kleidos::platform::crash_record::Reason::TaskWdt, kleidos::platform::crash_record::Reason::Wdt, kleidos::platform::crash_record::Reason::Brownout }
enum class kleidos::platform::light_sleep::WaitEnd : uint8_t { kleidos::platform::light_sleep::WaitEnd::Timeout , kleidos::platform::light_sleep::WaitEnd::WakePin , kleidos::platform::light_sleep::WaitEnd::PinAlreadyActive , kleidos::platform::light_sleep::WaitEnd::NotBuilt }
Why an idle wait ended. More about kleidos::platform::light_sleep::WaitEnd
enum class kleidos::platform::sleep::Ext1Mode : uint8_t { kleidos::platform::sleep::Ext1Mode::AnyLow , kleidos::platform::sleep::Ext1Mode::AllLow , kleidos::platform::sleep::Ext1Mode::AnyHigh }
enum class kleidos::platform::system::MacAddressKind : uint8_t { kleidos::platform::system::MacAddressKind::WifiStation , kleidos::platform::system::MacAddressKind::WifiSoftAp , kleidos::platform::system::MacAddressKind::Bluetooth }
Which interface MAC address to read. More about kleidos::platform::system::MacAddressKind
enum class kleidos::platform::sleep::UsbPadAction : uint8_t { kleidos::platform::sleep::UsbPadAction::Isolate , kleidos::platform::sleep::UsbPadAction::KeptAsWakePin , kleidos::platform::sleep::UsbPadAction::KeptAsHeldPad , kleidos::platform::sleep::UsbPadAction::NoSuchPad }
What a deep sleep does with one USB PHY pad, and the reason. More about kleidos::platform::sleep::UsbPadAction
enum class kleidos::platform::sleep::WakeCause : uint8_t { kleidos::platform::sleep::WakeCause::Undefined, kleidos::platform::sleep::WakeCause::Ext0, kleidos::platform::sleep::WakeCause::Ext1, kleidos::platform::sleep::WakeCause::Timer, kleidos::platform::sleep::WakeCause::Touchpad, kleidos::platform::sleep::WakeCause::Ulp, kleidos::platform::sleep::WakeCause::Gpio, kleidos::platform::sleep::WakeCause::Uart, kleidos::platform::sleep::WakeCause::Wifi, kleidos::platform::sleep::WakeCause::CoProcessor, kleidos::platform::sleep::WakeCause::Other }

Functions

constexpr BootWakekleidos::platform::sleep::bootWakeOf (const WakeReading &reading)
The boot one reading describes.
constexpr uint32_tkleidos::platform::clockWithFloorMhz (uint32_t askedMhz, uint32_t floorMhz)
The clock to apply for a request under a floor.
constexpr uint32_tkleidos::platform::clockWithFrameHoldMhz (uint32_t askedMhz, bool frameHeld)
The clock to apply for a request while a frame hold may be in force.
boolkleidos::platform::cpu_boost::held ()
Whether a boost is currently latched past its raising scope.
voidkleidos::platform::cpu_boost::hold (uint32_t restoreMhz)
Latch the boost, remembering the frequency the restore must return to.
uint32_tkleidos::platform::cpu_boost::pendingRestoreMhz ()
Frequency a held latch owes a restore to.
uint32_tkleidos::platform::cpu_boost::heldForMs ()
How long the current latch has been held.
uint32_tkleidos::platform::cpu_boost::currentMhz ()
Current core clock, for callers that report rather than set it.
voidkleidos::platform::cpu_boost::release ()
Drop the latch and restore the frequency it captured. Idempotent.
voidkleidos::platform::cpu_boost::discard ()
uint32_tkleidos::platform::cpu_boost::expireIfStale ()
Take down a latch that has outlived ::kCpuBoostMaxHoldMs.
constexpr uint32_tkleidos::platform::system::clockUnderRadioMhz (CpuClockSource running, CpuClockSource asked, bool radioUp)
The core clock to apply for a request, given whether a radio is up.
constexpr uint32_tkleidos::platform::system::clockBeforeRadioMhz (CpuClockSource running, CpuClockSource base)
The core clock to move to before a radio comes up.
boolkleidos::platform::crash_record::begin ()
Adopt the RTC ring, reconcile it with this boot, and mirror it to NVS.
uint32_tkleidos::platform::crash_record::crashCount ()
Total number of crashes recorded since the ring was last cleared.
uint32_tkleidos::platform::crash_record::recordCount ()
Number of records currently retained.
boolkleidos::platform::crash_record::recordAt (uint32_t index, Record &out)
Read one retained record, oldest first.
uint32_tkleidos::platform::crash_record::bootSequence ()
Ordinal of the current boot.
Firmwarekleidos::platform::crash_record::runningFirmware ()
Identity of the image that adopted the ring on this boot.
const char *kleidos::platform::crash_record::reasonName (Reason reason)
Stable lowercase token for reason ("fault", "abort", "task_wdt", ...).
voidkleidos::platform::crash_record::clear ()
Drop every retained record, in RTC and in the NVS mirror.
boolkleidos::platform::crash_record::eraseCoreDumpPartition ()
Erase the core dump partition, where the partition table has one.
constexpr boolkleidos::platform::crash_record::powerUpReportedAsWatchdog (bool rtcRetained, uint32_t socResetCode)
Whether a watchdog reset is a power-up the chip reported as one.
boolkleidos::platform::light_sleep::built ()
Whether this build carries automatic light sleep.
boolkleidos::platform::light_sleep::begin ()
Create the hold and take it. Idempotent.
boolkleidos::platform::light_sleep::addWakePin (int pin)
Register an active-low GPIO that ends an idle wait.
WaitEndkleidos::platform::light_sleep::idleWait (uint32_t timeoutMs, uint32_t activeFallbackMs)
Wait out an idle stretch, letting the chip light-sleep through it where the build can.
boolkleidos::platform::light_sleep::usbHostAttached ()
Whether a USB host is attached to the chip's own USB port.
boolkleidos::platform::light_sleep::waiting ()
Whether an idle wait is in progress (on a light-sleep build, the hold is let go).
Statskleidos::platform::light_sleep::stats ()
The idle-wait counters since boot.
constexpr uint64_tkleidos::platform::sleep::ext1PinMask (std::span< const int > gpioPins)
GPIO bit mask of a wake-pin list, in the form the EXT1 hardware takes.
boolkleidos::platform::sleep::lightSleepFor (uint64_t microseconds, bool keepCrystalOn)
Light-sleep the SoC for a fixed time and return when the timer ends it.
voidkleidos::platform::sleep::deepSleepStart ()
Enter deep sleep immediately; never returns (the SoC resets on wake).
const char *kleidos::platform::slow_clock::sourceName ()
Short name of the oscillator the RTC slow clock runs from.
uint32_tkleidos::platform::slow_clock::configuredCycles ()
Slow cycles ESP-IDF's startup calibration counts, as built.
uint64_tkleidos::platform::slow_clock::ticks ()
Raw RTC slow-clock ticks.
uint32_tkleidos::platform::slow_clock::period ()
The period ESP-IDF converts slow ticks at, now.
uint32_tkleidos::platform::slow_clock::measure (uint32_t cycles)
Measure the slow-clock period now, against the crystal.
uint64_tkleidos::platform::slow_clock::armedWakeTicks ()
The tick the sleep timer was last armed to fire at.
boolkleidos::platform::slow_clock::installEntryRecorder ()
Register the deep-sleep hook that records EntryRecord.
EntryRecordkleidos::platform::slow_clock::lastEntry ()
The record of the last deep sleep the hook saw begin.
OperatingPointkleidos::platform::slow_clock::operatingPoint ()
Read the regulator operating point.
boolkleidos::platform::slow_clock::measureAtRtcCode (uint8_t code, uint32_t cycles, uint32_t &result)
Measure the slow-clock period with the RTC regulator raised to code.
voidkleidos::platform::system::restart ()
Restart the device immediately (aborts on host); never returns.
voidkleidos::platform::system::abortWithReason (const char *reason)
Stop on a broken invariant, with reason printed in the panic report.
const char *kleidos::platform::system::resetReason ()
A stable, human-readable name for the last reset reason.
uint32_tkleidos::platform::system::socResetCode ()
The SoC's own reset code for the PRO CPU, before ESP-IDF maps it.
boolkleidos::platform::system::resetByPowerOn ()
Whether the last reset was a power-on: the supply came up.
constexpr uint64_tkleidos::platform::sleep::timerWakeDeadline (uint64_t nowUs, uint64_t delayUs)
The deadline of a timer wake asked for delayUs after nowUs.
constexpr uint64_tkleidos::platform::sleep::timerWakeRemainingUs (uint64_t deadlineUs, uint64_t nowUs)
Microseconds from nowUs to a deadline.
constexpr TimerWakeAtSleepkleidos::platform::sleep::timerWakeAtSleep (uint64_t deadlineUs, uint64_t benchAfterUs, uint64_t nowUs)
The timer wake of a deep sleep that starts at nowUs.
constexpr boolkleidos::platform::sleep::padListed (int pad, std::span< const int > pads)
Whether a pad number appears in a pin list.
constexpr UsbPadActionkleidos::platform::sleep::usbPadAction (int pad, std::span< const int > wakePins, std::span< const int > heldPads)
Decide what a deep sleep does with one USB PHY pad.
constexpr boolkleidos::platform::sleep::isolates (UsbPadAction action)
Whether an action actually touches the pad.
constexpr const char *kleidos::platform::sleep::usbPadActionName (UsbPadAction action)
A short name for an action, for a log line or a console reply.

Variables

constexpr uint32_tkleidos::platform::kCpuBaseMhz
constexpr uint32_tkleidos::platform::kCpuBoostMhz
Boost target for CPU-bound crypto bursts (both supported SoCs top out here).
constexpr uint32_tkleidos::platform::kCpuFrameMhz
constexpr uint32_tkleidos::platform::kCpuIdleFloorMhz
constexpr uint32_tkleidos::platform::kCpuBoostMaxHoldMs
constexpr uint32_tkleidos::platform::system::kNotPllSourced
constexpr uint32_tkleidos::platform::system::kPllTopCpuDivider
constexpr uint32_tkleidos::platform::system::kKeepClockMhz
Returned by clockUnderRadioMhz when the clock has to stay where it is.
constexpr uint32_tkleidos::platform::crash_record::kRecordCapacity
Number of crash records retained; the oldest is overwritten first.
constexpr uint32_tkleidos::platform::crash_record::kMaxFrames
Maximum call frames captured per record.
constexpr uint32_tkleidos::platform::crash_record::kElfShaTextLength
constexpr uint32_tkleidos::platform::crash_record::kVersionTextLength
Buffer for the image's project version text, plus the NUL.
constexpr uint32_tkleidos::platform::crash_record::kSocResetSysRtcWdt
constexpr size_tkleidos::platform::light_sleep::kMaxWakePins
Most wake pins one board arms (the longest list a variant declares, with room).
constexpr intkleidos::platform::sleep::kMaxWakeMaskGpio
Largest GPIO number a 64-bit deep-sleep wake mask can select.
constexpr uint32_tkleidos::platform::slow_clock::kPeriodFractionBits
Fraction bits of a slow-clock period (microseconds per tick, fixed point).
constexpr uint32_tkleidos::platform::slow_clock::kMaxCycles
constexpr uint32_tkleidos::platform::slow_clock::kMinCycles
Fewest slow cycles one measurement counts.
constexpr size_tkleidos::platform::system::kMacAddressLength
Raw MAC address length in bytes.
constexpr size_tkleidos::platform::system::kMacAddressTextLength
Buffer size for "AA:BB:CC:DD:EE:FF" + NUL.
constexpr size_tkleidos::platform::system::kChipModelNameLength
Buffer size for the chip model name + NUL.
constexpr size_tkleidos::platform::system::kElfSha256ShortChars
constexpr size_tkleidos::platform::system::kElfSha256ShortTextLength
Buffer size for the short ELF SHA-256 text + NUL.
constexpr size_tkleidos::platform::system::kElfSha256Chars
Hex characters in the full ELF SHA-256 text (FirmwareInfo::elfSha256).
constexpr size_tkleidos::platform::system::kElfSha256TextLength
Buffer size for the full ELF SHA-256 text + NUL.
constexpr size_tkleidos::platform::system::kAppDescFieldLength
Buffer size for a field copied out of esp_app_desc_t::version / ::project_name / ::idf_ver.
constexpr size_tkleidos::platform::system::kAppDescStampLength
Buffer size for a field copied out of esp_app_desc_t::date / ::time.
constexpr const char *kleidos::platform::system::kNativeAppVersion
constexpr const char *kleidos::platform::system::kNativeProjectName
Project name reported by appProjectName on the native build.
constexpr uint64_tkleidos::platform::sleep::kNoTimerWake
constexpr uint64_tkleidos::platform::sleep::kLatestTimerWake
constexpr uint64_tkleidos::platform::sleep::kMinTimerWakeUs
constexpr uint64_tkleidos::platform::sleep::kMaxTimerWakeUs

Heap accounting

enum class kleidos::platform::system::BleTxPowerType : uint8_t { kleidos::platform::system::BleTxPowerType::Advertising , kleidos::platform::system::BleTxPowerType::Default , kleidos::platform::system::BleTxPowerType::Connection0 }
Which of the controller's transmit power settings to read back. More about kleidos::platform::system::BleTxPowerType
uint32_tkleidos::platform::system::freeHeapBytes ()
Free internal heap, in bytes.
uint32_tkleidos::platform::system::minimumFreeHeapBytes ()
Lowest free internal heap since boot, in bytes.
uint32_tkleidos::platform::system::largestFreeBlockBytes ()
Largest contiguous free block of internal heap, in bytes.
uint32_tkleidos::platform::system::internalRamTotalBytes ()
Total size of the internal RAM heap region, in bytes.
uint32_tkleidos::platform::system::currentTaskStackFreeBytes ()
The calling task's stack high-water mark, in bytes never touched.
HeapStatskleidos::platform::system::heapStats ()
Read a per-region heap snapshot (internal / PSRAM / DMA).
boolkleidos::platform::system::hasPsram ()
True when the SoC has usable external PSRAM (SPIRAM).
boolkleidos::platform::system::releaseClassicBtRam ()
Hand the Classic-BT (BR/EDR) controller's reserved RAM back to the heap.
int8_tkleidos::platform::system::bleTxPowerDbm ()
The Bluetooth LE transmit power the controller is set to, in dBm.
boolkleidos::platform::system::applyBleTxPower ()
Set the Bluetooth controller's default transmit power to bleTxPowerDbm.
boolkleidos::platform::system::readBleTxPowerDbm (BleTxPowerType type, int8_t &dbm)
Read one of the controller's transmit power settings back.

Wake-source configuration

boolkleidos::platform::sleep::enableExt0Wakeup (int gpioPin, bool wakeOnHigh)
Configure EXT0 single-pin deep-sleep wake.
boolkleidos::platform::sleep::enableGpioWakeup (int gpioPin, bool wakeOnHigh)
Configure GPIO deep-sleep wake (light-sleep compatible).
boolkleidos::platform::sleep::enablePinWakeup (int gpioPin, bool wakeOnHigh)
Configure a pin wake source, preferring EXT0 with GPIO fallback.
boolkleidos::platform::sleep::pinWakesDeepSleep (int gpioPin)
Whether gpioPin can wake a deep sleep at all on this SoC.
boolkleidos::platform::sleep::enableTimerWakeup (uint64_t microseconds)
Ask the next deep sleep to wake on its timer microseconds from now.
voidkleidos::platform::sleep::disableTimerWakeup ()
Drop the timer wake enableTimerWakeup asked for.
boolkleidos::platform::sleep::timerWakeAvailable ()
Whether this board's production deep sleep takes a timer wake.
boolkleidos::platform::sleep::ext1ModeSupported (Ext1Mode mode)
True when this SoC's EXT1 hardware implements mode.
boolkleidos::platform::sleep::enableExt1Wakeup (std::span< const int > gpioPins, Ext1Mode mode)
Configure EXT1 multi-pin deep-sleep wake.
boolkleidos::platform::sleep::enableWakePinPullUp (int gpioPin)
Pull an RTC wake pin up through deep sleep.

Wake-cause inspection

How the current boot started, the same answer for the whole boot. ESP-IDF's own wake cause names a light sleep's cause once one has run, whatever the reset was, so the facade decides a deep-sleep wake from the reset reason and reads the cause and the EXT1 pins once, before the first light sleep (boot_wake_logic.h). No call here reports a light sleep.

voidkleidos::platform::sleep::captureBootWake ()
Read how the current boot started, if nothing has read it yet.
WakeCausekleidos::platform::sleep::wakeCause ()
Return the cause of the deep-sleep wake that started the current boot.
boolkleidos::platform::sleep::wokeFromDeepSleep ()
True when the current boot followed a deep-sleep wake.
uint64_tkleidos::platform::sleep::ext1WakePinMask ()
GPIO mask of the pins that fired the EXT1 wake that started the boot.
const char *kleidos::platform::sleep::wakeCauseName (WakeCause cause)
Human-readable name for a wake cause.

Slow-clock sleep record

Through a light sleep ESP-IDF advances the wall clock by the slept time it converts from the RTC slow clock, which is far less exact than the crystal that counts the time awake, so each light sleep adds an error to the clock. This record is how much light sleep this boot has taken: every light sleep, timed (lightSleepFor) or automatic (light_sleep.h, through ESP-IDF's light-sleep exit callback), is noted here. It lives in RAM and starts at zero on every boot; a deep sleep is not noted, because it always ends in a reset, which starts the record again.

voidkleidos::platform::sleep::noteSlowClockSleep (uint64_t sleptMicros)
Note one light sleep counted by the RTC slow clock.
uint32_tkleidos::platform::sleep::slowClockSleepCount ()
Light sleeps noted this boot.
uint64_tkleidos::platform::sleep::slowClockSleptMicros ()
Total light-sleep time noted this boot.

USB PHY pads across a sleep

uint32_tkleidos::platform::sleep::isolateUsbPadsForDeepSleep ()
Isolate the USB PHY pads that nothing claims, for a deep sleep.
uint32_tkleidos::platform::sleep::releaseUsbPadHolds ()
Release any RTC hold left on the USB PHY pads by a previous sleep.
voidkleidos::platform::sleep::suppressRomLogOnNextWake ()
Keep the ROM bootloader silent on the next deep-sleep wake.

CPU clock

uint32_tkleidos::platform::system::cpuFrequencyMhz ()
CPU frequency in MHz.
boolkleidos::platform::system::cpuIdleFloorBuilt ()
Whether this build lets the cores drop to an idle floor.
boolkleidos::platform::system::radioUp ()
Whether a radio is up: the Wi-Fi driver or the Bluetooth controller.
boolkleidos::platform::system::powerManagementBuilt ()
Whether this build runs ESP-IDF's power management (CONFIG_PM_ENABLE).
uint32_tkleidos::platform::system::cpuIdleMhz ()
The clock the cores drop to while both are idle, in MHz.
boolkleidos::platform::system::setCpuIdleFloor (bool enabled)
Turn the idle floor on or off, keeping the ceiling where it is.
boolkleidos::platform::system::writePowerManagementStats (TextSink sink)
Write ESP-IDF's power-management statistics through sink.
uint32_tkleidos::platform::system::bootCpuFrequencyMhz ()
The CPU frequency the startup code set before the app ran, in MHz.
boolkleidos::platform::system::setCpuFrequencyMhz (uint32_t mhz)
Request a new CPU frequency.
voidkleidos::platform::system::prepareClockForRadio ()
Put the core clock where a radio may start on it.
uint32_tkleidos::platform::system::requestedCpuFrequencyMhz ()
The clock last asked for, in MHz, without a frame hold's raise.
voidkleidos::platform::system::holdFrameClock ()
Take one frame hold: run the core at least at the frame clock.
voidkleidos::platform::system::releaseFrameClock ()
Release one frame hold.
voidkleidos::platform::system::holdMaxClock ()
Take one maximum-clock hold: run the core at the boost clock until it is released.
voidkleidos::platform::system::releaseMaxClock ()
Release one maximum-clock hold.
boolkleidos::platform::system::setFrameClockEnabled (bool enabled)
Switch the frame clock on or off, for a measurement of what it buys.
boolkleidos::platform::system::frameClockEnabled ()
Whether a frame hold raises the clock (setFrameClockEnabled).

Clock sources

ClockInfokleidos::platform::system::clockInfo ()
Read a clock-source snapshot (CPU / APB / crystal frequencies).
uint64_tkleidos::platform::system::uptimeMs ()
Milliseconds since boot, 64-bit, so it does not wrap.

SoC identity

ChipInfokleidos::platform::system::chipInfo ()
Read the silicon identity (model, cores, revision, radios).
uint32_tkleidos::platform::system::flashSizeBytes ()
Size of the attached SPI flash, in bytes.

Partition table

uint32_tkleidos::platform::system::partitionCount ()
Count the entries in the flash partition table.
boolkleidos::platform::system::partitionAt (uint32_t index, PartitionInfo &out)
Read the partition-table entry at index.

Firmware image info

uint32_tkleidos::platform::system::runningImageSizeBytes ()
Size of the running application image, in bytes.
uint32_tkleidos::platform::system::nextUpdatePartitionSizeBytes ()
Capacity of the next OTA partition, in bytes.
FirmwareInfokleidos::platform::system::firmwareInfo ()
Which application image is running: its descriptor and full ELF SHA-256.
const char *kleidos::platform::system::elfSha256ShortText ()
The first kElfSha256ShortChars hex characters of the running image's ELF SHA-256.
const char *kleidos::platform::system::appVersion ()
Firmware version of the running image.
const char *kleidos::platform::system::appProjectName ()
Project name of the running image.

MAC address

boolkleidos::platform::system::readMacAddress (MacAddressKind kind, uint8_t *output, size_t outputLength)
Read raw MAC address bytes for an interface.
boolkleidos::platform::system::readMacAddressText (MacAddressKind kind, char *output, size_t outputLength)
Read a formatted MAC address string ("AA:BB:CC:DD:EE:FF").

Back to the top

Typedef Documentation

TextSink #

using kleidos::platform::system::TextSink

Receiver of text that a statistics dump writes piece by piece.

Called with each piece as it is produced; text is not NUL-terminated.

Parameters
NameDirectionMeaning
textinStart of the piece.
lengthinBytes in the piece.

Back to the top

Enumeration Type Documentation

BleTxPowerType #

enum class kleidos::platform::system::BleTxPowerType : uint8_t

Which of the controller's transmit power settings to read back.

Enumerator
Advertising 

The advertising state's.

Default 

The default, for every type not set on its own.

Connection0 

Connection handle 0's (the one link Kleidos holds).

Ext1Mode #

enum class kleidos::platform::sleep::Ext1Mode : uint8_t

Level condition that fires an EXT1 wake over its whole pin set.

The SoC decides which conditions exist: the classic ESP32 implements AllLow and AnyHigh, the ESP32-S3 AnyLow and AnyHigh. Ask ext1ModeSupported before relying on one. A single-pin AllLow set is how a classic ESP32 wakes on a second active-low key beside EXT0.

Value Wakes when
AnyLow any selected pin reads low (not on the classic ESP32).
AllLow every selected pin reads low (classic ESP32 only).
AnyHigh any selected pin reads high.
Enumerator
AnyLow 

Any selected pin reads low (not on the classic ESP32).

AllLow 

Every selected pin reads low (classic ESP32 only).

AnyHigh 

Any selected pin reads high.

MacAddressKind #

enum class kleidos::platform::system::MacAddressKind : uint8_t

Which interface MAC address to read.

Enumerator
WifiStation 

Wi-Fi station (STA) MAC.

WifiSoftAp 

Wi-Fi SoftAP MAC.

Bluetooth 

Bluetooth / BLE controller identity MAC.

Reason #

enum class kleidos::platform::crash_record::Reason : uint8_t

Why a record exists — the reset reason, at the precision it was observed.

A record captured by the panic hook carries the panic classification, which is strictly finer than what esp_reset_reason() can report afterwards. A record synthesized at boot (for a reset that never reached the panic handler, such as a brownout or an RTC-watchdog reset) carries the coarser reset reason and no frames.

Enumerator
Unknown 

Not classified.

Fault 

CPU exception (illegal instruction, load/store fault, ...).

Abort 

abort() / failed assertion.

IntWdt 

Interrupt watchdog timeout.

TaskWdt 

Task watchdog timeout.

Wdt 

Other watchdog reset (RTC / super watchdog).

Brownout 

Supply dropped below the brownout threshold.

UsbPadAction #

enum class kleidos::platform::sleep::UsbPadAction : uint8_t

What a deep sleep does with one USB PHY pad, and the reason.

Only UsbPadAction::Isolate acts; every other value leaves the pad exactly as the awake firmware configured it. The reason is kept rather than reduced to a bool so the log line, and anything reading it, can say which claim won.

Enumerator
Isolate 

Nothing claims the pad: isolate it before sleeping.

KeptAsWakePin 

Armed as a wake source; isolating it would strand the board asleep.

KeptAsHeldPad 

The board latched this pad on purpose; the latch outranks the saving.

NoSuchPad 

Not a pad number this SoC has; there is nothing to isolate.

WaitEnd #

enum class kleidos::platform::light_sleep::WaitEnd : uint8_t

Why an idle wait ended.

Enumerator
Timeout 

The timeout passed with no wake pin.

WakePin 

A wake pin went active.

PinAlreadyActive 

A wake pin was active as the wait began; no idle wait made.

NotBuilt 

No wait could be set up (or the native build): a plain delay.

WakeCause #

enum class kleidos::platform::sleep::WakeCause : uint8_t

What started the current boot.

Value Meaning
Undefined Power-on or reset (not a deep-sleep wake).
Ext0 EXT0 single-pin wake.
Ext1 EXT1 pin-mask wake.
Timer RTC timer wake.
Touchpad Touchpad wake.
Ulp ULP co-processor wake.
Gpio GPIO (deep-sleep mask) wake.
Uart UART activity wake.
Wifi Wi-Fi wake.
CoProcessor Co-processor wake.
Other A deep-sleep wake whose cause is unrecognized.
Enumerator
Undefined 

Power-on or reset (not a deep-sleep wake).

Ext0 

EXT0 single-pin wake.

Ext1 

EXT1 pin-mask wake.

Timer 

RTC timer wake.

Touchpad 

Touchpad wake.

Ulp 

ULP co-processor wake.

Gpio 

GPIO (light/deep-sleep) wake.

Uart 

UART activity wake.

Wifi 

Wi-Fi wake.

CoProcessor 

Co-processor wake.

Other 

A deep-sleep wake whose cause is unrecognized.

Back to the top

Function Documentation

abortWithReason() #

void kleidos::platform::system::abortWithReason(const char * reason)

Stop on a broken invariant, with reason printed in the panic report.

Wraps esp_system_abort(): the panic handler prints reason itself, before the backtrace, so the cause reaches the console even when a log line written just before is still waiting in the queued logger. The native build calls std::abort().

Parameters
NameMeaning
reasonText naming what went wrong. The panic handler reads it after this call, so it must have static storage (a string literal).
Warning
[[noreturn]] — the SoC panics, then follows the build's panic configuration (reboot, halt or core dump).

addWakePin() #

bool kleidos::platform::light_sleep::addWakePin(int pin)

Register an active-low GPIO that ends an idle wait.

The pin's owner configures it as an input (a key, an interrupt line); this only attaches the handler that ends a wait. Call once per pin at boot, before the first idleWait.

Parameters
NameDirectionMeaning
pininGPIO number.
Return values
ValueMeaning
trueRegistered (always on the native build).
falseInvalid pin, the list is full, or the interrupt could not be attached.

applyBleTxPower() #

bool kleidos::platform::system::applyBleTxPower()

Set the Bluetooth controller's default transmit power to bleTxPowerDbm.

Call once the host has synced and before advertising starts: the HCI reset the host sends while it starts puts the controller's levels back to its own defaults, so a level set before the sync does not hold. It covers advertising and every connection made after it.

Return values
ValueMeaning
trueThe controller took the level.
falseIt refused it, or the native build.

appProjectName() #

const char * kleidos::platform::system::appProjectName()

Project name of the running image.

esp_app_desc_t::project_name, set per environment from the CMake project name, is the field that says which board variant a binary was built for. The OTA path rejects a candidate image whose project name differs from the running one, because the ESP32-S3 variants share a chip ID and would otherwise accept each other's pinout.

Returns
Pointer into the image's own rodata descriptor, valid for the lifetime of the program; kNativeProjectName on the native build.

appVersion() #

const char * kleidos::platform::system::appVersion()

Firmware version of the running image.

The single source of the firmware version: esp_app_desc_t::version, which ESP-IDF stamps from PROJECT_VER, which comes from the repository-root version.txt. It is the same value the OTA anti-downgrade guard compares (kleidos::platform::ota::AppUpdateSession::finishAndSetBootPartition), so what the UI shows and what the update path enforces can never disagree.

Returns
Pointer into the image's own rodata descriptor, valid for the lifetime of the program; kNativeAppVersion on the native build.

armedWakeTicks() #

uint64_t kleidos::platform::slow_clock::armedWakeTicks()

The tick the sleep timer was last armed to fire at.

ESP-IDF arms the RTC sleep timer as a timer-woken sleep begins. The register keeps its value through the sleep and the reset that ends it, so on the boot after a timer wake this is the tick the sleep ended at.

Returns
The armed tick (48 bits); 0 on the native build.

begin() [1/2] #

bool kleidos::platform::crash_record::begin()

Adopt the RTC ring, reconcile it with this boot, and mirror it to NVS.

Must run once on a normal boot, from a task context, after NVS is usable and before anything reads the ring. It:

  • validates the RTC ring and, when it is gone (power was lost), restores the NVS mirror into it;
  • advances the boot ordinal;
  • appends a frameless record when this boot follows an abnormal reset that never reached the panic handler (brownout, RTC watchdog);
  • writes the ring back to NVS when it changed.

Idempotent: a second call is a no-op.

Return values
ValueMeaning
trueThe ring is initialized and usable.
falseThis is the native build, or the RTC ring could not be adopted.

begin() [2/2] #

bool kleidos::platform::light_sleep::begin()

Create the hold and take it. Idempotent.

Called by platform::system before every configuration of ESP-IDF's power management that enables light sleep, so the hold exists, taken, before light sleep can begin. The light-sleep exit callback that feeds the slow-clock sleep record is registered first.

Return values
ValueMeaning
trueThe hold is in place (or the build has no light sleep).
falseESP-IDF refused the callback or the lock; light sleep must stay disabled.

bleTxPowerDbm() #

int8_t kleidos::platform::system::bleTxPowerDbm()

The Bluetooth LE transmit power the controller is set to, in dBm.

One level for advertising and every connection, +9 dBm on both chip families: the level both controllers run at after the host's HCI reset, read back from each controller. It is set explicitly by applyBleTxPower rather than left to either controller, so a default that changes in a later ESP-IDF changes nothing here.

Returns
The level in dBm.

bootCpuFrequencyMhz() #

uint32_t kleidos::platform::system::bootCpuFrequencyMhz()

The CPU frequency the startup code set before the app ran, in MHz.

The clock every boot-time derivation was computed against, the FreeRTOS tick period among them: a reading of a value derived from the core clock proves that it follows a frequency change only when it is taken at a clock other than this one.

Returns
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ in MHz; 0 on the native build.

bootSequence() #

uint32_t kleidos::platform::crash_record::bootSequence()

Ordinal of the current boot.

Advances once per begin. Compare it against Record::bootSequence to tell "crashed on the boot before this one" from "crashed a long time ago". Two caveats, both deliberate: every deep-sleep wake is a boot, and on a power cycle the ordinal is restored from the NVS mirror, which was last written when a crash was recorded — so boots that happened after the last crash and before power was lost are not counted. The ordinal orders records; it is not a device-lifetime boot counter.

Returns
Boot ordinal; 0 on the native build or before begin.

bootWakeOf() #

BootWake kleidos::platform::sleep::bootWakeOf(const WakeReading & reading)
constexpr

The boot one reading describes.

Only a deep-sleep reset is a deep-sleep wake: on any other boot the reported cause can only be a light sleep's, so it is dropped. A deep-sleep reset whose cause decodes to nothing ESP-IDF names is still a deep-sleep wake, reported as Other, so cause is Undefined exactly when deepSleepWake is false. The EXT1 pins are kept for an EXT1 wake only.

Parameters
NameDirectionMeaning
readinginWhat the chip said.
Returns
The boot it describes.

built() #

bool kleidos::platform::light_sleep::built()

Whether this build carries automatic light sleep.

Return values
ValueMeaning
trueCONFIG_FREERTOS_USE_TICKLESS_IDLE is on.
falseIt is not, or this is the native build.

captureBootWake() #

void kleidos::platform::sleep::captureBootWake()

Read how the current boot started, if nothing has read it yet.

Every path into a light sleep calls it first (lightSleepFor, and the automatic light sleep's light_sleep::begin before ESP-IDF's power management may enable it), so the reading always precedes the first light sleep; any other first call of the calls below takes it too. Idempotent and safe from any task, not from an ISR.

chipInfo() #

ChipInfo kleidos::platform::system::chipInfo()

Read the silicon identity (model, cores, revision, radios).

Returns
A populated ChipInfo on device; a zeroed value on the native build.

clockBeforeRadioMhz() #

uint32_t kleidos::platform::system::clockBeforeRadioMhz(CpuClockSource running, CpuClockSource base)
constexpr

The core clock to move to before a radio comes up.

Once a radio runs off the PLL, clockUnderRadioMhz refuses every request that only the other PLL setting can give, so a clock left on that setting when the radio starts stays there until the radio is down: a 240 MHz boost still in force when Bluetooth starts would hold the whole BLE session at 240 MHz. Moving to the base clock first puts the PLL on the base clock's setting, where the base clock is always reachable again. A clock already on that setting, or not PLL-sourced, stays where it is: clockUnderRadioMhz lets the base clock be asked for from it with the radio up.

Parameters
NameDirectionMeaning
runninginThe clock in force.
baseinThe base clock of the boards.
Returns
base's core frequency in MHz, or ::kKeepClockMhz to leave the clock as it is.

clockInfo() #

ClockInfo kleidos::platform::system::clockInfo()

Read a clock-source snapshot (CPU / APB / crystal frequencies).

Returns
A populated ClockInfo on device; a zeroed value on native.

clockUnderRadioMhz() #

uint32_t kleidos::platform::system::clockUnderRadioMhz(CpuClockSource running, CpuClockSource asked, bool radioUp)
constexpr

The core clock to apply for a request, given whether a radio is up.

With no radio up, or when asked comes off the same PLL setting as running (or either is not PLL-sourced), the request stands. Otherwise the request would re-lock the PLL under the radio, so:

  • a request above the running setting's top is narrowed to that top (240 asked at 80 or 160 gives 160), unless the clock already runs there;
  • a request at or below that top, which only the other setting can give (80 or 160 asked at 240), is refused.
Parameters
NameDirectionMeaning
runninginThe clock in force.
askedinThe clock requested.
radioUpinWhether Wi-Fi or Bluetooth is up.
Returns
The core frequency to apply in MHz, or ::kKeepClockMhz to leave the clock as it is.

clockWithFloorMhz() #

uint32_t kleidos::platform::clockWithFloorMhz(uint32_t askedMhz, uint32_t floorMhz)
constexpr

The clock to apply for a request under a floor.

A floor raises a request below it to itself and leaves a higher one alone, so whichever of the two is the faster clock wins and neither owner has to know about the other. Arithmetic only, so the host tests assert it; system::setCpuFrequencyMhz applies the floor in force to every request.

Parameters
NameDirectionMeaning
askedMhzinThe clock asked for, MHz.
floorMhzinThe floor in force, MHz; 0 when there is none.
Returns
The clock to apply, MHz.

clockWithFrameHoldMhz() #

uint32_t kleidos::platform::clockWithFrameHoldMhz(uint32_t askedMhz, bool frameHeld)
constexpr

The clock to apply for a request while a frame hold may be in force.

A frame hold is a floor at ::kCpuFrameMhz (clockWithFloorMhz).

Parameters
NameDirectionMeaning
askedMhzinThe clock asked for, MHz.
frameHeldinWhether a frame hold is in force.
Returns
The clock to apply, MHz.

configuredCycles() #

uint32_t kleidos::platform::slow_clock::configuredCycles()

Slow cycles ESP-IDF's startup calibration counts, as built.

Returns
CONFIG_RTC_CLK_CAL_CYCLES; 0 on the native build.

cpuFrequencyMhz() #

uint32_t kleidos::platform::system::cpuFrequencyMhz()

CPU frequency in MHz.

On a board built with the idle floor (cpuIdleFloorBuilt) this is the ceiling: the clock a core runs at whenever a task or an interrupt keeps it busy, which is every moment a caller can read it from. The cores drop below it only while both are idle (cpuIdleMhz).

Returns
CPU frequency in MHz; 0 on the native build.

cpuIdleFloorBuilt() #

bool kleidos::platform::system::cpuIdleFloorBuilt()

Whether this build lets the cores drop to an idle floor.

The idle floor is ESP-IDF's dynamic frequency scaling (esp_pm, CONFIG_PM_ENABLE), switched on per variant in that variant's sdkconfig fragment and held there by a check of the build, and only on the ESP32-S3: the classic ESP32's tick and esp_timer clock do not keep time through its switches, so a classic board that builds esp_pm (for automatic light sleep) never gets a floor. With it, every clock setCpuFrequencyMhz applies is a ceiling: a busy core runs at it, and while both cores are idle the clock drops to kleidos::platform::kCpuIdleFloorMhz, the crystal, until the next interrupt or task wakes one.

Return values
ValueMeaning
trueThe idle floor is built in.
falseIt is not (and on the native build): the clock stays where setCpuFrequencyMhz puts it.

cpuIdleMhz() #

uint32_t kleidos::platform::system::cpuIdleMhz()

The clock the cores drop to while both are idle, in MHz.

Returns
kleidos::platform::kCpuIdleFloorMhz while the idle floor is built and in force; otherwise the clock in force (cpuFrequencyMhz), which idle cores keep. 0 on the native build.

crashCount() #

uint32_t kleidos::platform::crash_record::crashCount()

Total number of crashes recorded since the ring was last cleared.

Counts crashes whose record has since been overwritten, and saturates instead of wrapping.

Returns
Crash count; 0 on the native build.

currentMhz() #

uint32_t kleidos::platform::cpu_boost::currentMhz()
inline

Current core clock, for callers that report rather than set it.

Returns
Core frequency in MHz; 0 on the native host, which has none.

currentTaskStackFreeBytes() #

uint32_t kleidos::platform::system::currentTaskStackFreeBytes()

The calling task's stack high-water mark, in bytes never touched.

The least free stack the calling task has ever had. A task the firmware does not own (the HTTP server's, for one) cannot be found by a task census, so a handler that runs on it reports the figure itself.

Returns
Bytes of stack that were never touched; 0 on the native build.

deepSleepStart() #

void kleidos::platform::sleep::deepSleepStart()

Enter deep sleep immediately; never returns (the SoC resets on wake).

Before sleeping, arms the deep-sleep GPIO hold so any pad latched via kleidos::platform::gpio::holdEnable retains its level through sleep (harmless no-op when nothing is held). It then decides the timer wake, on every build: armed for the time left to a pending enableTimerWakeup deadline (at least kMinTimerWakeUs, so a deadline already due wakes the board at once), or for a debug build's test length when that is sooner, capped at kMaxTimerWakeUs, and dropped when neither is pending. ESP-IDF's own timer source, which a length handed to it once or automatic light sleep's last light sleep leaves armed, therefore never carries an old request into this sleep. Should ESP-IDF refuse a length the facade arms, the board wakes on kMinTimerWakeUs instead (logged as an error) rather than on no timer.

It then isolates the USB PHY pads nothing claims (isolateUsbPadsForDeepSleep). That step runs LAST, after every caller has armed its wake pins, held its pads and written its final log line, for one reason and it is diagnostic: on every build that prints to the USB-Serial/JTAG, isolating earlier would delete the lines a test reads to confirm a sleep started. It cannot disarm a wake source — it refuses any pad the board lists as a wake pin, which is a build error, or that was armed through this facade — nor release a hold, both effects being per-pin.

Warning
[[noreturn]] — the device resets on wake. Power down BLE, WiFi, LittleFS, and the display before calling this. Never call from an ISR; the call is only legal from the FSM/main-loop task.

disableTimerWakeup() #

void kleidos::platform::sleep::disableTimerWakeup()

Drop the timer wake enableTimerWakeup asked for.

For a caller whose reason to wake ended before the board slept. It drops the one record every caller shares, so a caller that shares the board with another asks again after the other's cancel. Safe when nothing is pending. The test timer of a debug build is left as it is.

discard() #

void kleidos::platform::cpu_boost::discard()
inline

Drop the latch WITHOUT restoring, for a caller that applies its own target frequency in the same breath. Idempotent.

elfSha256ShortText() #

const char * kleidos::platform::system::elfSha256ShortText()

The first kElfSha256ShortChars hex characters of the running image's ELF SHA-256.

ESP-IDF converts that prefix into a DRAM string at startup precisely so it stays readable when the flash cache is off, and its own core-dump writer uses it for the same reason (espcoredump/src/core_dump_elf.c). It is therefore the form the panic-time crash record stamps into a record.

Returns
Pointer to a static NUL-terminated string; "" on the native build.

enableExt0Wakeup() #

bool kleidos::platform::sleep::enableExt0Wakeup(int gpioPin, bool wakeOnHigh)

Configure EXT0 single-pin deep-sleep wake.

Parameters
NameMeaning
gpioPinRTC-capable GPIO pin number.
wakeOnHighTrue to wake when the pin is high, false for low.
Return values
ValueMeaning
trueEXT0 wake source configured successfully.
falseDriver rejected the EXT0 configuration.

enableExt1Wakeup() #

bool kleidos::platform::sleep::enableExt1Wakeup(std::span< const int > gpioPins, Ext1Mode mode)

Configure EXT1 multi-pin deep-sleep wake.

Arms every pin in gpioPins under one level condition and replaces any EXT1 set armed before, the way enableExt0Wakeup replaces its one pin. EXT0 and EXT1 are separate sources and can be armed together. EXT1 keeps working with the RTC peripherals powered down. This call configures no pull resistor: the board's own pulls, or ones the caller set, hold each pin's idle level.

Parameters
NameMeaning
gpioPinsRTC-capable GPIO numbers. ESP32: 0, 2, 4, 12-15, 25-27, 32-39. ESP32-S3: 0-21.
modeLevel condition; one ext1ModeSupported accepts.
Return values
ValueMeaning
trueEXT1 now wakes on exactly gpioPins under mode.
falseEmpty list, a pin that is not an RTC GPIO, a condition this SoC lacks, or a host build. A rejected argument leaves the previous EXT1 configuration untouched.

enableGpioWakeup() #

bool kleidos::platform::sleep::enableGpioWakeup(int gpioPin, bool wakeOnHigh)

Configure GPIO deep-sleep wake (light-sleep compatible).

Parameters
NameMeaning
gpioPinGPIO pin number.
wakeOnHighTrue to wake when the pin is high, false for low.
Return values
ValueMeaning
trueGPIO wake source configured successfully.
falseDriver rejected the GPIO configuration.

enablePinWakeup() #

bool kleidos::platform::sleep::enablePinWakeup(int gpioPin, bool wakeOnHigh)

Configure a pin wake source, preferring EXT0 with GPIO fallback.

Parameters
NameMeaning
gpioPinGPIO pin number.
wakeOnHighTrue to wake when the pin is high, false for low.
Return values
ValueMeaning
trueEither EXT0 or GPIO wake was configured successfully.
falseBoth EXT0 and GPIO configurations failed.
Note
An external RTC-alarm wake (e.g. the BM8563 INT line armed via rtc::armAlarmWake) arrives through this path, so wakeCause reports it as WakeCause::Ext0 or WakeCause::Gpio (whichever backend was selected) — not WakeCause::Timer. WakeCause::Timer denotes the SoC's own internal RTC timer (see enableTimerWakeup), a different source; an external RTC alarm is never reported as a timer wake.

enableTimerWakeup() #

bool kleidos::platform::sleep::enableTimerWakeup(uint64_t microseconds)

Ask the next deep sleep to wake on its timer microseconds from now.

Records a deadline, not a length: the board must wake at this call's monotonic time plus microseconds. Nothing reaches ESP-IDF before a deep sleep starts; deepSleepStart then arms ESP-IDF's timer for the time still left, never under kMinTimerWakeUs (1 s), so a deadline that came during the teardown before the sleep wakes the board at once, as an RTC alarm that fired while the board was up holds its interrupt (the record and the arithmetic are timer_wake_logic.h). A caller whose reason to wake ends before the board sleeps cancels with disableTimerWakeup. The deadline lives in RAM and a deep sleep ends in a reset, so one request reaches one sleep at most. The wake reports WakeCause::Timer on the next boot.

Every caller shares one record: a call never postpones a sooner deadline already pending (each request only asks to be awake by its moment), and disableTimerWakeup drops them all. To ask for a later wake than the one pending, cancel first. One deep sleep's timer is at most kMaxTimerWakeUs (24 h): a longer request wakes the board then, and its caller asks again on the next boot.

Refused on a board whose production deep sleep only a reset ends (the LILYGO T-Deck; timerWakeAvailable answers it), so no caller has to know the board; the first refusal of a boot is logged. The test sleeps of a debug build arm their own timer, on every board, through enableBenchTimerWakeup.

Parameters
NameMeaning
microsecondsDelay until the wake, in microseconds, measured from this call.
Return values
ValueMeaning
trueThe deadline is recorded (merged into the soonest pending).
falseThis board's deep sleep takes no timer wake, or a host build.

enableWakePinPullUp() #

bool kleidos::platform::sleep::enableWakePinPullUp(int gpioPin)

Pull an RTC wake pin up through deep sleep.

Enables the pin's RTC-domain pull-up and disables its pull-down. EXT1 routes each of its pins to the RTC domain on sleep entry and, with the RTC peripherals powered down, holds the pad, pull included, for the whole sleep; the boot after the wake releases that hold. For a wake line that nothing else holds high while it is released, such as a PMIC IRQ output, an active-low EXT1 set would otherwise wake on a floating level. Call it once the pin's last digital configuration is done: a later kleidos::platform::gpio::configure returns the pad to the digital domain.

Parameters
NameMeaning
gpioPinRTC-capable GPIO number.
Return values
ValueMeaning
trueThe pull-up is set.
falseThe pin is not an RTC GPIO, the driver refused, or this is a host build.

eraseCoreDumpPartition() #

bool kleidos::platform::crash_record::eraseCoreDumpPartition()

Erase the core dump partition, where the partition table has one.

Only a debug build's table carries one: a crash there writes a DRAM snapshot to it, live task stacks included, which can hold a secret or a session key. A factory reset erases it with the rest of the owner's flash.

Return values
ValueMeaning
trueThe partition was erased, or this table has none.
falseThe erase failed (logged).

expireIfStale() #

uint32_t kleidos::platform::cpu_boost::expireIfStale()
inline

Take down a latch that has outlived ::kCpuBoostMaxHoldMs.

The latch is normally ended by the state that owns the boosted phase, and every state entry ends it as a backstop because each one names its own frequency. Both of those are call sites, and a call site can be forgotten by a route added later. This is not a call site: it is a sweep the main loop runs unconditionally on every tick, so the longest a leaked boost can survive is one bound rather than the rest of the session. Returning the restored frequency instead of logging keeps this header free of the log facade — the caller reports the leak, which is the only place that knows a tick happened.

Returns
Frequency restored in MHz, or 0 when no latch was overdue.

ext1ModeSupported() #

bool kleidos::platform::sleep::ext1ModeSupported(Ext1Mode mode)

True when this SoC's EXT1 hardware implements mode.

Parameters
NameMeaning
modeLevel condition to test.
Return values
ValueMeaning
trueenableExt1Wakeup accepts mode on this SoC.
falseThe SoC has no such EXT1 condition, no EXT1 at all, or this is a host build.

ext1PinMask() #

uint64_t kleidos::platform::sleep::ext1PinMask(std::span< const int > gpioPins)
constexpr

GPIO bit mask of a wake-pin list, in the form the EXT1 hardware takes.

Pure and constexpr, so a board's pin list can be checked at compile time and on the host. A pin listed twice sets its bit once. Whether each pin is an RTC GPIO of the running SoC is not checked here: enableExt1Wakeup does that against the SoC.

Parameters
NameMeaning
gpioPinsGPIO numbers to select.
Returns
The mask, or 0 when gpioPins is empty or holds a number outside [0, kMaxWakeMaskGpio].

ext1WakePinMask() #

uint64_t kleidos::platform::sleep::ext1WakePinMask()

GPIO mask of the pins that fired the EXT1 wake that started the boot.

Tells apart the keys of one EXT1 set (bit N set means GPIO N was at its wake level). Read once with the cause (captureBootWake) and kept.

Returns
The mask, or 0 when the boot did not follow an EXT1 deep-sleep wake, the SoC has no EXT1, or this is a host build.

firmwareInfo() #

FirmwareInfo kleidos::platform::system::firmwareInfo()

Which application image is running: its descriptor and full ELF SHA-256.

Reads the image's esp_app_desc_t through esp_app_get_description() and the full ELF SHA-256 out of the same structure. Both live in flash-mapped rodata, so this is a task-context call: it must not be made from a panic handler or with the cache disabled — use elfSha256ShortText there.

Returns
The running image's identity; every field empty/zero on the native build.

flashSizeBytes() #

uint32_t kleidos::platform::system::flashSizeBytes()

Size of the attached SPI flash, in bytes.

Returns
Flash size in bytes; 0 on the native build or on a query failure.

frameClockEnabled() #

bool kleidos::platform::system::frameClockEnabled()

Whether a frame hold raises the clock (setFrameClockEnabled).

Return values
ValueMeaning
trueIt does (the state every boot starts in).
falseIt was switched off, or this is the native build.

freeHeapBytes() #

uint32_t kleidos::platform::system::freeHeapBytes()

Free internal heap, in bytes.

Returns
Free heap bytes; 0 on the native build.

hasPsram() #

bool kleidos::platform::system::hasPsram()

True when the SoC has usable external PSRAM (SPIRAM).

Return values
ValueMeaning
truePSRAM is present and initialized (non-zero SPIRAM capacity).
falseNo PSRAM, or the native build.

heapStats() #

HeapStats kleidos::platform::system::heapStats()

Read a per-region heap snapshot (internal / PSRAM / DMA).

Breaks the aggregate heap out by memory capability for leak / fragmentation monitoring. The psram* fields read 0 on a board with no PSRAM; every field reads 0 on the native build.

Returns
A populated HeapStats on device; a zeroed value on native.

held() #

bool kleidos::platform::cpu_boost::held()
inline

Whether a boost is currently latched past its raising scope.

Return values
ValueMeaning
trueA latch is in effect and owes a restore.

heldForMs() #

uint32_t kleidos::platform::cpu_boost::heldForMs()
inline

How long the current latch has been held.

Returns
Milliseconds since the latch was taken; 0 while none is held.

hold() #

void kleidos::platform::cpu_boost::hold(uint32_t restoreMhz)
inline

Latch the boost, remembering the frequency the restore must return to.

No-op when restoreMhz is 0 or a latch is already in effect.

Parameters
NameDirectionMeaning
restoreMhzinFrequency captured before the boost was applied.

holdFrameClock() #

void kleidos::platform::system::holdFrameClock()

Take one frame hold: run the core at least at the frame clock.

Holds are counted. While one is held, every clock this module applies is the one asked for or kleidos::platform::kCpuFrameMhz, whichever is higher (kleidos::platform::clockWithFrameHoldMhz): a crypto boost asked for during the hold runs at its own clock, and its restore lands on the frame clock while the hold lasts. The first hold switches only when the clock in force is below the frame clock, and the radio rule of setCpuFrequencyMhz applies to it as to every clock; on the classic ESP32 the frame clock comes off the base clock's PLL setting, so a hold taken at the base clock never re-locks the PLL. A no-op while the frame clock is switched off (setFrameClockEnabled). Takes the same lock as setCpuFrequencyMhz. Taken through kleidos::platform::FrameBoostGuard, which the display layer holds for the length of a heavy frame.

holdMaxClock() #

void kleidos::platform::system::holdMaxClock()

Take one maximum-clock hold: run the core at the boost clock until it is released.

The same counted floor a frame hold is, at kleidos::platform::kCpuBoostMhz instead of the frame clock, and for a whole phase instead of one frame: while one is held, every clock this module applies is raised to the boost clock, so a request for the base clock does not lower it while the hold is taken. The higher floor wins, so a frame hold taken inside one changes nothing. The radio rule of setCpuFrequencyMhz applies as to every clock: on a classic ESP32 with a radio up the floor lands at the fastest clock the running PLL setting reaches. Takes the same lock as setCpuFrequencyMhz. Taken through kleidos::platform::MaxClockGuard, which each recording path holds for a whole take: the debug video stream for a connection's session, the console's cable take for the cable's.

idleWait() #

WaitEnd kleidos::platform::light_sleep::idleWait(uint32_t timeoutMs, uint32_t activeFallbackMs)

Wait out an idle stretch, letting the chip light-sleep through it where the build can.

Arms every wake pin, enables ESP-IDF's GPIO wake source and lets go of the hold, blocks until a wake pin goes active or timeoutMs passes, then takes the hold back, drops the GPIO wake source and disarms the pins again. On a build without automatic light sleep there is no hold and no wake source: the pins are armed as interrupts and the call blocks the same way. A wake pin already active when the call begins ends nothing: the call waits activeFallbackMs with the hold kept, so a line left asserted cannot turn the wait into a spin. Called from one task, the main loop.

Parameters
NameDirectionMeaning
timeoutMsinLongest wait, ms.
activeFallbackMsinWait made instead when a wake pin is already active, ms.
Returns
Why the wait ended.

installEntryRecorder() #

bool kleidos::platform::slow_clock::installEntryRecorder()

Register the deep-sleep hook that records EntryRecord.

The hook runs inside ESP-IDF's deep-sleep entry, after its ten-cycle calibration and before the sleep timer is armed, with interrupts off and the other core stalled: it copies the period, the tick count and the uptime into RTC memory and nothing else. Registering it again is a no-op. Debug instrumentation: the production firmware installs no hook.

Return values
ValueMeaning
trueThe hook is registered.
falseESP-IDF has no free hook slot, or this is the native build.

internalRamTotalBytes() #

uint32_t kleidos::platform::system::internalRamTotalBytes()

Total size of the internal RAM heap region, in bytes.

Returns
Total internal (DRAM) heap capacity in bytes; 0 on the native build.

isolates() #

bool kleidos::platform::sleep::isolates(UsbPadAction action)
nodiscardconstexpr

Whether an action actually touches the pad.

Parameters
NameMeaning
actionThe action to test.
Returns
True when action is UsbPadAction::Isolate.

isolateUsbPadsForDeepSleep() #

uint32_t kleidos::platform::sleep::isolateUsbPadsForDeepSleep()

Isolate the USB PHY pads that nothing claims, for a deep sleep.

Called by deepSleepStart, so every board inherits it from one place and no board file repeats it. On an ESP32-S3 the pads are GPIO19 (D-) and GPIO20 (D+); both numbers come from the SoC headers, and both pads are isolated, which is what makes the ECO1 USB_EXCHG_PINS swap irrelevant here — whichever of the two the eFuse makes D+, its pull-up is the one cleared. For each pad it takes the verdict of sleep::usbPadAction (usb_pad_sleep.h) against every pin that can end a sleep — the board's deep-sleep and idle wake sets, plus every pin armed through this facade since boot — and against the pads kleidos::platform::gpio::isHeld reports latched, and isolates only the pads that verdict clears. Isolating removes the pad's pulls — on the D+ pad that reaches into the USB peripheral and clears its pull-up, which is the drain this exists to stop — disables its input and output, and latches the result with an RTC-domain pad hold. It logs one line per pad naming the verdict before it acts, and flushes the console, because on the ESP32-S3 boards those lines leave over the peripheral it is about to park.

Note
Whether the pad hold keeps the USB pull-up off through the whole sleep has not been measured on silicon, and Espressif's own driver/gpio.h says the pull-up returns ("the USB related registers are reset, so the USB pull-up is back" after a deep-sleep wake). What the step guarantees regardless is that no constant bias hides in a power measurement.
Warning
Terminal: a build whose console is the USB-Serial/JTAG loses it until the next reset, which is why deepSleepStart runs this after everything its callers say.
Returns
How many pads were isolated; 0 on a SoC with no USB PHY, on a host build, or when every pad was claimed.

largestFreeBlockBytes() #

uint32_t kleidos::platform::system::largestFreeBlockBytes()

Largest contiguous free block of internal heap, in bytes.

Returns
Largest free block in bytes; 0 on the native build.

lastEntry() #

EntryRecord kleidos::platform::slow_clock::lastEntry()

The record of the last deep sleep the hook saw begin.

RTC memory keeps it through deep sleep and software resets; a power-on loses it. On the boot after a deep sleep it describes the sleep that just ended.

Returns
The record; valid is false when none survives.

lightSleepFor() #

bool kleidos::platform::sleep::lightSleepFor(uint64_t microseconds, bool keepCrystalOn)

Light-sleep the SoC for a fixed time and return when the timer ends it.

Every wake source armed before is dropped, so only the timer ends the sleep, and the timer source is dropped again on return. A deadline enableTimerWakeup recorded is the facade's, not ESP-IDF's, so it is kept for the next deep sleep. Both cores stop, RAM and every peripheral keep their state, and every pad keeps its awake configuration (ESP-IDF's switch to an isolated sleep configuration is suspended for the sleep), so a board's rails and parts stay as they were. On a board built with automatic light sleep the pads stay as that leaves them instead: each one a platform facade configured keeps its awake configuration (kleidos::platform::gpio::keepThroughLightSleep), and switching the isolation back on for every pad on return would undo that. The monotonic clock is advanced on return by the slept time as ESP-IDF converts it from the RTC slow clock; the FreeRTOS tick count is not. The crystal is powered down for the sleep unless keepCrystalOn asks to keep it; the setting is put back to automatic on return.

Bring the radios down first. On a board whose console is the ESP32-S3's own USB port the host sees the port go away for the sleep: the chip cannot keep that peripheral alive through a light sleep.

The sleep is noted in the slow-clock sleep record (noteSlowClockSleep) with its full length before it begins, so a sleep ESP-IDF refuses still counts: the record may overstate the slept time, never understate it.

Parameters
NameMeaning
microsecondsSleep length.
keepCrystalOnKeep the 40 MHz crystal powered through the sleep.
Return values
ValueMeaning
trueThe SoC slept and the timer woke it.
falseESP-IDF refused the sleep (too short, or a wake already pending), or this is a host build (which notes nothing).

measure() #

uint32_t kleidos::platform::slow_clock::measure(uint32_t cycles)

Measure the slow-clock period now, against the crystal.

Counts crystal cycles over cycles slow cycles, the same measurement ESP-IDF takes at startup, and leaves ESP-IDF's own period untouched. A busy wait on the calling task (see the file note).

Parameters
NameDirectionMeaning
cyclesinSlow cycles to count, clamped to [kMinCycles, kMaxCycles].
Returns
Microseconds per tick with kPeriodFractionBits fraction bits, or 0 when the measurement timed out; exactly one microsecond on the native build.

measureAtRtcCode() #

bool kleidos::platform::slow_clock::measureAtRtcCode(uint8_t code, uint32_t cycles, uint32_t & result)

Measure the slow-clock period with the RTC regulator raised to code.

Raises the RTC regulator to code, lets it settle, measures over cycles and puts back the code ESP-IDF runs at the CPU frequency in force at the end. Only codes from the one in force now up to ESP-IDF's own 240 MHz code are accepted: never below what ESP-IDF set, so the RTC domain never drops under the digital one, and never above a code ESP-IDF itself uses awake.

Parameters
NameDirectionMeaning
codeinRTC regulator code to measure at.
cyclesinSlow cycles to count, clamped as measure clamps them.
resultoutThe period, as measure returns it.
Return values
ValueMeaning
trueresult holds the measurement.
falsecode is outside the accepted range, or this is not an ESP32-S3 target.

minimumFreeHeapBytes() #

uint32_t kleidos::platform::system::minimumFreeHeapBytes()

Lowest free internal heap since boot, in bytes.

Returns
Minimum free heap bytes observed since boot; 0 on the native build.

nextUpdatePartitionSizeBytes() #

uint32_t kleidos::platform::system::nextUpdatePartitionSizeBytes()

Capacity of the next OTA partition, in bytes.

Returns
Partition size in bytes; 0 on the native build.

noteSlowClockSleep() #

void kleidos::platform::sleep::noteSlowClockSleep(uint64_t sleptMicros)

Note one light sleep counted by the RTC slow clock.

Called by lightSleepFor and by the automatic light-sleep exit callback; public so the native tests can drive the record. Safe from any task and from the idle task's sleep path.

Parameters
NameMeaning
sleptMicrosTime slept, in microseconds.

operatingPoint() #

OperatingPoint kleidos::platform::slow_clock::operatingPoint()

Read the regulator operating point.

Returns
The point; available is false off the ESP32-S3.

padListed() #

bool kleidos::platform::sleep::padListed(int pad, std::span< const int > pads)
nodiscardconstexpr

Whether a pad number appears in a pin list.

Parameters
NameMeaning
padGPIO number to look for.
padsThe list to search; may be empty.
Returns
True when pad appears in pads.

partitionAt() #

bool kleidos::platform::system::partitionAt(uint32_t index, PartitionInfo & out)

Read the partition-table entry at index.

Entries are enumerated in the same order esp_partition_find yields them. The running app partition is flagged via PartitionInfo::running.

Parameters
NameDirectionMeaning
indexinZero-based partition index (0 .. partitionCount()-1).
outoutReceives the descriptor on success.
Return values
ValueMeaning
trueindex was valid and out was filled.
falseindex was out of range, or the native build.

partitionCount() #

uint32_t kleidos::platform::system::partitionCount()

Count the entries in the flash partition table.

Returns
Number of partitions; 0 on the native build.

pendingRestoreMhz() #

uint32_t kleidos::platform::cpu_boost::pendingRestoreMhz()
inline

Frequency a held latch owes a restore to.

Returns
Restore frequency in MHz; 0 while no latch is held.

period() #

uint32_t kleidos::platform::slow_clock::period()

The period ESP-IDF converts slow ticks at, now.

The startup measurement until a sleep begins; each sleep entry replaces it with ESP-IDF's ten-cycle measurement, and the boot after a deep sleep with a new startup one.

Returns
Microseconds per tick with kPeriodFractionBits fraction bits.

pinWakesDeepSleep() #

bool kleidos::platform::sleep::pinWakesDeepSleep(int gpioPin)

Whether gpioPin can wake a deep sleep at all on this SoC.

True for an RTC GPIO (the EXT0 path) and, on a SoC with a digital-GPIO deep sleep wake, for a pin that path accepts. A pin this answers false for is refused by enablePinWakeup; asking first lets a caller refuse before it changes anything else. On a classic ESP32, GPIO19 is not an RTC GPIO.

Parameters
NameMeaning
gpioPinGPIO pin number.
Return values
ValueMeaning
trueenablePinWakeup can arm this pin.
falseIt cannot, or this is a host build.

powerManagementBuilt() #

bool kleidos::platform::system::powerManagementBuilt()

Whether this build runs ESP-IDF's power management (CONFIG_PM_ENABLE).

True on every board built with the idle floor (cpuIdleFloorBuilt) or with automatic light sleep (light_sleep::built); setCpuFrequencyMhz then hands the clock to ESP-IDF as a ceiling instead of switching it itself.

Return values
ValueMeaning
trueesp_pm is built in.
falseIt is not, or this is the native build.

powerUpReportedAsWatchdog() #

bool kleidos::platform::crash_record::powerUpReportedAsWatchdog(bool rtcRetained, uint32_t socResetCode)
nodiscardconstexpr

Whether a watchdog reset is a power-up the chip reported as one.

Parameters
NameMeaning
rtcRetainedThe RTC copy of the ring read valid, so the chip kept power.
socResetCodeThe SoC's own reset code (esp_rom_get_reset_reason(0)).
Return values
ValueMeaning
trueA whole-chip RTC-watchdog reset that followed a loss of power: no firmware died, so the boot records nothing.
falseAny other code, or the chip kept power: a watchdog death.

prepareClockForRadio() #

void kleidos::platform::system::prepareClockForRadio()

Put the core clock where a radio may start on it.

Called by every Wi-Fi and Bluetooth bring-up right before it initializes its driver. On the classic ESP32 a clock left on the other BBPLL setting than the base clock's (a 240 MHz boost still in force) would be held there for the radio's whole session, because setCpuFrequencyMhz refuses every move between the settings while a radio is up; this moves it to kleidos::platform::kCpuBaseMhz first (kleidos::platform::system::clockBeforeRadioMhz). A clock already on the base clock's setting is left alone, as is every clock on the ESP32-S3, which has no such split, and on the native build. Takes the same lock as setCpuFrequencyMhz. With a radio already up the PLL is where that radio found it and setCpuFrequencyMhz refuses the move, so the second radio of a session starts wherever the first one did. With the idle floor built it reads and moves the ceiling (setCpuFrequencyMhz).

radioUp() #

bool kleidos::platform::system::radioUp()

Whether a radio is up: the Wi-Fi driver or the Bluetooth controller.

From esp_wifi_init() to esp_wifi_deinit(), and from the Bluetooth controller's initialization until it is de-initialized. Either one holds a power-management lock of its own while it runs.

Return values
ValueMeaning
trueWi-Fi or Bluetooth is up.
falseNeither is, or this is the native build.

readBleTxPowerDbm() #

bool kleidos::platform::system::readBleTxPowerDbm(BleTxPowerType type, int8_t & dbm)

Read one of the controller's transmit power settings back.

Parameters
NameDirectionMeaning
typeinWhich setting to read.
dbmoutThe level in dBm (written only on success).
Return values
ValueMeaning
trueThe controller is enabled and reported a level this facade knows.
falseThe controller is not enabled, the level is unknown, or the native build.

readMacAddress() #

bool kleidos::platform::system::readMacAddress(MacAddressKind kind, uint8_t * output, size_t outputLength)

Read raw MAC address bytes for an interface.

Parameters
NameMeaning
kindWhich interface MAC to read.
outputBuffer for the raw MAC bytes (must be at least kMacAddressLength bytes).
outputLengthSize of output in bytes.
Return values
ValueMeaning
trueMAC bytes were written to output.
falseRead failed or output is smaller than kMacAddressLength.
Note
MacAddressKind::Bluetooth is derived from the base MAC by the SoC, so it reads the controller identity address without the BLE host being up — which is what makes it answerable from ADMIN_MODE, where BLE is deinitialized. Silicon with no Bluetooth radio reports false.

readMacAddressText() #

bool kleidos::platform::system::readMacAddressText(MacAddressKind kind, char * output, size_t outputLength)

Read a formatted MAC address string ("AA:BB:CC:DD:EE:FF").

Parameters
NameMeaning
kindWhich interface MAC to read.
outputBuffer for the text string (must be at least kMacAddressTextLength bytes).
outputLengthSize of output in bytes.
Return values
ValueMeaning
trueFormatted MAC string was written to output.
falseRead failed or output is smaller than kMacAddressTextLength.

reasonName() #

const char * kleidos::platform::crash_record::reasonName(Reason reason)

Stable lowercase token for reason ("fault", "abort", "task_wdt", ...).

Parameters
NameMeaning
reasonReason to name.
Returns
Pointer to a static string; "unknown" for Reason::Unknown.

recordAt() #

bool kleidos::platform::crash_record::recordAt(uint32_t index, Record & out)

Read one retained record, oldest first.

Parameters
NameDirectionMeaning
indexinZero-based index into the retained records; 0 is the oldest.
outoutReceives the record on success; untouched otherwise.
Return values
ValueMeaning
trueindex was in range and out was filled.
falseindex was out of range.

recordCount() #

uint32_t kleidos::platform::crash_record::recordCount()

Number of records currently retained.

Returns
min(crashCount(), ::kRecordCapacity).

releaseClassicBtRam() #

bool kleidos::platform::system::releaseClassicBtRam()

Hand the Classic-BT (BR/EDR) controller's reserved RAM back to the heap.

Kleidos is BLE-only, but a build with Bluetooth enabled still reserves the BR/EDR controller's DRAM until something releases it. Otherwise that reclaim happens only as a side effect of NimBLE coming up, so a session that goes straight to the admin portal never gets the memory back — and on classic ESP32 that is ~15 kB the WPA3 association needs. Call once, early, before any BT init.

Returns
true when memory was reclaimed by this call.

releaseFrameClock() #

void kleidos::platform::system::releaseFrameClock()

Release one frame hold.

The last release returns the clock to the one last asked for (requestedCpuFrequencyMhz) when the clock in force differs from it: a boost asked for during the hold keeps its clock. An unbalanced release is ignored. Takes the same lock as setCpuFrequencyMhz.

releaseMaxClock() #

void kleidos::platform::system::releaseMaxClock()

Release one maximum-clock hold.

The last release returns the clock to the one last asked for (requestedCpuFrequencyMhz), raised to a frame hold still in force. An unbalanced release is ignored. Takes the same lock as setCpuFrequencyMhz.

releaseUsbPadHolds() #

uint32_t kleidos::platform::sleep::releaseUsbPadHolds()

Release any RTC hold left on the USB PHY pads by a previous sleep.

app_main() calls it first of all, before the main-loop task is spawned, which is the earliest point Kleidos code runs. The hold isolateUsbPadsForDeepSleep latches lives in the always-on RTC domain, and ESP-IDF clears neither it nor RTC_CNTL_PAD_HOLD_REG at startup (esp_deep_sleep_wakeup_io_reset releases the EXT1 wake pins only), while the USB peripheral's own registers DO reset on the wake. On the LILYGO T-Deck and the M5Cardputer ADV the USB-Serial/JTAG is the only console and the only flash path, so the window in which the pads are still latched is kept as short as our own code can make it; only a power cycle clears the RTC domain otherwise.

Returns
How many hold-release calls succeeded, which is both pads on every SoC that has them, cold boot or not: ESP-IDF reports success for a pad that was never held, and no hold register reads back, so this counts calls and not pads that were actually latched. 0 on a SoC with no USB PHY or on a host build.

requestedCpuFrequencyMhz() #

uint32_t kleidos::platform::system::requestedCpuFrequencyMhz()

The clock last asked for, in MHz, without a frame hold's raise.

The clock the last setCpuFrequencyMhz call asked for, or the one prepareClockForRadio moved to: the clock in force whenever no frame hold raises it (holdFrameClock), narrowing under a radio aside. A caller that captures the clock to restore it later reads this one, not the clock in force (cpuFrequencyMhz), which during a heavy frame is the frame clock: restoring that would keep the frame clock after the frame. Before the first request it is the clock in force.

Returns
Clock in MHz; 0 on the native build.

resetByPowerOn() #

bool kleidos::platform::system::resetByPowerOn()
nodiscard

Whether the last reset was a power-on: the supply came up.

On a board that cuts its own power to sleep, the key or interrupt that switched it back on shows up as a power-on.

Returns
True for a power-on reset; false for every other cause and on the native build.

resetReason() #

const char * kleidos::platform::system::resetReason()

A stable, human-readable name for the last reset reason.

Wraps esp_reset_reason() and maps it to a compact uppercase token so diagnostics (and the QA serial console) can report why the SoC last reset without pulling in ESP-IDF headers. Stable tokens: "POWERON", "SW", "PANIC", "INT_WDT", "TASK_WDT", "WDT", "DEEPSLEEP", "BROWNOUT", "SDIO", "USB", "JTAG", "EXT", "UNKNOWN".

Returns
Pointer to a static string; "UNKNOWN" on the native build or an unrecognized cause.

restart() #

void kleidos::platform::system::restart()

Restart the device immediately (aborts on host); never returns.

Warning
[[noreturn]] — the SoC reboots. Save any critical state in NVS before calling. Call from the FSM task only; not safe from an ISR.

runningFirmware() #

Firmware kleidos::platform::crash_record::runningFirmware()

Identity of the image that adopted the ring on this boot.

Stamped by begin from the running application description. The panic path copies the version text from here (flash-mapped rodata is unreadable at that moment) and re-reads the ELF hash from the RAM copy ESP-IDF keeps for exactly that purpose, so a record's identity and this one agree whenever begin has run. Compare it against Record::firmware to tell a record produced by the running image from one carried across an OTA.

Returns
The running image's identity; both fields empty before begin or on the native build.

runningImageSizeBytes() #

uint32_t kleidos::platform::system::runningImageSizeBytes()

Size of the running application image, in bytes.

Read once from the image's own headers (its segments, padding, appended hash and signature block) and kept: the image cannot change while it runs, and the bootloader verified it before starting it, so no call hashes it again. Cheap enough to poll from any task after the first call, which reads a few headers from flash.

Returns
Image size in bytes; 0 when the headers cannot be read, or on the native build.

setCpuFrequencyMhz() #

bool kleidos::platform::system::setCpuFrequencyMhz(uint32_t mhz)

Request a new CPU frequency.

The single place a core frequency is applied, and therefore the place that keeps everything derived from the core clock true to it: the ROM busy-wait calibration and, on the SoCs whose FreeRTOS tick counts CPU cycles, the tick period (kleidos::platform::rtos::syncTickBase). Both happen only on the accepted path, and against the clock actually applied, so a request the silicon refused or this function narrowed leaves every derived timebase describing the clock that is in force.

On the classic ESP32 it also keeps the radio's clock source steady. That SoC runs 80 and 160 MHz off a 320 MHz BBPLL and 240 MHz off a 480 MHz one, and a change between the two disables the BBPLL and locks it again, which the Wi-Fi and Bluetooth radios run from: a Wi-Fi station loses its access point to a beacon timeout. So while Wi-Fi or Bluetooth is up, a request above the running setting's top is narrowed to that top (240 asked at 80 or 160 gives 160) and a request only the other setting can give is refused (80 or 160 asked at 240 keeps 240). The ESP32-S3 has no such split and is never narrowed.

Calls are serialized: the UI task's state entries and a worker's boost on the other core may both ask for a clock, and a classic-ESP32 change between the two PLL settings is a sequence (the CPU onto the crystal, the PLL off, relocked, the CPU back onto it) that a second change must not interleave. Each call reads the running clock, decides and applies under one lock, which makes it a blocking call: never from an ISR or a critical section.

The request is recorded as the clock asked for (requestedCpuFrequencyMhz). While a frame hold is in force (holdFrameClock) the clock applied is the request raised to the frame clock when it is below it, and the frame hold's release returns to the request, so a crypto boost and a heavy frame on different cores never undo each other.

On a board built with ESP-IDF's power management (powerManagementBuilt) the clock it applies is the ceiling ESP-IDF runs a busy core at (esp_pm_configure), with kleidos::platform::kCpuIdleFloorMhz as the idle floor where the floor is built (cpuIdleFloorBuilt) and the ceiling itself otherwise. ESP-IDF then makes every switch, and re-bases with each one what this function re-bases by hand on the other boards: the ROM busy-wait calibration, the classic-ESP32 tick period and, on both cores, the tick comparator already counting. The radio rule above reads the ceiling, not the instantaneous clock: a core drops to the crystal while idle, but the PLL stays at the ceiling's setting, and that is the setting a radio runs off. Switches to and from the crystal keep the PLL locked, so the floor itself never re-locks it.

Parameters
NameMeaning
mhzDesired frequency in MHz (e.g., 80, 160, 240).
Return values
ValueMeaning
trueFrequency was accepted and the CPU is now running at mhz, or at the frame clock above it while a frame hold is in force.
falseRequest was rejected (the native build, an unsupported value, or a radio that pins the clock where it is), or narrowed: read cpuFrequencyMhz for the clock in force.

setCpuIdleFloor() #

bool kleidos::platform::system::setCpuIdleFloor(bool enabled)

Turn the idle floor on or off, keeping the ceiling where it is.

The floor is on from the first setCpuFrequencyMhz call of a boot; until then every board runs at its boot clock, busy or idle. Turned off, the cores stay at the ceiling while idle as they do on a build without the floor, which is what a measurement compares the floor against. Takes the same lock as setCpuFrequencyMhz.

Parameters
NameDirectionMeaning
enabledinTrue to let idle cores drop to the floor.
Return values
ValueMeaning
trueThe floor is now as asked.
falseNo floor is built (or the native build), or ESP-IDF refused the configuration; nothing changed.

setFrameClockEnabled() #

bool kleidos::platform::system::setFrameClockEnabled(bool enabled)

Switch the frame clock on or off, for a measurement of what it buys.

On from boot. Off, a frame hold raises nothing and heavy frames run at the clock asked for; holds already taken are re-applied at once. Only the debug console turns it off, for a measurement. Not persisted. Takes the same lock as setCpuFrequencyMhz.

Parameters
NameDirectionMeaning
enabledinTrue to let a frame hold raise the clock.
Return values
ValueMeaning
trueThe frame clock is now as asked.
falseThe native build; nothing changed.

slowClockSleepCount() #

uint32_t kleidos::platform::sleep::slowClockSleepCount()
nodiscard

Light sleeps noted this boot.

Returns
The count, zero at every boot.

slowClockSleptMicros() #

uint64_t kleidos::platform::sleep::slowClockSleptMicros()
nodiscard

Total light-sleep time noted this boot.

Returns
Microseconds, zero at every boot.

socResetCode() #

uint32_t kleidos::platform::system::socResetCode()

The SoC's own reset code for the PRO CPU, before ESP-IDF maps it.

resetReason folds several hardware causes into one token: on a classic ESP32, "WDT" covers the RTC watchdog resetting the digital core (0x09), the CPU (0x0D) and the whole chip, RTC domain included (0x10, the code the ROM prints as RTCWDT_RTC_RESET). This raw code tells them apart. It is the value of esp_rom_get_reset_reason(0), the number the ROM boot banner prints as rst:0x...; its meaning is the SoC's soc_reset_reason_t.

Returns
The SoC reset code; 0 on the native build.

sourceName() #

const char * kleidos::platform::slow_clock::sourceName()

Short name of the oscillator the RTC slow clock runs from.

Returns
"rc_slow" (the ~136 kHz RC), "rc_fast_d256" (the ~17.5 MHz RC divided by 256), "xtal32k", or "other"; "host" on the native build.

stats() #

Stats kleidos::platform::light_sleep::stats()

The idle-wait counters since boot.

Returns
A copy of the counters.

suppressRomLogOnNextWake() #

void kleidos::platform::sleep::suppressRomLogOnNextWake()

Keep the ROM bootloader silent on the next deep-sleep wake.

The ROM prints its boot banner on UART0's TX pad on every reset unless told not to. On a board that wires that pad to a peripheral's input, the banner is traffic the peripheral did not ask for: on the LILYGO T-Deck it is the GPS receiver's RX line, and a u-blox M10 in software standby wakes on any edge there, so every wake would undo the park the sleep had proven. ESP-IDF's esp_deep_sleep_disable_rom_logging sets a bit in an RTC store register that the ROM reads on a deep-sleep wake only. It burns nothing: the eFuse that silences the ROM on every boot is a separate, irreversible decision, and a cold boot still prints. The banner also leaves on the USB-Serial/JTAG, so a console reading the wake sees the application's first line instead.

ticks() #

uint64_t kleidos::platform::slow_clock::ticks()

Raw RTC slow-clock ticks.

The counter behind the RTC timer, with no period applied: it runs through deep sleep and software resets and restarts only when the chip loses power.

Returns
Ticks since the last power-on; the native build returns microseconds of the monotonic clock (one tick per microsecond).

timerWakeAtSleep() #

TimerWakeAtSleep kleidos::platform::sleep::timerWakeAtSleep(uint64_t deadlineUs, uint64_t benchAfterUs, uint64_t nowUs)
nodiscardconstexpr

The timer wake of a deep sleep that starts at nowUs.

Parameters
NameMeaning
deadlineUsThe pending request's deadline (timerWakeDeadline), or kNoTimerWake.
benchAfterUsA bench wake's length from sleep entry, or kNoTimerWake.
nowUsMonotonic microseconds at sleep entry.
Returns
Dropped when neither is pending. Otherwise armed for the sooner of the bench length and the deadline's time left, the time left raised to kMinTimerWakeUs (a deadline already due wakes the board at once), and the result capped at kMaxTimerWakeUs.

timerWakeAvailable() #

bool kleidos::platform::sleep::timerWakeAvailable()
nodiscard

Whether this board's production deep sleep takes a timer wake.

Return values
ValueMeaning
trueenableTimerWakeup records a deadline on this board.
falseOnly a reset ends this board's deep sleep, or a host build.

timerWakeDeadline() #

uint64_t kleidos::platform::sleep::timerWakeDeadline(uint64_t nowUs, uint64_t delayUs)
nodiscardconstexpr

The deadline of a timer wake asked for delayUs after nowUs.

Parameters
NameMeaning
nowUsMonotonic microseconds when the request is made.
delayUsHow long after nowUs the board must wake, in microseconds.
Returns
nowUs + delayUs, saturated at kLatestTimerWake; never kNoTimerWake.

timerWakeRemainingUs() #

uint64_t kleidos::platform::sleep::timerWakeRemainingUs(uint64_t deadlineUs, uint64_t nowUs)
nodiscardconstexpr

Microseconds from nowUs to a deadline.

Parameters
NameMeaning
deadlineUsA deadline from timerWakeDeadline, or kNoTimerWake.
nowUsMonotonic microseconds now.
Returns
The time left; 0 when nothing is pending or the deadline is not after nowUs.

uptimeMs() #

uint64_t kleidos::platform::system::uptimeMs()

Milliseconds since boot, 64-bit, so it does not wrap.

Wraps the 64-bit high-resolution timer so uptime never wraps at the 32-bit boundary the millis facade uses.

Returns
Milliseconds since boot; 0 on the native build.

usbHostAttached() #

bool kleidos::platform::light_sleep::usbHostAttached()

Whether a USB host is attached to the chip's own USB port.

The ESP32-S3's USB-Serial/JTAG port, by the start-of-frame packets a host sends every millisecond. ESP-IDF takes the port's pad down for every light sleep, so a host would see the board come and go; the idle rule therefore keeps the chip awake while one is attached. Without a USB port of its own (the classic ESP32, whose console is a separate USB-UART bridge), and on a build without automatic light sleep, this is false.

Return values
ValueMeaning
trueA host is attached and polling the port.

usbPadAction() #

UsbPadAction kleidos::platform::sleep::usbPadAction(int pad, std::span< const int > wakePins, std::span< const int > heldPads)
nodiscardconstexpr

Decide what a deep sleep does with one USB PHY pad.

There is no board opt-out: the pad is a property of the SoC, identical on every ESP32-S3, and the two claims below cover every case a board can actually have. Both are tested, so the reason returned names the one a reader has to act on.

Parameters
NameMeaning
padGPIO number of the USB PHY pad under test.
wakePinsEvery pin that can end a sleep: the board's deep-sleep and idle wake sets and every pin armed through the sleep facade this boot, as one list.
heldPadsPads the board latched on purpose for the sleep.
Returns
The action, carrying the reason it was chosen.

usbPadActionName() #

const char * kleidos::platform::sleep::usbPadActionName(UsbPadAction action)
nodiscardconstexpr

A short name for an action, for a log line or a console reply.

Parameters
NameMeaning
actionThe action to name.
Returns
A static string; never nullptr.

waiting() #

bool kleidos::platform::light_sleep::waiting()

Whether an idle wait is in progress (on a light-sleep build, the hold is let go).

Return values
ValueMeaning
trueAn idle wait is in progress.

wakeCause() #

WakeCause kleidos::platform::sleep::wakeCause()

Return the cause of the deep-sleep wake that started the current boot.

Read once (captureBootWake) and kept, so a light sleep later in the boot leaves it as it was.

Return values
ValueMeaning
WakeCause::UndefinedPower-on or reset (not a deep-sleep wake).
WakeCause::Ext0EXT0 single-pin wake.
WakeCause::Ext1EXT1 pin-mask wake.
WakeCause::TimerRTC timer wake.
WakeCause::TouchpadTouchpad wake.
WakeCause::UlpULP co-processor wake.
WakeCause::GpioGPIO (light/deep-sleep) wake.
WakeCause::UartUART activity wake.
WakeCause::WifiWi-Fi wake.
WakeCause::CoProcessorCo-processor wake.
WakeCause::OtherA deep-sleep wake whose cause is unrecognized.

wakeCauseName() #

const char * kleidos::platform::sleep::wakeCauseName(WakeCause cause)

Human-readable name for a wake cause.

Parameters
NameMeaning
causeWake cause value to name.
Returns
Pointer to a static string (e.g., "Ext0", "Timer").

wokeFromDeepSleep() #

bool kleidos::platform::sleep::wokeFromDeepSleep()

True when the current boot followed a deep-sleep wake.

Decided by the reset reason that started the boot (a deep-sleep reset), so neither a light sleep since nor the order of the calls changes it. Equal to wakeCause() != WakeCause::Undefined.

Return values
ValueMeaning
trueThe boot followed a deep-sleep wake.
falseThe boot followed a power-on, a software restart, a panic, a watchdog or any other reset; or this is a host build.

writePowerManagementStats() #

bool kleidos::platform::system::writePowerManagementStats(TextSink sink)

Write ESP-IDF's power-management statistics through sink.

Every power-management lock with its type and whether it is held; with the profiling counters built in (CONFIG_PM_PROFILING, the debug builds of the boards that build power management) also the time each lock has been held and the time spent in each mode since boot, the idle floor's and light sleep's among them, and the light sleeps taken and refused. The text is ESP-IDF's own (esp_pm_dump_locks).

Parameters
NameDirectionMeaning
sinkinReceiver of the text.
Return values
ValueMeaning
trueThe statistics were written.
falseNo power management is built (powerManagementBuilt, or the native build); nothing was written.

Back to the top

Variable Documentation

kCpuBaseMhz #

uint32_t kleidos::platform::kCpuBaseMhz
inlineconstexpr

Core clock every board runs at whenever it is not doing crypto or drawing a heavy frame: every FSM state names it on entry, and a boost returns to it. The lowest clock both SoCs take off the PLL, so the APB bus, and every peripheral clocked from it, runs at the same 80 MHz it does at the higher clocks.

kCpuBoostMaxHoldMs #

uint32_t kleidos::platform::kCpuBoostMaxHoldMs
inlineconstexpr

Longest a latched boost may outlive the scope that raised it before the per-tick sweep takes it down. The boosted unlock phase is a small fraction of this — key derivation plus the list decrypt plus two frames — so the bound never truncates a legitimate hold; it exists so that a route which ends without naming a frequency costs a bounded amount of battery.

kCpuFrameMhz #

uint32_t kleidos::platform::kCpuFrameMhz
inlineconstexpr

Core clock a heavy frame (a full-frame compose or a popup card) is composed and blitted at, through a FrameBoostGuard. The highest clock of the base clock's PLL setting on the classic ESP32 (320 MHz divided by two), so a frame never re-locks the PLL a radio runs off.

kCpuIdleFloorMhz #

uint32_t kleidos::platform::kCpuIdleFloorMhz
inlineconstexpr

Clock the cores drop to while both are idle, on a board built with the idle floor (system::cpuIdleFloorBuilt): the 40 MHz crystal every board carries, divided by one. Off the PLL, so the APB bus drops with it; the peripherals that need the APB clock at 80 MHz hold it there while they run (ESP-IDF's power-management locks), and the ones that run on through an idle stretch are clocked from a source that does not follow it.

kElfSha256ShortChars #

size_t kleidos::platform::system::kElfSha256ShortChars
constexpr

Hex characters in the short ELF SHA-256 text (elfSha256ShortText).

Must equal CONFIG_APP_RETRIEVE_LEN_ELF_SHA (sdkconfig.defaults.kleidos_ble); a static_assert in system.cpp enforces that on the device build.

kElfShaTextLength #

uint32_t kleidos::platform::crash_record::kElfShaTextLength
constexpr

Hex characters of the app ELF SHA-256 kept per record, plus the NUL.

The value is the prefix ESP-IDF keeps as a DRAM string (CONFIG_APP_RETRIEVE_LEN_ELF_SHA, which the build pins to 16), which is the only form readable with the flash cache off. 16 hex characters are 64 bits of a hash taken over the whole ELF, so it separates any two builds that will ever exist side by side.

kLatestTimerWake #

uint64_t kleidos::platform::sleep::kLatestTimerWake
inlineconstexpr

The latest deadline a request can name: one below kNoTimerWake, so a delay too long to add still names a moment instead of reading as none.

kMaxCycles #

uint32_t kleidos::platform::slow_clock::kMaxCycles
inlineconstexpr

Most slow cycles one measurement counts. The calibration unit times out after the cycle count shifted left by 12 crystal cycles on RC_FAST/256, and that threshold field holds 25 bits, so 8190 is the longest count every source accepts.

kMaxTimerWakeUs #

uint64_t kleidos::platform::sleep::kMaxTimerWakeUs
inlineconstexpr

The longest timer any deep sleep arms, in microseconds (24 h): a longer request wakes the board at this length and its caller asks again on the next boot. It is the longest any caller asks for (the SoC clock backend clamps its countdown and alarm wakes to it, and the debug console caps its timer at 86,400 s) and far inside every SoC's LP-timer range, so ESP-IDF accepts every length the facade arms.

kMinTimerWakeUs #

uint64_t kleidos::platform::sleep::kMinTimerWakeUs
inlineconstexpr

The shortest timer a pending deadline arms, in microseconds (1 s): what a deadline already due at sleep entry wakes on, so ESP-IDF's timer is never handed 0 or a moment its own sleep entry has already passed. The SoC clock backend clamps its countdown and alarm wakes to it as well, and no production caller asks for a shorter wake.

kNativeAppVersion #

const char* kleidos::platform::system::kNativeAppVersion
constexpr

Version reported by appVersion on the native build (no image descriptor).

A valid three-field semver on purpose: the OTA logic under test parses it with the same strict parser the firmware uses, which fails closed on anything else.

kNoTimerWake #

uint64_t kleidos::platform::sleep::kNoTimerWake
inlineconstexpr

No timer wake pending: the deadline of a request never made or cancelled, and the bench length of a sleep that asked for none.

kNotPllSourced #

uint32_t kleidos::platform::system::kNotPllSourced
inlineconstexpr

CpuClockSource::pllMhz of a clock that does not come off the PLL (the crystal or the internal oscillator).

kPllTopCpuDivider #

uint32_t kleidos::platform::system::kPllTopCpuDivider
inlineconstexpr

Divider that takes a PLL setting to the highest core clock it yields: the 320 MHz setting gives 160 MHz and the 480 MHz one 240 MHz.

kSocResetSysRtcWdt #

uint32_t kleidos::platform::crash_record::kSocResetSysRtcWdt
inlineconstexpr

SoC reset code of an RTC-watchdog reset of the whole chip, RTC domain included (RESET_REASON_SYS_RTC_WDT, the ROM's RTCWDT_RTC_RESET); the same value on the classic ESP32 and the ESP32-S3.

Back to the top