Kleidos API Search

In development. It changes without notice.

Topic

Diagnostics

What a board reports of itself: the log's queue, memory and tasks, the time spent drawing, and an estimate of what it draws.

Part What it reports In which builds
Queued log Messages written by a task of their own Those that ask for it
Memory and tasks The heap and the time since boot; each task's stack and share of the CPU The heap, all; the tasks, those built to measure
Drawing Frames, the time to send one, the gaps between them Those built to measure
Power meter The current of each state, of a session, and of the last sleep All
Telemetry Chosen values sampled while somebody asks All; it costs nothing while nobody does

The power meter is not a measurement on most boards. Where the power chip has a current sensor (Core2 v1.3, M5StickC Plus 1.1, M5StickC Plus SE) it integrates what the chip reads. On the others it multiplies the time in each state by a modeled current, and says so beside the figure. What a board draws by an instrument is at kleidos.dev/measurements.

See also
Platform Memory & Errors, Power, Battery & Parking

Files

file src/diag/core_diagnostics.h
Opt-in dual-core diagnostics helpers (watchdog, stack, heap, core).
file src/diag/log_task.h
Queued logger task that moves ESP_LOGx formatting off the hot path.
file src/diag/power_meter.h
On-device power meter: per-state consumption, session charge and the last deep sleep's average current, each with a quality label.
file src/diag/power_meter_logic.h
Pure arithmetic of the on-device power meter (host-tested).
file src/diag/power_profile.h
Per-board constant data the power meter works from.
file src/diag/power_run_logic.h
Timing of a scripted power run: a fixed sequence of timed phases the board steps through on its own (host-tested).
file src/diag/render_profile.h
Render-loop profiling counters (debug builds only).
file src/diag/runtime_stats.h
Lightweight FreeRTOS runtime/heap profiling helpers.
file src/diag/telemetry_service.cpp
Implementation of the on-demand telemetry service.
file src/diag/telemetry_service.h
On-demand, zero-idle-cost telemetry sampling service.

Classes

struct kleidos::diag::power_meter::StateRoles
Application-state indices the meter treats specially. More about kleidos::diag::power_meter::StateRoles
struct kleidos::diag::power_meter::Snapshot
Published state of the meter. More about kleidos::diag::power_meter::Snapshot
struct kleidos::diag::power_meter::StateFigure
One state's figures, as diagnostics report them. More about kleidos::diag::power_meter::StateFigure
struct kleidos::diag::power_meter::BudgetLine
One phase's figure beside the value the board is expected to hold there. More about kleidos::diag::power_meter::BudgetLine
struct kleidos::diag::power_meter::IntervalFigures
Figures the meter booked over one measuring interval (openInterval .. closeInterval). More about kleidos::diag::power_meter::IntervalFigures
struct kleidos::diag::power_meter::logic::ModeSignature
Everything the current model depends on, read from RAM each loop tick. More about kleidos::diag::power_meter::logic::ModeSignature
struct kleidos::diag::power_meter::logic::ModelCoefficients
Per-board coefficients of the additive current model, in microamps. More about kleidos::diag::power_meter::logic::ModelCoefficients
struct kleidos::diag::power_meter::logic::Segment
One integrated piece of time: its length and the charge in it. More about kleidos::diag::power_meter::logic::Segment
class kleidos::diag::power_meter::logic::ChargeIntegrator
Integrates sampled current over 64-bit time with no float drift. More about kleidos::diag::power_meter::logic::ChargeIntegrator
class kleidos::diag::power_meter::logic::PeakWindow
Turns integrated pieces into 1 s window means. More about kleidos::diag::power_meter::logic::PeakWindow
struct kleidos::diag::power_meter::logic::StateBucket
Time and charge booked against one application state. More about kleidos::diag::power_meter::logic::StateBucket
class kleidos::diag::power_meter::logic::ModeAccountant
Books time (and, on modeled boards, charge) per application state. More about kleidos::diag::power_meter::logic::ModeAccountant
struct kleidos::diag::power_meter::logic::Estimate
A figure with its interval and quality. More about kleidos::diag::power_meter::logic::Estimate
struct kleidos::diag::power_meter::logic::OcvTable
Rest-voltage table of a cell: kOcvPoints millivolt values, ascending. More about kleidos::diag::power_meter::logic::OcvTable
struct kleidos::diag::power_meter::logic::VoltageDropInput
Inputs of a rest-voltage sleep estimate. More about kleidos::diag::power_meter::logic::VoltageDropInput
struct kleidos::diag::power_meter::logic::SleepSnapshot
What the meter captures just before a deep sleep. More about kleidos::diag::power_meter::logic::SleepSnapshot
struct kleidos::diag::power_meter::logic::SessionRecord
One closed awake session (≤ 64 B encoded). More about kleidos::diag::power_meter::logic::SessionRecord
struct kleidos::diag::power_meter::PowerBudgets
Expected values of one board, from its variant.h. More about kleidos::diag::power_meter::PowerBudgets
struct kleidos::diag::power_meter::PowerProfile
Constant power description of one board. More about kleidos::diag::power_meter::PowerProfile
struct kleidos::diag::power_run::Phase
One timed phase of a plan. More about kleidos::diag::power_run::Phase
struct kleidos::diag::power_run::Plan
A run: its phases, in order, and whether it waits for USB to go away first. More about kleidos::diag::power_run::Plan
class kleidos::diag::power_run::Sequencer
Steps a plan through its phases on a monotonic clock. More about kleidos::diag::power_run::Sequencer
struct kleidos::diag::render::Sample
Snapshot of render-loop profiling counters. More about kleidos::diag::render::Sample
struct kleidos::diag::RuntimeSnapshot
Result of a single sampling pass. All numbers are absolute counts. More about kleidos::diag::RuntimeSnapshot
struct kleidos::diag::telemetry::Config
Sampling configuration passed to start. More about kleidos::diag::telemetry::Config
struct kleidos::diag::telemetry::Sample
One recorded measurement. More about kleidos::diag::telemetry::Sample

Typedefs

usingkleidos::diag::telemetry::SampleFn
Channel sampling callback.

Enumerations

enum class kleidos::diag::power_meter::Basis : uint8_t { kleidos::diag::power_meter::Basis::Measured , kleidos::diag::power_meter::Basis::Usb , kleidos::diag::power_meter::Basis::Model }
What a current figure rests on. More about kleidos::diag::power_meter::Basis
enum class kleidos::diag::power_meter::Budget : uint8_t { kleidos::diag::power_meter::Budget::PinEntry, kleidos::diag::power_meter::Budget::BlePeak, kleidos::diag::power_meter::Budget::WifiPeak, kleidos::diag::power_meter::Budget::StandbyLocked, kleidos::diag::power_meter::Budget::DeepSleep }
The phases the meter reports a figure for, each beside the value the board is expected to hold there. More about kleidos::diag::power_meter::Budget
enum class kleidos::diag::power_meter::logic::Quality : uint8_t { kleidos::diag::power_meter::logic::Quality::Measured, kleidos::diag::power_meter::logic::Quality::Calibrated, kleidos::diag::power_meter::logic::Quality::Modeled, kleidos::diag::power_meter::logic::Quality::Bound, kleidos::diag::power_meter::logic::Quality::Unknown }
How a figure was obtained, best first. More about kleidos::diag::power_meter::logic::Quality
enum class kleidos::diag::power_meter::logic::Verdict : uint8_t { kleidos::diag::power_meter::logic::Verdict::Pass , kleidos::diag::power_meter::logic::Verdict::Fail , kleidos::diag::power_meter::logic::Verdict::Unknown }
Outcome of checking a figure against an expected value. More about kleidos::diag::power_meter::logic::Verdict
enum class kleidos::diag::power_meter::logic::BleMode : uint8_t { kleidos::diag::power_meter::logic::BleMode::Off , kleidos::diag::power_meter::logic::BleMode::Adv , kleidos::diag::power_meter::logic::BleMode::Connected , kleidos::diag::power_meter::logic::BleMode::Typing }
BLE radio activity, as the current model distinguishes it. More about kleidos::diag::power_meter::logic::BleMode
enum class kleidos::diag::power_meter::logic::WifiMode : uint8_t { kleidos::diag::power_meter::logic::WifiMode::Off , kleidos::diag::power_meter::logic::WifiMode::Ap , kleidos::diag::power_meter::logic::WifiMode::ApClient , kleidos::diag::power_meter::logic::WifiMode::Sta }
Wi-Fi radio activity, as the current model distinguishes it. More about kleidos::diag::power_meter::logic::WifiMode
enum class kleidos::diag::power_meter::SleepKind : uint8_t { kleidos::diag::power_meter::SleepKind::EspDeepSleep , kleidos::diag::power_meter::SleepKind::PowerCut , kleidos::diag::power_meter::SleepKind::PowerCutWithTicks }
What entering "deep sleep" does to the ESP32 on a board. More about kleidos::diag::power_meter::SleepKind
enum class kleidos::diag::power_run::RunState : uint8_t { kleidos::diag::power_run::RunState::Idle, kleidos::diag::power_run::RunState::WaitingForBattery, kleidos::diag::power_run::RunState::Settling, kleidos::diag::power_run::RunState::Measuring, kleidos::diag::power_run::RunState::Done, kleidos::diag::power_run::RunState::Aborted }
Where a run is. More about kleidos::diag::power_run::RunState
enum class kleidos::diag::power_run::Event : uint8_t { kleidos::diag::power_run::Event::None, kleidos::diag::power_run::Event::EnterPhase, kleidos::diag::power_run::Event::OpenFigures, kleidos::diag::power_run::Event::ClosePhase, kleidos::diag::power_run::Event::Finished, kleidos::diag::power_run::Event::BatteryTimeout }
What the caller has to do now. More about kleidos::diag::power_run::Event
enum class kleidos::diag::telemetry::StopStatus : uint8_t { kleidos::diag::telemetry::StopStatus::Idle , kleidos::diag::telemetry::StopStatus::Stopped , kleidos::diag::telemetry::StopStatus::Timeout , kleidos::diag::telemetry::StopStatus::Busy }
Outcome of a stop request. More about kleidos::diag::telemetry::StopStatus

Functions

boolkleidos::diag::enableIdle1Watchdog () noexcept
Watch the Core 1 (APP_CPU) idle task with the Task Watchdog Timer.
voidkleidos::diag::logStackHighWaterMark (const char *tag) noexcept
Log the calling task's stack high-water mark via the platform logger.
voidkleidos::diag::logHeapStats (const char *tag) noexcept
Log free heap and largest free block (DRAM, 8-bit-capable).
voidkleidos::diag::logCurrentCore (const char *tag) noexcept
Log the calling core id.
boolkleidos::diag::log::begin (kleidos::platform::rtos::Core core=kleidos::platform::rtos::Core::ProCpu, kleidos::platform::rtos::Priority priority=2)
Install the queued logger.
voidkleidos::diag::log::shutdown ()
Restore the default vprintf, drain pending messages, then stop the task.
uint32_tkleidos::diag::log::droppedCount ()
Total number of messages dropped because the queue was full since boot.
boolkleidos::diag::log::running ()
Whether the queued logger is installed and draining.
const char *kleidos::diag::power_meter::basisName (Basis b)
Console token of a basis.
const char *kleidos::diag::power_meter::budgetName (Budget b)
Short name of a phase, as diagnostics print it.
voidkleidos::diag::power_meter::begin (PowerManager &pm, const PowerProfile &profile, const StateRoles &roles)
Start the meter: probe what the board measures, estimate the sleep that preceded this boot, and open the accounting at time 0.
voidkleidos::diag::power_meter::tick (uint64_t nowMs, const logic::ModeSignature &sig)
Loop hook: close the open interval on a signature change and take a current sample when one is due.
voidkleidos::diag::power_meter::prepareForSleep ()
Close the session and store the pre-sleep snapshot in RTC memory.
Snapshotkleidos::diag::power_meter::snapshot ()
Copy of the latest published state; safe from any task.
StateFigurekleidos::diag::power_meter::stateFigure (uint8_t state, uint64_t nowMs)
Figures of one state, the open interval included.
uint64_tkleidos::diag::power_meter::accountedMs (uint64_t nowMs)
Total time accounted since boot, the open interval included.
BudgetLinekleidos::diag::power_meter::budgetLine (Budget b, uint64_t nowMs)
The meter's figure for one phase, beside its expected value if it has one.
voidkleidos::diag::power_meter::openInterval ()
Open a measuring interval at this instant (closing any open one).
IntervalFigureskleidos::diag::power_meter::closeInterval ()
Close the open interval and return its figures.
IntervalFigureskleidos::diag::power_meter::intervalFigures (uint64_t nowMs)
Figures of the open interval so far, without closing it or sampling.
boolkleidos::diag::power_meter::measuresCurrent ()
Whether the board measures current (the meter runs in measured mode).
boolkleidos::diag::power_meter::usbPresent ()
Whether USB powers the board right now, from a fresh reading.
boolkleidos::diag::power_meter::readLoadMilliamps (float &milliamps)
Take a fresh load-current reading (the load_ma telemetry channel).
uint32_tkleidos::diag::power_meter::logic::modelCurrentUa (const ModeSignature &m, const ModelCoefficients &k)
Modeled current of one mode signature.
Qualitykleidos::diag::power_meter::logic::modelQuality (bool calibrated)
Quality label of a model figure.
Estimatekleidos::diag::power_meter::logic::measuredEstimate (int32_t microamps)
Interval around a measured current: ±(1 mA + 5 %).
Estimatekleidos::diag::power_meter::logic::modelEstimate (uint32_t microamps, bool calibrated)
Interval around a modeled current: ±50 % seed, ±20 % calibrated.
Estimatekleidos::diag::power_meter::logic::sleepFloorEstimate (uint32_t declaredUa, bool calibrated)
Estimate of the deep-sleep floor from the figure the variant declares.
Verdictkleidos::diag::power_meter::logic::judge (const Estimate &e, uint32_t limitUa)
Judge a figure against a limit.
boolkleidos::diag::power_run::cpuClockValid (uint32_t mhz)
Whether a phase may hold the core clock mhz.
uint64_tkleidos::diag::power_run::planDurationMs (const Plan &plan)
Length of a plan: the sum of its phases' dwell times.
boolkleidos::diag::power_run::planValid (const Plan &plan)
Whether a plan can run.
const char *kleidos::diag::power_run::runStateName (RunState s)
Console token of a run state.
voidkleidos::diag::render::onTimerHandlerEnter ()
Call right before the render tick. Records the gap since the previous tick and bumps frameCount.
voidkleidos::diag::render::onFlushEnter ()
Call right before flushCb does its bus traffic. Captures the start timestamp used by onFlushExit() to compute latency.
voidkleidos::diag::render::onFlushExit ()
Call right after flushCb has pushed its colors. Updates lastFlushUs / maxFlushUs and bumps flushCount.
Samplekleidos::diag::render::snapshot ()
Atomic snapshot of the counters. Safe to call from any task.
voidkleidos::diag::render::reset ()
Reset all counters to zero. Useful for measurement runs.
size_tkleidos::diag::render::formatReport (char *out, size_t outLen)
Format a multi-line plain-text dump. Returns bytes written (excl. NUL).
RuntimeSnapshotkleidos::diag::snapshot ()
Capture a coarse-grained snapshot. Always available, even in release builds — it has no measurable cost.
size_tkleidos::diag::formatTaskTable (char *out, size_t outLen)
Render a multi-line table of every task with its core, priority, state, stack high-water mark, and CPU runtime percentage since the previous call.
voidkleidos::diag::recordLoopTickUs (uint32_t deltaUs)
Record one loop-tick interval in microseconds.
uint32_tkleidos::diag::loopTickLastUs ()
Most recent loop-tick interval in microseconds (0 before the first tick).
uint32_tkleidos::diag::loopTickMaxUsAndReset ()
Peak loop-tick interval since the last read, then reset the peak.
boolkleidos::diag::telemetry::registerChannel (const char *name, SampleFn fn, void *ctx)
Register a sampling channel.
size_tkleidos::diag::telemetry::channelCount ()
Number of channels currently registered.
const char *kleidos::diag::telemetry::channelName (size_t i)
Access a registered channel name by index, in registration order.
boolkleidos::diag::telemetry::start (const Config &config)
Start sampling.
StopStatuskleidos::diag::telemetry::stop (uint32_t timeoutMs=kStopWaitForever)
Stop sampling and release all per-run resources, with a bounded wait.
StopStatuskleidos::diag::telemetry::reapPendingStop ()
Finish a teardown that a timed-out stop left pending.
boolkleidos::diag::telemetry::isRunning ()
Whether a telemetry run currently owns the service.
uint32_tkleidos::diag::telemetry::activePeriodMs ()
Sampling period of the active run.
size_tkleidos::diag::telemetry::copySamples (Sample *out, size_t maxSamples)
Copy an oldest-first snapshot of the recorded samples.
size_tkleidos::diag::telemetry::copyRecentSamples (Sample *out, size_t maxSamples)
Copy an oldest-first snapshot of the newest recorded samples.
size_tkleidos::diag::telemetry::droppedSamples ()
Number of samples overwritten (dropped) since the ring was allocated.
size_tkleidos::diag::telemetry::sampleCount ()
Number of samples currently held in the ring.
voidkleidos::diag::telemetry::serviceFromUiTask ()
Service the telemetry service from the FSM/main-loop task (Core 1).
size_tkleidos::diag::telemetry::selectChannels (const char *csv, uint8_t *out, size_t maxOut)
Resolve a CSV channel list to registry indices.
voidkleidos::diag::telemetry::ringAppend (const Sample &sample)
Append one sample to the ring (production write path).
voidkleidos::diag::telemetry::appendSampleForTest (const Sample &sample)
Native-test alias for ::ringAppend.
boolkleidos::diag::telemetry::resetForTest ()
Reset registry and ring state, (re)allocating an empty ring.

Variables

constexpr size_tkleidos::diag::power_meter::kBudgetCount
Number of Budget values.
constexpr size_tkleidos::diag::power_meter::logic::kBleModeCount
Number of BleMode values.
constexpr size_tkleidos::diag::power_meter::logic::kWifiModeCount
Number of WifiMode values.
constexpr size_tkleidos::diag::power_meter::logic::kMaxStates
Number of per-state accounting buckets (one per application state).
constexpr std::array< uint16_t, logic::kOcvPoints >kleidos::diag::power_meter::kGenericLipoOcvMv
Rest voltage of a generic 1-cell LiPo at 0, 10, ..., 100 % SoC (mV).
constexpr size_tkleidos::diag::power_run::kMaxPhases
Most phases a plan may hold (the device keeps one result per phase).
constexpr uint8_tkleidos::diag::power_run::kMaxBacklightPct
Highest backlight level a phase may hold, %.
constexpr uint64_tkleidos::diag::power_run::kBatteryConfirmMs
USB must stay away this long before a plan that waits for battery starts.
constexpr uint64_tkleidos::diag::power_run::kBatteryWaitMaxMs
A plan that waits for battery gives up when USB is still there after this long.
constexpr std::array< uint16_t, 3 >kleidos::diag::power_run::kForcedCpuMhz
Core clocks a phase may hold, MHz: the PLL-sourced settings both SoCs run.
constexpr size_tkleidos::diag::telemetry::kMaxChannels
constexpr size_tkleidos::diag::telemetry::kTelemetryRingSamples
Ring-buffer capacity in samples (fixed; ~6 KB — fits the no-PSRAM boards).
constexpr uint32_tkleidos::diag::telemetry::kStopWaitForever
stop timeout sentinel: block until the sampler has actually exited.
constexpr uint32_tkleidos::diag::telemetry::kStopPollSliceMs
Longest single sleep the sampler takes between stop-request checks.
constexpr size_tkleidos::diag::telemetry::kSampleQueueDepth
Depth of the sampler-to-UI tick queue.

Records kept across a deep sleep

enum class kleidos::diag::power_meter::logic::SleepMethod : uint8_t { kleidos::diag::power_meter::logic::SleepMethod::None, kleidos::diag::power_meter::logic::SleepMethod::Coulomb, kleidos::diag::power_meter::logic::SleepMethod::VoltageDrop, kleidos::diag::power_meter::logic::SleepMethod::Bound, kleidos::diag::power_meter::logic::SleepMethod::Model }
How the previous sleep's figure was obtained. More about kleidos::diag::power_meter::logic::SleepMethod
constexpr uint8_tkleidos::diag::power_meter::logic::kSnapshotVersion
SleepSnapshot wire version.
constexpr uint8_tkleidos::diag::power_meter::logic::kRecordVersion
constexpr size_tkleidos::diag::power_meter::logic::kSnapshotBytes
Encoded size of a SleepSnapshot (version + payload + CRC-32).
constexpr size_tkleidos::diag::power_meter::logic::kRecordBytes
Encoded size of a SessionRecord (version + payload + CRC-32).
const char *kleidos::diag::power_meter::logic::sleepMethodName (SleepMethod m)
Console token of a sleep method.
size_tkleidos::diag::power_meter::logic::encodeSnapshot (const SleepSnapshot &s, uint8_t *buf, size_t cap)
Encode a snapshot as [ver][payload LE][crc32 LE].
boolkleidos::diag::power_meter::logic::decodeSnapshot (const uint8_t *buf, size_t len, SleepSnapshot &out)
Decode a snapshot, checking version, length and CRC.
size_tkleidos::diag::power_meter::logic::encodeRecord (const SessionRecord &r, uint8_t *buf, size_t cap)
Encode a session record as [ver][payload LE][crc32 LE].
boolkleidos::diag::power_meter::logic::decodeRecord (const uint8_t *buf, size_t len, SessionRecord &out)
Decode a session record, checking version, length and CRC.

Coulomb counter (AXP192)

usingkleidos::diag::power_meter::logic::CoulombRaw
Raw counters + ADC rate.
constexpr uint64_tkleidos::diag::power_meter::logic::kCoulombCountUahNumerator
One count = 65536 × 0.5 mA / (3600 × rate) mAh = this / (3600 × rate) µAh.
constexpr uint64_tkleidos::diag::power_meter::logic::kSecondsPerHour
Seconds per hour, for µAh ↔ µA·s conversions.
constexpr uint32_tkleidos::diag::power_meter::logic::kCoulombMeasuredMinCounts
Counts below which a coulomb sleep figure is only a bound (±1 count ≥ ±25 %).
uint32_tkleidos::diag::power_meter::logic::coulombLsbUah (uint16_t rateHz)
µAh one counter count represents, rounded up (a conservative bound).
int64_tkleidos::diag::power_meter::logic::coulombCountsToUah (int64_t counts, uint16_t rateHz)
Convert a count difference to µAh (rounded to nearest).
boolkleidos::diag::power_meter::logic::coulombDrawnUah (const CoulombRaw &a, const CoulombRaw &b, int64_t &drawnUah)
Charge drawn from the cell between two readings: Δout − Δin.
boolkleidos::diag::power_meter::logic::coulombDeltaUah (const CoulombRaw &a, const CoulombRaw &b, int64_t &outUah)
Net charge into the cell between two readings: Δin − Δout.
Estimatekleidos::diag::power_meter::logic::sleepFromCoulomb (int64_t drawnUah, uint32_t sleepS, uint16_t rateHz)
Average sleep current from the charge the counters saw drawn.

ModeSignature extras bits

constexpr uint8_tkleidos::diag::power_meter::logic::kExtraGps
GPS receiver powered.
constexpr uint8_tkleidos::diag::power_meter::logic::kExtraTone
Speaker tone playing.
constexpr uint8_tkleidos::diag::power_meter::logic::kExtraSd
SD card mounted.
constexpr uint8_tkleidos::diag::power_meter::logic::kExtraUsb
USB power present (last PMIC reading).

Measurement and model intervals

constexpr uint32_tkleidos::diag::power_meter::logic::kMeasuredAbsErrUa
AXP192 1 s mean: ±1 mA ...
constexpr uint32_tkleidos::diag::power_meter::logic::kMeasuredRelErrPct
... plus ±5 % of the value.
constexpr uint32_tkleidos::diag::power_meter::logic::kModelUncalibratedErrPct
Seed coefficients: ±50 %.
constexpr uint32_tkleidos::diag::power_meter::logic::kModelCalibratedErrPct
Bench-calibrated: ±20 %.

Rest voltage (open-circuit voltage)

constexpr size_tkleidos::diag::power_meter::logic::kOcvPoints
Table points at 0, 10, ..., 100 % SoC.
constexpr uint32_tkleidos::diag::power_meter::logic::kMinVoltageDropSleepS
Shorter sleeps give a bound only.
constexpr int16_tkleidos::diag::power_meter::logic::kMaxRestTempDeltaDeciC
|ΔT| above 5 °C gives Unknown.
uint16_tkleidos::diag::power_meter::logic::socPermille (const OcvTable &t, uint16_t mv)
State of charge from a rest voltage, piecewise linear and clamped.
Estimatekleidos::diag::power_meter::logic::sleepFromVoltageDrop (const VoltageDropInput &in, const OcvTable &t)
Average sleep current from the drop in rest voltage.

Labels

const char *kleidos::diag::power_meter::logic::qualityName (Quality q)
Console token of a quality.
const char *kleidos::diag::power_meter::logic::verdictName (Verdict v)
Console token of a verdict.
const char *kleidos::diag::power_meter::logic::bleModeName (BleMode m)
Console token of a BLE mode.
const char *kleidos::diag::power_meter::logic::wifiModeName (WifiMode m)
Console token of a Wi-Fi mode.

Back to the top

Typedef Documentation

SampleFn #

using kleidos::diag::telemetry::SampleFn

Channel sampling callback.

Reads one measurement for a channel. Returning false records nothing for this tick (e.g. an optional PMIC ADC the board does not have), so callers can adapt getters whose "unsupported/failed" path returns false.

Parameters
NameMeaning
ctxOpaque context the channel registered with (e.g. a PowerManager*).
outSet to the sampled value on success; untouched on failure.
Return values
ValueMeaning
trueA value was produced in out.
falseNo value this tick.

Back to the top

Enumeration Type Documentation

Basis #

enum class kleidos::diag::power_meter::Basis : uint8_t

What a current figure rests on.

Enumerator
Measured 

Current ADC, on battery.

Usb 

Current ADC while USB powers the board (IPSOUT-side load).

Model 

The board's current model.

BleMode #

enum class kleidos::diag::power_meter::logic::BleMode : uint8_t

BLE radio activity, as the current model distinguishes it.

Enumerator
Off 

Radio down.

Adv 

Starting, advertising or stopping.

Connected 

Pairing or connected, idle.

Typing 

Sending HID reports.

Budget #

enum class kleidos::diag::power_meter::Budget : uint8_t

The phases the meter reports a figure for, each beside the value the board is expected to hold there.

A phase has an expected value only once a bench meter has measured the board in it (PowerBudgets); until then its line carries the figure with no limit and an unknown verdict.

Enumerator
PinEntry 

Mean current on the unlock entry (PIN or passphrase).

BlePeak 

Largest 1 s mean while typing over BLE.

WifiPeak 

Largest 1 s mean in admin mode.

StandbyLocked 

Average current locked on standby.

DeepSleep 

Average current of the last deep sleep.

Event #

enum class kleidos::diag::power_run::Event : uint8_t

What the caller has to do now.

Enumerator
None 

Nothing is due.

EnterPhase 

Set up phase Sequencer::phase now.

OpenFigures 

The settle is over: start measuring the phase.

ClosePhase 

The phase is over (Sequencer::phase still names it): keep its figures.

Finished 

The last phase closed: the run is done.

BatteryTimeout 

USB never went away: the run is aborted before any phase.

Quality #

enum class kleidos::diag::power_meter::logic::Quality : uint8_t

How a figure was obtained, best first.

Enumerator
Measured 

From a current ADC, a coulomb counter or a valid rest-voltage pair.

Calibrated 

From the state model with bench-calibrated coefficients.

Modeled 

From the state model with seed (uncalibrated) coefficients.

Bound 

Only an interval is known; the point value is not meaningful.

Unknown 

Nothing usable.

RunState #

enum class kleidos::diag::power_run::RunState : uint8_t

Where a run is.

Enumerator
Idle 

Never started.

WaitingForBattery 

Started; waiting for USB to stay away for kBatteryConfirmMs.

Settling 

In a phase, before its figures open.

Measuring 

In a phase, its figures open.

Done 

Every phase ran.

Aborted 

Stopped early (Sequencer::abort or the battery wait timed out).

SleepKind #

enum class kleidos::diag::power_meter::SleepKind : uint8_t

What entering "deep sleep" does to the ESP32 on a board.

Enumerator
EspDeepSleep 

ESP deep sleep with the RTC domain kept (RTC memory survives).

PowerCut 

The board powers the ESP32 off (RTC memory is lost).

PowerCutWithTicks 

Power cut with periodic wakes to redraw the lock clock (CoreInk).

SleepMethod #

enum class kleidos::diag::power_meter::logic::SleepMethod : uint8_t

How the previous sleep's figure was obtained.

Enumerator
None 

No previous sleep known.

Coulomb 

Coulomb-counter delta with enough counts.

VoltageDrop 

Rest-voltage drop.

Bound 

Only an interval (few counts, short sleep, voltage rose).

Model 

The profile's modeled sleep floor.

StopStatus #

enum class kleidos::diag::telemetry::StopStatus : uint8_t

Outcome of a stop request.

Enumerator
Idle 

No run was active; nothing to tear down.

Stopped 

The sampler exited and every per-run resource was released.

Timeout 

The sampler had not exited within the budget; the run is retained.

Busy 

Another caller already owns this run's teardown.

Verdict #

enum class kleidos::diag::power_meter::logic::Verdict : uint8_t

Outcome of checking a figure against an expected value.

Enumerator
Pass 

The whole interval is below the limit.

Fail 

The whole interval is above the limit.

Unknown 

The interval straddles the limit, or the figure cannot be judged.

WifiMode #

enum class kleidos::diag::power_meter::logic::WifiMode : uint8_t

Wi-Fi radio activity, as the current model distinguishes it.

Enumerator
Off 

Radio down.

Ap 

Access point up, no client.

ApClient 

Access point with a client (or an OTA upload).

Sta 

Station session (NTP sync, Wi-Fi tests).

Back to the top

Function Documentation

accountedMs() #

uint64_t kleidos::diag::power_meter::accountedMs(uint64_t nowMs)

Total time accounted since boot, the open interval included.

Parameters
NameDirectionMeaning
nowMsinMonotonic time, ms.
Returns
Accounted ms (equals nowMs once started).

activePeriodMs() #

uint32_t kleidos::diag::telemetry::activePeriodMs()

Sampling period of the active run.

Lets callers report the live period without shadowing it in their own state.

Returns
Period in milliseconds, or 0 when idle.

appendSampleForTest() #

void kleidos::diag::telemetry::appendSampleForTest(const Sample & sample)

Native-test alias for ::ringAppend.

Retained so existing tests keep their intent-revealing call name; forwards verbatim to the production ::ringAppend write path.

Parameters
NameMeaning
sampleSample to append.

basisName() #

const char * kleidos::diag::power_meter::basisName(Basis b)

Console token of a basis.

Parameters
NameDirectionMeaning
binBasis.
Returns
"meas", "usb" or "model".

begin() [1/2] #

Install the queued logger.

Default placement: Core 0, priority 2, the services band (one above the FSM loop task's 1, below the vault worker's 3). Spawns the drainer task, creates the queue, and installs the vprintf hook.

Parameters
NameDirectionMeaning
coreinTarget core for the worker task.
priorityinFreeRTOS priority for the worker task.
Return values
ValueMeaning
trueLogger task, queue, and vprintf hook installed (or the logger was already running).
falseQueue or task creation failed; the hook is left in its previous state.
See also
shutdown, droppedCount

begin() [2/2] #

void kleidos::diag::power_meter::begin(PowerManager & pm, const PowerProfile & profile, const StateRoles & roles)

Start the meter: probe what the board measures, estimate the sleep that preceded this boot, and open the accounting at time 0.

Call once from setup(), after the PMIC is initialized and before BLE starts. The time from boot to this call is booked to state 0 (boot).

Parameters
NameDirectionMeaning
pminThe board's power manager (outlives the meter).
profileinThe board's power profile (outlives the meter).
rolesinIndices of the states the meter treats specially.

bleModeName() #

const char * kleidos::diag::power_meter::logic::bleModeName(BleMode m)

Console token of a BLE mode.

Parameters
NameDirectionMeaning
minBLE mode.
Returns
"off", "adv", "conn" or "typing".

budgetLine() #

BudgetLine kleidos::diag::power_meter::budgetLine(Budget b, uint64_t nowMs)

The meter's figure for one phase, beside its expected value if it has one.

Parameters
NameDirectionMeaning
binBudget.
nowMsinMonotonic time, ms.
Returns
The budget line.

budgetName() #

const char * kleidos::diag::power_meter::budgetName(Budget b)

Short name of a phase, as diagnostics print it.

Parameters
NameDirectionMeaning
binBudget.
Returns
"pin_entry", "ble_peak", "wifi", "standby" or "deep_sleep".

channelCount() #

size_t kleidos::diag::telemetry::channelCount()

Number of channels currently registered.

Returns
Count in [0, ::kMaxChannels].

channelName() #

const char * kleidos::diag::telemetry::channelName(size_t i)

Access a registered channel name by index, in registration order.

Parameters
NameMeaning
iIndex in [0, channelCount()).
Returns
NUL-terminated name, or nullptr if i is out of range.

closeInterval() #

IntervalFigures kleidos::diag::power_meter::closeInterval()

Close the open interval and return its figures.

On a measuring board a current sample is taken first, so the interval ends on a reading too.

Returns
The figures (open false when no interval was open).

copyRecentSamples() #

size_t kleidos::diag::telemetry::copyRecentSamples(Sample * out, size_t maxSamples)

Copy an oldest-first snapshot of the newest recorded samples.

copySamples answers with the oldest end of the ring, which is the wrong window for a caller that can only afford part of it: a polled chart wants the most recent history, and a reader that keeps re-reading the oldest samples would never see anything new once the ring filled. This copies the last maxSamples samples instead, still oldest-first so the ordering contract (and the encoder's "one tick shares one timestamp" invariant) is unchanged.

Parameters
NameMeaning
outDestination array.
maxSamplesCapacity of out in samples.
Returns
Number of samples written (min of maxSamples and the ring fill).

copySamples() #

size_t kleidos::diag::telemetry::copySamples(Sample * out, size_t maxSamples)

Copy an oldest-first snapshot of the recorded samples.

Parameters
NameMeaning
outDestination array.
maxSamplesCapacity of out in samples.
Returns
Number of samples written (min of maxSamples and the ring fill).

coulombCountsToUah() #

int64_t kleidos::diag::power_meter::logic::coulombCountsToUah(int64_t counts, uint16_t rateHz)

Convert a count difference to µAh (rounded to nearest).

Parameters
NameDirectionMeaning
countsinSigned count difference.
rateHzinADC rate in Hz.
Returns
µAh; 0 when rateHz is 0.

coulombDeltaUah() #

bool kleidos::diag::power_meter::logic::coulombDeltaUah(const CoulombRaw & a, const CoulombRaw & b, int64_t & outUah)

Net charge into the cell between two readings: Δin − Δout.

Parameters
NameDirectionMeaning
ainEarlier reading.
binLater reading.
outUahoutNet charge into the cell, µAh.
Return values
ValueMeaning
trueComparable readings.
falseSee coulombDrawnUah.

coulombDrawnUah() #

bool kleidos::diag::power_meter::logic::coulombDrawnUah(const CoulombRaw & a, const CoulombRaw & b, int64_t & drawnUah)

Charge drawn from the cell between two readings: Δout − Δin.

Parameters
NameDirectionMeaning
ainEarlier reading.
binLater reading.
drawnUahoutCharge out of the cell, µAh (negative = net charging).
Return values
ValueMeaning
trueBoth readings are comparable.
falseThe rate is 0 or changed, or a counter went backwards (cleared or wrapped); drawnUah is untouched.

coulombLsbUah() #

uint32_t kleidos::diag::power_meter::logic::coulombLsbUah(uint16_t rateHz)

µAh one counter count represents, rounded up (a conservative bound).

Parameters
NameDirectionMeaning
rateHzinADC rate in Hz.
Returns
µAh per count; 0 when rateHz is 0.

cpuClockValid() #

bool kleidos::diag::power_run::cpuClockValid(uint32_t mhz)

Whether a phase may hold the core clock mhz.

Parameters
NameDirectionMeaning
mhzinClock in MHz; 0 means the phase holds none.
Return values
ValueMeaning
true0, or one of kForcedCpuMhz.
falseAny other value: a clock the SoC cannot run, or one only a crystal divider gives, which would move the bus clocks too.

decodeRecord() #

bool kleidos::diag::power_meter::logic::decodeRecord(const uint8_t * buf, size_t len, SessionRecord & out)

Decode a session record, checking version, length and CRC.

Parameters
NameDirectionMeaning
bufinEncoded bytes.
leninLength of buf.
outoutDecoded record (written only on success).
Return values
ValueMeaning
trueValid record.
falseShort buffer, version mismatch or CRC mismatch.

decodeSnapshot() #

bool kleidos::diag::power_meter::logic::decodeSnapshot(const uint8_t * buf, size_t len, SleepSnapshot & out)

Decode a snapshot, checking version, length and CRC.

Parameters
NameDirectionMeaning
bufinEncoded bytes.
leninLength of buf.
outoutDecoded snapshot (written only on success).
Return values
ValueMeaning
trueValid snapshot.
falseShort buffer, version mismatch or CRC mismatch.

droppedCount() #

uint32_t kleidos::diag::log::droppedCount()

Total number of messages dropped because the queue was full since boot.

0 is the only acceptable steady-state value; non-zero indicates the queue depth or the task priority is wrong for current load.

Returns
Cumulative count of dropped log messages.
See also
begin

droppedSamples() #

size_t kleidos::diag::telemetry::droppedSamples()

Number of samples overwritten (dropped) since the ring was allocated.

Returns
Cumulative dropped-sample count.

enableIdle1Watchdog() #

bool kleidos::diag::enableIdle1Watchdog()
noexcept

Watch the Core 1 (APP_CPU) idle task with the Task Watchdog Timer.

The boards boot watching no idle task. This adds IDLE1 through the watchdog's idle-core mask, so ESP-IDF also registers the idle hook that feeds it (a bare subscription of an idle task is never fed and fires after the timeout); a task that then monopolizes Core 1 past the timeout (e.g. a busy-spin in the UI loop) fires the watchdog. Call it after setup() has configured the watchdog. IDLE1 stays watched for the rest of the boot: ESP-IDF changes the idle mask by first dropping every idle task the old mask named, which races that core's idle hook, so the mask is only ever grown from empty.

Return values
ValueMeaning
trueIDLE1 is watched (now, or it already was).
falseThe watchdog is not initialized, or another idle task is already watched.

encodeRecord() #

size_t kleidos::diag::power_meter::logic::encodeRecord(const SessionRecord & r, uint8_t * buf, size_t cap)

Encode a session record as [ver][payload LE][crc32 LE].

Parameters
NameDirectionMeaning
rinRecord.
bufoutDestination.
capinCapacity of buf.
Returns
Bytes written (kRecordBytes), or 0 when cap is too small.

encodeSnapshot() #

size_t kleidos::diag::power_meter::logic::encodeSnapshot(const SleepSnapshot & s, uint8_t * buf, size_t cap)

Encode a snapshot as [ver][payload LE][crc32 LE].

Parameters
NameDirectionMeaning
sinSnapshot.
bufoutDestination.
capinCapacity of buf.
Returns
Bytes written (kSnapshotBytes), or 0 when cap is too small.

formatReport() #

size_t kleidos::diag::render::formatReport(char * out, size_t outLen)

Format a multi-line plain-text dump. Returns bytes written (excl. NUL).

Always available; emits "(disabled)" line when KLEIDOS_PROFILE is off.

Parameters
NameDirectionMeaning
outoutDestination buffer.
outLeninCapacity of out in bytes.
Returns
Bytes written, excluding the terminating NUL.
See also
Sample

formatTaskTable() #

size_t kleidos::diag::formatTaskTable(char * out, size_t outLen)

Render a multi-line table of every task with its core, priority, state, stack high-water mark, and CPU runtime percentage since the previous call.

Output is ASCII, suitable for a serial log or a text/plain HTTP body. Returns 0 in release builds.

Parameters
NameDirectionMeaning
outoutDestination buffer of at least outLen bytes.
outLeninBuffer capacity in bytes (recommended: 2048 for ~30 tasks).
Returns
Number of bytes written, excluding the terminating NUL.
See also
snapshot

intervalFigures() #

IntervalFigures kleidos::diag::power_meter::intervalFigures(uint64_t nowMs)

Figures of the open interval so far, without closing it or sampling.

Parameters
NameDirectionMeaning
nowMsinMonotonic time, ms.
Returns
The figures (open false when no interval is open).

isRunning() #

bool kleidos::diag::telemetry::isRunning()

Whether a telemetry run currently owns the service.

True from a successful start until stop has released the run's resources — including the window after a StopStatus::Timeout, where the sampler has been asked to exit but the ring is still live. This is the flag start tests, so it is also the right question to ask before offering to start one.

Return values
ValueMeaning
trueA run is active or its teardown is still pending.
falseIdle.

judge() #

Verdict kleidos::diag::power_meter::logic::judge(const Estimate & e, uint32_t limitUa)

Judge a figure against a limit.

Pass only when hi < limit, fail only when lo > limit, unknown otherwise. A Quality::Modeled (uncalibrated) or Quality::Unknown figure is always Verdict::Unknown.

Parameters
NameDirectionMeaning
einFigure with its interval.
limitUainBudget limit, µA.
Returns
Verdict.

logCurrentCore() #

void kleidos::diag::logCurrentCore(const char * tag)
noexcept

Log the calling core id.

Parameters
NameDirectionMeaning
taginLog tag printed alongside the core id.

logHeapStats() #

void kleidos::diag::logHeapStats(const char * tag)
noexcept

Log free heap and largest free block (DRAM, 8-bit-capable).

Parameters
NameDirectionMeaning
taginLog tag printed before the heap statistics.

logStackHighWaterMark() #

void kleidos::diag::logStackHighWaterMark(const char * tag)
noexcept

Log the calling task's stack high-water mark via the platform logger.

Parameters
NameDirectionMeaning
taginLog tag printed before the high-water mark value.

loopTickLastUs() #

uint32_t kleidos::diag::loopTickLastUs()

Most recent loop-tick interval in microseconds (0 before the first tick).

Returns
Last recorded loop-tick interval in microseconds, or 0 if no tick has been recorded yet.

loopTickMaxUsAndReset() #

uint32_t kleidos::diag::loopTickMaxUsAndReset()

Peak loop-tick interval since the last read, then reset the peak.

Reading and resetting makes each query of the debug console report the worst UI-loop stall observed since the previous query — a rolling worst-case, not an all-time max that a single early spike would pin forever.

Returns
Peak loop-tick interval in microseconds since the last call.

measuredEstimate() #

Estimate kleidos::diag::power_meter::logic::measuredEstimate(int32_t microamps)

Interval around a measured current: ±(1 mA + 5 %).

Parameters
NameDirectionMeaning
microampsinMeasured current, µA (negative values clamp to 0).
Returns
Estimate with Quality::Measured.

measuresCurrent() #

bool kleidos::diag::power_meter::measuresCurrent()

Whether the board measures current (the meter runs in measured mode).

Return values
ValueMeaning
trueA board whose AXP192 reads current, after begin.
falseModeled board, or before begin.

modelCurrentUa() #

uint32_t kleidos::diag::power_meter::logic::modelCurrentUa(const ModeSignature & m, const ModelCoefficients & k)

Modeled current of one mode signature.

Parameters
NameDirectionMeaning
minMode signature.
kinBoard coefficients.
Returns
Modeled current in µA (saturates at UINT32_MAX).

modelEstimate() #

Estimate kleidos::diag::power_meter::logic::modelEstimate(uint32_t microamps, bool calibrated)

Interval around a modeled current: ±50 % seed, ±20 % calibrated.

Parameters
NameDirectionMeaning
microampsinModeled current, µA.
calibratedinTrue for a bench-calibrated profile.
Returns
Estimate with modelQuality.

modelQuality() #

Quality kleidos::diag::power_meter::logic::modelQuality(bool calibrated)

Quality label of a model figure.

Parameters
NameDirectionMeaning
calibratedinTrue when the profile's coefficients are bench-calibrated.
Returns
Quality::Calibrated or Quality::Modeled.

onFlushEnter() #

void kleidos::diag::render::onFlushEnter()
inline

Call right before flushCb does its bus traffic. Captures the start timestamp used by onFlushExit() to compute latency.

See also
onFlushExit

onFlushExit() #

void kleidos::diag::render::onFlushExit()
inline

Call right after flushCb has pushed its colors. Updates lastFlushUs / maxFlushUs and bumps flushCount.

See also
onFlushEnter

onTimerHandlerEnter() #

void kleidos::diag::render::onTimerHandlerEnter()
inline

Call right before the render tick. Records the gap since the previous tick and bumps frameCount.

See also
onFlushEnter, onFlushExit

openInterval() #

void kleidos::diag::power_meter::openInterval()

Open a measuring interval at this instant (closing any open one).

On a measuring board a current sample is taken first, so the interval starts on a reading rather than on a value held since the last one. One interval at a time: the debug console's power run is its one user.

planDurationMs() #

uint64_t kleidos::diag::power_run::planDurationMs(const Plan & plan)

Length of a plan: the sum of its phases' dwell times.

Parameters
NameDirectionMeaning
planinPlan.
Returns
Milliseconds from the first phase's setup to the end of the last one (the wait for battery not included).

planValid() #

bool kleidos::diag::power_run::planValid(const Plan & plan)

Whether a plan can run.

Parameters
NameDirectionMeaning
planinPlan.
Return values
ValueMeaning
true1 to kMaxPhases phases, each with a dwell longer than its settle, a clock cpuClockValid accepts and a backlight level no higher than kMaxBacklightPct.
falseEmpty, too long, a phase with no measuring window, or a phase that holds a clock the board cannot run.

prepareForSleep() #

void kleidos::diag::power_meter::prepareForSleep()

Close the session and store the pre-sleep snapshot in RTC memory.

Call on every path into deep sleep, after the radios stop. Writes no flash. No-op before begin.

qualityName() #

const char * kleidos::diag::power_meter::logic::qualityName(Quality q)

Console token of a quality.

Parameters
NameDirectionMeaning
qinQuality.
Returns
"meas", "cal", "model", "bound" or "na".

readLoadMilliamps() #

bool kleidos::diag::power_meter::readLoadMilliamps(float & milliamps)

Take a fresh load-current reading (the load_ma telemetry channel).

Three short I2C reads: battery charge, battery discharge and VBUS current.

Parameters
NameDirectionMeaning
milliampsoutLoad current in mA on success.
Return values
ValueMeaning
trueMeasuring board and the reads succeeded.
falseModeled board, not started, or an I2C error.

reapPendingStop() #

StopStatus kleidos::diag::telemetry::reapPendingStop()

Finish a teardown that a timed-out stop left pending.

Polls the stop semaphore without blocking and completes the release if the sampler has since exited. A no-op unless a stop was already requested, so it is safe to call speculatively from a polled read path — it never stops a healthy run.

Returns
StopStatus::Idle when there is nothing pending, otherwise the outcome of the non-blocking teardown attempt.

recordLoopTickUs() #

void kleidos::diag::recordLoopTickUs(uint32_t deltaUs)

Record one loop-tick interval in microseconds.

Parameters
NameDirectionMeaning
deltaUsinMicroseconds since the previous tick.

registerChannel() #

bool kleidos::diag::telemetry::registerChannel(const char * name, SampleFn fn, void * ctx)

Register a sampling channel.

Not thread-safe: call only during single-threaded board init.

Parameters
NameMeaning
nameChannel name (e.g. "batt_mv"); must outlive the registry.
fnSampling callback; must not be nullptr.
ctxOpaque context passed back to fn on every sample.
Return values
ValueMeaning
trueRegistered.
falseRejected: name/fn is nullptr, a channel with the same name (case-insensitive) already exists, or the registry is at ::kMaxChannels capacity.

resetForTest() #

bool kleidos::diag::telemetry::resetForTest()

Reset registry and ring state, (re)allocating an empty ring.

Native-test seam only: gives each test case a clean registry and ring. Never call this from device firmware.

Return values
ValueMeaning
trueState reset and ring allocated.
falseRing allocation failed.

ringAppend() #

void kleidos::diag::telemetry::ringAppend(const Sample & sample)

Append one sample to the ring (production write path).

The sampler task calls this once per channel per tick; it owns the append/wrap/drop accounting and the ring critical section. Exposed in the header so native tests can drive the same code path without the RTOS sampler.

Parameters
NameMeaning
sampleSample to append.

running() #

bool kleidos::diag::log::running()

Whether the queued logger is installed and draining.

Return values
ValueMeaning
truebegin() succeeded and shutdown() has not run since: every ESP_LOGx line goes through the queue, and a line that finds it full is dropped and counted by droppedCount().
falseLines go straight to the default writer and none is dropped.
See also
begin, shutdown, droppedCount

runStateName() #

const char * kleidos::diag::power_run::runStateName(RunState s)

Console token of a run state.

Parameters
NameDirectionMeaning
sinRun state.
Returns
"idle", "waiting", "settling", "measuring", "done" or "aborted".

sampleCount() #

size_t kleidos::diag::telemetry::sampleCount()

Number of samples currently held in the ring.

A lock-guarded count only — no sample copy — so callers that just need the fill level avoid snapshotting the whole ring.

Returns
Sample count in [0, ::kTelemetryRingSamples].

selectChannels() #

size_t kleidos::diag::telemetry::selectChannels(const char * csv, uint8_t * out, size_t maxOut)

Resolve a CSV channel list to registry indices.

Parameters
NameMeaning
csvComma-separated channel names, or nullptr to select every registered channel in order. Unknown names are ignored (skipped).
outDestination array of channel indices.
maxOutCapacity of out.
Returns
Number of indices written.

serviceFromUiTask() #

void kleidos::diag::telemetry::serviceFromUiTask()

Service the telemetry service from the FSM/main-loop task (Core 1).

Call once per loop tick, unconditionally. While no run owns the service it returns after a single atomic load, so the common case costs nothing; with a run active it does two things, both bounded:

  1. Takes the readings. The ticks the Core-0 sampler had posted when the pump began are drained — at most ::kSampleQueueDepth per call, the most the queue can hold, so a sampling period shorter than one pass cannot pin this task behind the sampler. The channel callbacks are invoked from this task — the one PowerManager requires (hal/power/power_manager.h, "Threading"). Samples keep the sampler's tick timestamp, so the recorded cadence stays drift-free even though the reads happen a few milliseconds later.
  2. Finishes a pending teardown. A stop that timed out leaves the release latched; completing it here is what lets callers on this task request a stop without parking on the sampler (see stop).

Device-only (ESP_PLATFORM), exactly like start and stop — there is no sampler in native host builds and therefore no host definition.

shutdown() #

void kleidos::diag::log::shutdown()

Restore the default vprintf, drain pending messages, then stop the task.

Bounded wait (~200 ms). Safe to call multiple times. Must be called before deep sleep to flush queued messages and tear down the drainer task on Core 0 — leaving the task live while the rest of the system sleeps would block deep-sleep entry.

See also
begin

sleepFloorEstimate() #

Estimate kleidos::diag::power_meter::logic::sleepFloorEstimate(uint32_t declaredUa, bool calibrated)

Estimate of the deep-sleep floor from the figure the variant declares.

The declared figure is a measurement or nothing. 0 means the board's sleep has never been measured, and the estimate is then Quality::Unknown rather than a 0 µA reading; any other figure is modeled like a seed coefficient.

Parameters
NameDirectionMeaning
declaredUainPOWER_DEEP_SLEEP_UA; 0 when never measured.
calibratedinThe profile's coefficients are bench-calibrated.
Returns
The estimate.

sleepFromCoulomb() #

Estimate kleidos::diag::power_meter::logic::sleepFromCoulomb(int64_t drawnUah, uint32_t sleepS, uint16_t rateHz)

Average sleep current from the charge the counters saw drawn.

The interval is ±1 count. Fewer than kCoulombMeasuredMinCounts counts give only a Quality::Bound. Whether the counter moves at all for currents below one ADC LSB (0.5 mA) is not known yet, so a small figure is a leak detector, not a µA measurement.

Parameters
NameDirectionMeaning
drawnUahinCharge drawn during the sleep, µAh (see coulombDrawnUah).
sleepSinSleep length, s.
rateHzinADC rate the counts were taken at.
Returns
Estimate; Quality::Unknown when sleepS or rateHz is 0 or the cell charged.

sleepFromVoltageDrop() #

Estimate kleidos::diag::power_meter::logic::sleepFromVoltageDrop(const VoltageDropInput & in, const OcvTable & t)

Average sleep current from the drop in rest voltage.

ΔSoC × capacity / Δt, with an interval from mvResolution at both ends. A voltage that rose gives a bound with lo = 0; a sleep shorter than kMinVoltageDropSleepS gives a bound; USB, charging or a temperature swing over kMaxRestTempDeltaDeciC gives Unknown.

Parameters
NameDirectionMeaning
ininInputs.
tinRest-voltage table of the cell.
Returns
Estimate.

sleepMethodName() #

const char * kleidos::diag::power_meter::logic::sleepMethodName(SleepMethod m)

Console token of a sleep method.

Parameters
NameDirectionMeaning
minMethod.
Returns
"na", "coulomb", "vdrop", "bound" or "model".

snapshot() [1/3] #

Snapshot kleidos::diag::power_meter::snapshot()

Copy of the latest published state; safe from any task.

Returns
Snapshot (with started false before begin).

snapshot() [2/3] #

Sample kleidos::diag::render::snapshot()
inline

Atomic snapshot of the counters. Safe to call from any task.

Returns
Current Sample values.

snapshot() [3/3] #

RuntimeSnapshot kleidos::diag::snapshot()

Capture a coarse-grained snapshot. Always available, even in release builds — it has no measurable cost.

Returns
Current heap and uptime snapshot.
See also
RuntimeSnapshot

socPermille() #

uint16_t kleidos::diag::power_meter::logic::socPermille(const OcvTable & t, uint16_t mv)

State of charge from a rest voltage, piecewise linear and clamped.

Parameters
NameDirectionMeaning
tinTable.
mvinRest voltage, mV.
Returns
SoC in permille, 0..1000 (0 for a null table).

start() #

bool kleidos::diag::telemetry::start(const Config & config)

Start sampling.

Claims the single run slot, selects channels from config.channelCsv (nullptr = all), allocates the ring, and spawns the sampler task on Core 0 at the minimum app priority. Safe to call from any task.

The sampler is a metronome only: it owns the cadence and posts a tick per period, and serviceFromUiTask does the reading. A run therefore records nothing until the loop task starts pumping — which it does every tick.

Also reaps a teardown that an earlier stop left pending (see StopStatus::Timeout) before claiming, so a single timed-out stop cannot strand the service.

Parameters
NameMeaning
configSampling configuration. config.stream is honored only on the debug-serial surface; callers reachable from the network must leave it false (it drives writes into the debug UART).
Return values
ValueMeaning
trueSampler started.
falseA run is already active (or its teardown has not finished), no channels were selected, or an allocation failed.

stateFigure() #

StateFigure kleidos::diag::power_meter::stateFigure(uint8_t state, uint64_t nowMs)

Figures of one state, the open interval included.

Parameters
NameDirectionMeaning
stateinState index.
nowMsinMonotonic time, ms.
Returns
Figures (all zero for a state never entered).

stop() #

StopStatus kleidos::diag::telemetry::stop(uint32_t timeoutMs = kStopWaitForever)

Stop sampling and release all per-run resources, with a bounded wait.

Requests the stop, waits up to timeoutMs for the sampler to exit, then frees the ring. Recorded samples are discarded with the ring, so snapshot them with copySamples first. Safe to call from any task, including the single Core-0 HTTP server task — which is why the wait is bounded: that task serves every admin request, so blocking it indefinitely would wedge the whole portal.

On StopStatus::Timeout every resource is deliberately retained: the sampler task is still alive and still writing the ring, so freeing it would be a use-after-free. The run stays claimed (so start cannot recycle it) and the stop request stays latched, so any later stop or start finishes the teardown. With kStopPollSliceMs bounding the sampler's sleep, a timeout needs a budget under ~100 ms plus one sampling pass.

A caller on the UI loop task should pass 0: that latches the stop without blocking (answering StopStatus::Timeout), and the very next serviceFromUiTask pump completes the release. Blocking the loop task on the sampler is only acceptable on the deep-sleep teardown path, where the whole shutdown sequence is already synchronous.

Parameters
NameMeaning
timeoutMsMilliseconds to wait for the sampler to exit, 0 to latch the stop without waiting, or ::kStopWaitForever to block until it does.
Returns
What happened; see StopStatus.
Note
The stop semaphore is intentionally not destroyed here. The sampler signals it as its last act before deleting itself, so on SMP the giving task can still be inside the give when the waiter wakes on the other core; freeing the semaphore there is a narrow but real use-after-free. Retaining it (~88 B, created on the first start) removes the race entirely and costs nothing per run.

tick() #

void kleidos::diag::power_meter::tick(uint64_t nowMs, const logic::ModeSignature & sig)

Loop hook: close the open interval on a signature change and take a current sample when one is due.

O(1) and free of I2C traffic unless a sample is due (measuring boards only).

Parameters
NameDirectionMeaning
nowMsinMonotonic time, ms.
siginCurrent mode signature.

usbPresent() #

bool kleidos::diag::power_meter::usbPresent()

Whether USB powers the board right now, from a fresh reading.

On a measuring board the USB input's voltage or current (VBUS, or ACIN on the Core2 v1.3); elsewhere the charger's state. The voltage is the steady signal: with USB plugged in and a small load the AXP192's input-current ADC reads near 0 for single samples, which the samples' own USB flag follows.

Return values
ValueMeaning
trueUSB present.
falseNo USB, or the meter is not started.

verdictName() #

const char * kleidos::diag::power_meter::logic::verdictName(Verdict v)

Console token of a verdict.

Parameters
NameDirectionMeaning
vinVerdict.
Returns
"pass", "fail" or "unknown".

wifiModeName() #

const char * kleidos::diag::power_meter::logic::wifiModeName(WifiMode m)

Console token of a Wi-Fi mode.

Parameters
NameDirectionMeaning
minWi-Fi mode.
Returns
"off", "ap", "ap_client" or "sta".

Back to the top

Variable Documentation

kGenericLipoOcvMv #

std::array<uint16_t, logic::kOcvPoints> kleidos::diag::power_meter::kGenericLipoOcvMv
inlineconstexpr

Rest voltage of a generic 1-cell LiPo at 0, 10, ..., 100 % SoC (mV).

A planning table, not a measurement of any board's cell: the rest voltage is a per-cell characteristic, so a board that gets a measured table replaces this one in its profile.

kMaxChannels #

size_t kleidos::diag::telemetry::kMaxChannels
inlineconstexpr

Maximum number of channels the registry can hold. The registry is a boot-time static (12 bytes per slot of permanent DRAM), so the capacity is sized to what the boards actually register — seven battery channels on the richest PMIC (mV, %, mA, VBUS mV/mA, temperature, coulomb counter) plus the power meter's load current — plus spare, not to a round number: the classic-ESP32 debug builds link with only a few hundred bytes of DRAM headroom.

kRecordVersion #

uint8_t kleidos::diag::power_meter::logic::kRecordVersion
inlineconstexpr

SessionRecord wire version.

kSampleQueueDepth #

size_t kleidos::diag::telemetry::kSampleQueueDepth
inlineconstexpr

Depth of the sampler-to-UI tick queue.

The sampler posts a tick and immediately goes back to sleep — it never waits for the loop task — so this depth is jitter absorption, not capacity: two slots cover a loop tick that ran long without letting a starved UI accumulate an unbounded backlog of stale ticks. A tick that finds the queue full is dropped, which shows up honestly as a gap in the recorded history.

The same constant bounds how many ticks one ::serviceFromUiTask pump drains: the depth is the largest backlog that can exist when the pump begins, so draining more would mean chasing ticks posted during the pump itself — a chase that, at a period shorter than one sampling pass, never ends.

kStopPollSliceMs #

uint32_t kleidos::diag::telemetry::kStopPollSliceMs
inlineconstexpr

Longest single sleep the sampler takes between stop-request checks.

The sampler sleeps out its configured period in slices of at most this many milliseconds, re-reading the stop request between slices. Stop latency is therefore bounded by this constant plus one sampling pass regardless of the configured period, which is what lets a Core-0 HTTP handler stop a run with a short, bounded wait instead of blocking for a whole (possibly minutes-long) period.

Back to the top