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/
Files | |
| file | src/ |
| Opt-in dual-core diagnostics helpers (watchdog, stack, heap, core). | |
| file | src/ |
| Queued logger task that moves ESP_LOGx formatting off the hot path. | |
| file | src/ |
| On-device power meter: per-state consumption, session charge and the last deep sleep's average current, each with a quality label. | |
| file | src/ |
| Pure arithmetic of the on-device power meter (host-tested). | |
| file | src/ |
| Per-board constant data the power meter works from. | |
| file | src/ |
| Timing of a scripted power run: a fixed sequence of timed phases the board steps through on its own (host-tested). | |
| file | src/ |
| Render-loop profiling counters (debug builds only). | |
| file | src/ |
| Lightweight FreeRTOS runtime/heap profiling helpers. | |
| file | src/ |
| Implementation of the on-demand telemetry service. | |
| file | src/ |
| On-demand, zero-idle-cost telemetry sampling service. | |
Typedefs | |
| using | kleidos:: |
| Channel sampling callback. | |
Functions | |
| bool | kleidos:: |
| Watch the Core 1 (APP_CPU) idle task with the Task Watchdog Timer. | |
| void | kleidos:: |
| Log the calling task's stack high-water mark via the platform logger. | |
| void | kleidos:: |
| Log free heap and largest free block (DRAM, 8-bit-capable). | |
| void | kleidos:: |
| Log the calling core id. | |
| bool | kleidos:: |
| Install the queued logger. | |
| void | kleidos:: |
| Restore the default vprintf, drain pending messages, then stop the task. | |
| uint32_t | kleidos:: |
| Total number of messages dropped because the queue was full since boot. | |
| bool | kleidos:: |
| Whether the queued logger is installed and draining. | |
| const char * | kleidos:: |
| Console token of a basis. | |
| const char * | kleidos:: |
| Short name of a phase, as diagnostics print it. | |
| void | kleidos:: |
| Start the meter: probe what the board measures, estimate the sleep that preceded this boot, and open the accounting at time 0. | |
| void | kleidos:: |
| Loop hook: close the open interval on a signature change and take a current sample when one is due. | |
| void | kleidos:: |
| Close the session and store the pre-sleep snapshot in RTC memory. | |
| Snapshot | kleidos:: |
| Copy of the latest published state; safe from any task. | |
| StateFigure | kleidos:: |
| Figures of one state, the open interval included. | |
| uint64_t | kleidos:: |
| Total time accounted since boot, the open interval included. | |
| BudgetLine | kleidos:: |
| The meter's figure for one phase, beside its expected value if it has one. | |
| void | kleidos:: |
| Open a measuring interval at this instant (closing any open one). | |
| IntervalFigures | kleidos:: |
| Close the open interval and return its figures. | |
| IntervalFigures | kleidos:: |
| Figures of the open interval so far, without closing it or sampling. | |
| bool | kleidos:: |
| Whether the board measures current (the meter runs in measured mode). | |
| bool | kleidos:: |
| Whether USB powers the board right now, from a fresh reading. | |
| bool | kleidos:: |
Take a fresh load-current reading (the load_ma telemetry channel). | |
| uint32_t | kleidos:: |
| Modeled current of one mode signature. | |
| Quality | kleidos:: |
| Quality label of a model figure. | |
| Estimate | kleidos:: |
| Interval around a measured current: ±(1 mA + 5 %). | |
| Estimate | kleidos:: |
| Interval around a modeled current: ±50 % seed, ±20 % calibrated. | |
| Estimate | kleidos:: |
| Estimate of the deep-sleep floor from the figure the variant declares. | |
| Verdict | kleidos:: |
| Judge a figure against a limit. | |
| bool | kleidos:: |
Whether a phase may hold the core clock mhz. | |
| uint64_t | kleidos:: |
| Length of a plan: the sum of its phases' dwell times. | |
| bool | kleidos:: |
| Whether a plan can run. | |
| const char * | kleidos:: |
| Console token of a run state. | |
| void | kleidos:: |
Call right before the render tick. Records the gap since the previous tick and bumps frameCount. | |
| void | kleidos:: |
Call right before flushCb does its bus traffic. Captures the start timestamp used by onFlushExit() to compute latency. | |
| void | kleidos:: |
Call right after flushCb has pushed its colors. Updates lastFlushUs / maxFlushUs and bumps flushCount. | |
| Sample | kleidos:: |
| Atomic snapshot of the counters. Safe to call from any task. | |
| void | kleidos:: |
| Reset all counters to zero. Useful for measurement runs. | |
| size_t | kleidos:: |
| Format a multi-line plain-text dump. Returns bytes written (excl. NUL). | |
| RuntimeSnapshot | kleidos:: |
| Capture a coarse-grained snapshot. Always available, even in release builds — it has no measurable cost. | |
| size_t | kleidos:: |
| 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. | |
| void | kleidos:: |
| Record one loop-tick interval in microseconds. | |
| uint32_t | kleidos:: |
| Most recent loop-tick interval in microseconds (0 before the first tick). | |
| uint32_t | kleidos:: |
| Peak loop-tick interval since the last read, then reset the peak. | |
| bool | kleidos:: |
| Register a sampling channel. | |
| size_t | kleidos:: |
| Number of channels currently registered. | |
| const char * | kleidos:: |
| Access a registered channel name by index, in registration order. | |
| bool | kleidos:: |
| Start sampling. | |
| StopStatus | kleidos:: |
| Stop sampling and release all per-run resources, with a bounded wait. | |
| StopStatus | kleidos:: |
| Finish a teardown that a timed-out stop left pending. | |
| bool | kleidos:: |
| Whether a telemetry run currently owns the service. | |
| uint32_t | kleidos:: |
| Sampling period of the active run. | |
| size_t | kleidos:: |
| Copy an oldest-first snapshot of the recorded samples. | |
| size_t | kleidos:: |
| Copy an oldest-first snapshot of the newest recorded samples. | |
| size_t | kleidos:: |
| Number of samples overwritten (dropped) since the ring was allocated. | |
| size_t | kleidos:: |
| Number of samples currently held in the ring. | |
| void | kleidos:: |
| Service the telemetry service from the FSM/main-loop task (Core 1). | |
| size_t | kleidos:: |
| Resolve a CSV channel list to registry indices. | |
| void | kleidos:: |
| Append one sample to the ring (production write path). | |
| void | kleidos:: |
| Native-test alias for ::ringAppend. | |
| bool | kleidos:: |
| Reset registry and ring state, (re)allocating an empty ring. | |
Variables | |
| constexpr size_t | kleidos:: |
| Number of Budget values. | |
| constexpr size_t | kleidos:: |
| Number of BleMode values. | |
| constexpr size_t | kleidos:: |
| Number of WifiMode values. | |
| constexpr size_t | kleidos:: |
| Number of per-state accounting buckets (one per application state). | |
| constexpr std::array< uint16_t, logic:: | kleidos:: |
| Rest voltage of a generic 1-cell LiPo at 0, 10, ..., 100 % SoC (mV). | |
| constexpr size_t | kleidos:: |
| Most phases a plan may hold (the device keeps one result per phase). | |
| constexpr uint8_t | kleidos:: |
| Highest backlight level a phase may hold, %. | |
| constexpr uint64_t | kleidos:: |
| USB must stay away this long before a plan that waits for battery starts. | |
| constexpr uint64_t | kleidos:: |
| A plan that waits for battery gives up when USB is still there after this long. | |
| constexpr std::array< uint16_t, 3 > | kleidos:: |
| Core clocks a phase may hold, MHz: the PLL-sourced settings both SoCs run. | |
| constexpr size_t | kleidos:: |
| constexpr size_t | kleidos:: |
| Ring-buffer capacity in samples (fixed; ~6 KB — fits the no-PSRAM boards). | |
| constexpr uint32_t | kleidos:: |
| stop timeout sentinel: block until the sampler has actually exited. | |
| constexpr uint32_t | kleidos:: |
| Longest single sleep the sampler takes between stop-request checks. | |
| constexpr size_t | kleidos:: |
| Depth of the sampler-to-UI tick queue. | |
Records kept across a deep sleep | |
| enum class | kleidos:: |
| How the previous sleep's figure was obtained. More about kleidos:: | |
| constexpr uint8_t | kleidos:: |
| SleepSnapshot wire version. | |
| constexpr uint8_t | kleidos:: |
| constexpr size_t | kleidos:: |
| Encoded size of a SleepSnapshot (version + payload + CRC-32). | |
| constexpr size_t | kleidos:: |
| Encoded size of a SessionRecord (version + payload + CRC-32). | |
| const char * | kleidos:: |
| Console token of a sleep method. | |
| size_t | kleidos:: |
| Encode a snapshot as [ver][payload LE][crc32 LE]. | |
| bool | kleidos:: |
| Decode a snapshot, checking version, length and CRC. | |
| size_t | kleidos:: |
| Encode a session record as [ver][payload LE][crc32 LE]. | |
| bool | kleidos:: |
| Decode a session record, checking version, length and CRC. | |
Coulomb counter (AXP192) | |
| using | kleidos:: |
| Raw counters + ADC rate. | |
| constexpr uint64_t | kleidos:: |
| One count = 65536 × 0.5 mA / (3600 × rate) mAh = this / (3600 × rate) µAh. | |
| constexpr uint64_t | kleidos:: |
| Seconds per hour, for µAh ↔ µA·s conversions. | |
| constexpr uint32_t | kleidos:: |
| Counts below which a coulomb sleep figure is only a bound (±1 count ≥ ±25 %). | |
| uint32_t | kleidos:: |
| µAh one counter count represents, rounded up (a conservative bound). | |
| int64_t | kleidos:: |
| Convert a count difference to µAh (rounded to nearest). | |
| bool | kleidos:: |
| Charge drawn from the cell between two readings: Δout − Δin. | |
| bool | kleidos:: |
| Net charge into the cell between two readings: Δin − Δout. | |
| Estimate | kleidos:: |
| Average sleep current from the charge the counters saw drawn. | |
Rest voltage (open-circuit voltage) | |
| constexpr size_t | kleidos:: |
| Table points at 0, 10, ..., 100 % SoC. | |
| constexpr uint32_t | kleidos:: |
| Shorter sleeps give a bound only. | |
| constexpr int16_t | kleidos:: |
| |ΔT| above 5 °C gives Unknown. | |
| uint16_t | kleidos:: |
| State of charge from a rest voltage, piecewise linear and clamped. | |
| Estimate | kleidos:: |
| Average sleep current from the drop in rest voltage. | |
Labels | |
| const char * | kleidos:: |
| Console token of a quality. | |
| const char * | kleidos:: |
| Console token of a verdict. | |
| const char * | kleidos:: |
| Console token of a BLE mode. | |
| const char * | kleidos:: |
| Console token of a Wi-Fi mode. | |
Typedef Documentation
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/false.
- Parameters
-
Name Meaning ctx Opaque context the channel registered with (e.g. a PowerManager*). out Set to the sampled value on success; untouched on failure.
- Return values
-
Value Meaning true A value was produced in out.false No value this tick.
Enumeration Type Documentation
Basis #
BleMode #
Budget #
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.
Event #
What the caller has to do now.
| Enumerator | |
|---|---|
| None | Nothing is due. |
| EnterPhase | Set up phase Sequencer:: |
| OpenFigures | The settle is over: start measuring the phase. |
| ClosePhase | The phase is over (Sequencer:: |
| Finished | The last phase closed: the run is done. |
| BatteryTimeout | USB never went away: the run is aborted before any phase. |
Quality #
How a figure was obtained, best first.
RunState #
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:: |
SleepKind #
SleepMethod #
StopStatus #
Outcome of a stop request.
Verdict #
WifiMode #
Function Documentation
accountedMs() #
Total time accounted since boot, the open interval included.
- Parameters
-
Name Direction Meaning nowMs in Monotonic time, ms.
- Returns
- Accounted ms (equals
nowMsonce started).
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() #
Native-test alias for ::ringAppend.
Retained so existing tests keep their intent-revealing call name; forwards verbatim to the production ::ringAppend write path.
- Parameters
-
Name Meaning sample Sample to append.
basisName() #
Console token of a basis.
- Parameters
-
Name Direction Meaning b in Basis.
- 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
-
Name Direction Meaning core in Target core for the worker task. priority in FreeRTOS priority for the worker task.
- Return values
-
Value Meaning true Logger task, queue, and vprintf hook installed (or the logger was already running). false Queue or task creation failed; the hook is left in its previous state.
- See also
- shutdown, droppedCount
begin() [2/2] #
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
-
Name Direction Meaning pm in The board's power manager (outlives the meter). profile in The board's power profile (outlives the meter). roles in Indices of the states the meter treats specially.
bleModeName() #
Console token of a BLE mode.
- Parameters
-
Name Direction Meaning m in BLE mode.
- Returns
- "off", "adv", "conn" or "typing".
budgetLine() #
The meter's figure for one phase, beside its expected value if it has one.
- Parameters
-
Name Direction Meaning b in Budget. nowMs in Monotonic time, ms.
- Returns
- The budget line.
budgetName() #
Short name of a phase, as diagnostics print it.
- Parameters
-
Name Direction Meaning b in Budget.
- Returns
- "pin_entry", "ble_peak", "wifi", "standby" or "deep_sleep".
channelCount() #
Number of channels currently registered.
- Returns
- Count in [0, ::
kMaxChannels].
channelName() #
Access a registered channel name by index, in registration order.
- Parameters
-
Name Meaning i Index in [0, channelCount()).
- Returns
- NUL-terminated name, or nullptr if
iis out of range.
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 (
openfalse when no interval was open).
copyRecentSamples() #
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
-
Name Meaning out Destination array. maxSamples Capacity of outin samples.
- Returns
- Number of samples written (min of
maxSamplesand the ring fill).
copySamples() #
Copy an oldest-first snapshot of the recorded samples.
- Parameters
-
Name Meaning out Destination array. maxSamples Capacity of outin samples.
- Returns
- Number of samples written (min of
maxSamplesand the ring fill).
coulombCountsToUah() #
Convert a count difference to µAh (rounded to nearest).
- Parameters
-
Name Direction Meaning counts in Signed count difference. rateHz in ADC rate in Hz.
- Returns
- µAh; 0 when
rateHzis 0.
coulombDeltaUah() #
Net charge into the cell between two readings: Δin − Δout.
- Parameters
-
Name Direction Meaning a in Earlier reading. b in Later reading. outUah out Net charge into the cell, µAh.
- Return values
-
Value Meaning true Comparable readings. false See coulombDrawnUah.
coulombDrawnUah() #
Charge drawn from the cell between two readings: Δout − Δin.
- Parameters
-
Name Direction Meaning a in Earlier reading. b in Later reading. drawnUah out Charge out of the cell, µAh (negative = net charging).
- Return values
-
Value Meaning true Both readings are comparable. false The rate is 0 or changed, or a counter went backwards (cleared or wrapped); drawnUahis untouched.
coulombLsbUah() #
µAh one counter count represents, rounded up (a conservative bound).
- Parameters
-
Name Direction Meaning rateHz in ADC rate in Hz.
- Returns
- µAh per count; 0 when
rateHzis 0.
cpuClockValid() #
Whether a phase may hold the core clock mhz.
- Parameters
-
Name Direction Meaning mhz in Clock in MHz; 0 means the phase holds none.
- Return values
-
Value Meaning true 0, or one of kForcedCpuMhz. false Any other value: a clock the SoC cannot run, or one only a crystal divider gives, which would move the bus clocks too.
decodeRecord() #
Decode a session record, checking version, length and CRC.
- Parameters
-
Name Direction Meaning buf in Encoded bytes. len in Length of buf.out out Decoded record (written only on success).
- Return values
-
Value Meaning true Valid record. false Short buffer, version mismatch or CRC mismatch.
decodeSnapshot() #
Decode a snapshot, checking version, length and CRC.
- Parameters
-
Name Direction Meaning buf in Encoded bytes. len in Length of buf.out out Decoded snapshot (written only on success).
- Return values
-
Value Meaning true Valid snapshot. false Short buffer, version mismatch or CRC mismatch.
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() #
Number of samples overwritten (dropped) since the ring was allocated.
- Returns
- Cumulative dropped-sample count.
enableIdle1Watchdog() #
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
-
Value Meaning true IDLE1 is watched (now, or it already was). false The watchdog is not initialized, or another idle task is already watched.
encodeRecord() #
Encode a session record as [ver][payload LE][crc32 LE].
- Parameters
-
Name Direction Meaning r in Record. buf out Destination. cap in Capacity of buf.
- Returns
- Bytes written (kRecordBytes), or 0 when
capis too small.
encodeSnapshot() #
Encode a snapshot as [ver][payload LE][crc32 LE].
- Parameters
-
Name Direction Meaning s in Snapshot. buf out Destination. cap in Capacity of buf.
- Returns
- Bytes written (kSnapshotBytes), or 0 when
capis too small.
formatReport() #
Format a multi-line plain-text dump. Returns bytes written (excl. NUL).
Always available; emits "(disabled)" line when KLEIDOS_
- Parameters
-
Name Direction Meaning out out Destination buffer. outLen in Capacity of outin bytes.
- Returns
- Bytes written, excluding the terminating NUL.
- See also
- Sample
formatTaskTable() #
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
-
Name Direction Meaning out out Destination buffer of at least outLenbytes.outLen in Buffer capacity in bytes (recommended: 2048 for ~30 tasks).
- Returns
- Number of bytes written, excluding the terminating NUL.
- See also
- snapshot
intervalFigures() #
Figures of the open interval so far, without closing it or sampling.
- Parameters
-
Name Direction Meaning nowMs in Monotonic time, ms.
- Returns
- The figures (
openfalse when no interval is open).
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::
- Return values
-
Value Meaning true A run is active or its teardown is still pending. false Idle.
judge() #
Judge a figure against a limit.
Pass only when hi < limit, fail only when lo > limit, unknown otherwise. A Quality::
- Parameters
-
Name Direction Meaning e in Figure with its interval. limitUa in Budget limit, µA.
- Returns
- Verdict.
logCurrentCore() #
Log the calling core id.
- Parameters
-
Name Direction Meaning tag in Log tag printed alongside the core id.
logHeapStats() #
Log free heap and largest free block (DRAM, 8-bit-capable).
- Parameters
-
Name Direction Meaning tag in Log tag printed before the heap statistics.
logStackHighWaterMark() #
Log the calling task's stack high-water mark via the platform logger.
- Parameters
-
Name Direction Meaning tag in Log tag printed before the high-water mark value.
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() #
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() #
Interval around a measured current: ±(1 mA + 5 %).
- Parameters
-
Name Direction Meaning microamps in Measured current, µA (negative values clamp to 0).
- Returns
- Estimate with Quality::
Measured.
measuresCurrent() #
modelCurrentUa() #
Modeled current of one mode signature.
- Parameters
-
Name Direction Meaning m in Mode signature. k in Board coefficients.
- Returns
- Modeled current in µA (saturates at
UINT32_MAX).
modelEstimate() #
Interval around a modeled current: ±50 % seed, ±20 % calibrated.
- Parameters
-
Name Direction Meaning microamps in Modeled current, µA. calibrated in True for a bench-calibrated profile.
- Returns
- Estimate with modelQuality.
modelQuality() #
Quality label of a model figure.
- Parameters
-
Name Direction Meaning calibrated in True when the profile's coefficients are bench-calibrated.
- Returns
- Quality::
Calibrated or Quality:: Modeled.
onFlushEnter() #
Call right before flushCb does its bus traffic. Captures the start timestamp used by onFlushExit() to compute latency.
- See also
- onFlushExit
onFlushExit() #
Call right after flushCb has pushed its colors. Updates lastFlushUs / maxFlushUs and bumps flushCount.
- See also
- onFlushEnter
onTimerHandlerEnter() #
Call right before the render tick. Records the gap since the previous tick and bumps frameCount.
- See also
- onFlushEnter, onFlushExit
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() #
Length of a plan: the sum of its phases' dwell times.
- Parameters
-
Name Direction Meaning plan in Plan.
- Returns
- Milliseconds from the first phase's setup to the end of the last one (the wait for battery not included).
planValid() #
Whether a plan can run.
- Parameters
-
Name Direction Meaning plan in Plan.
- Return values
-
Value Meaning true 1 to kMaxPhases phases, each with a dwell longer than its settle, a clock cpuClockValid accepts and a backlight level no higher than kMaxBacklightPct. false Empty, too long, a phase with no measuring window, or a phase that holds a clock the board cannot run.
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() #
Console token of a quality.
- Parameters
-
Name Direction Meaning q in Quality.
- Returns
- "meas", "cal", "model", "bound" or "na".
readLoadMilliamps() #
Take a fresh load-current reading (the load_ma telemetry channel).
Three short I2C reads: battery charge, battery discharge and VBUS current.
- Parameters
-
Name Direction Meaning milliamps out Load current in mA on success.
- Return values
-
Value Meaning true Measuring board and the reads succeeded. false Modeled board, not started, or an I2C error.
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() #
Record one loop-tick interval in microseconds.
- Parameters
-
Name Direction Meaning deltaUs in Microseconds since the previous tick.
registerChannel() #
Register a sampling channel.
Not thread-safe: call only during single-threaded board init.
- Parameters
-
Name Meaning name Channel name (e.g. "batt_mv"); must outlive the registry. fn Sampling callback; must not be nullptr. ctx Opaque context passed back to fnon every sample.
- Return values
-
Value Meaning true Registered. false Rejected: name/nullptr, a channel with the same name (case-insensitive) already exists, or the registry is at ::fniskMaxChannels capacity.
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
-
Value Meaning true State reset and ring allocated. false Ring allocation failed.
ringAppend() #
Append one sample to the ring (production write path).
The sampler task calls this once per channel per tick; it owns the append/
- Parameters
-
Name Meaning sample Sample to append.
running() #
Whether the queued logger is installed and draining.
- Return values
-
Value Meaning true begin() 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(). false Lines go straight to the default writer and none is dropped.
- See also
- begin, shutdown, droppedCount
runStateName() #
Console token of a run state.
- Parameters
-
Name Direction Meaning s in Run state.
- Returns
- "idle", "waiting", "settling", "measuring", "done" or "aborted".
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() #
Resolve a CSV channel list to registry indices.
- Parameters
-
Name Meaning csv Comma-separated channel names, or nullptr to select every registered channel in order. Unknown names are ignored (skipped). out Destination array of channel indices. maxOut Capacity of out.
- Returns
- Number of indices written.
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:
- 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 PowerManagerrequires (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. - 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() #
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 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::
- Parameters
-
Name Direction Meaning declaredUa in POWER_; 0 when never measured.DEEP_ SLEEP_ UA calibrated in The profile's coefficients are bench-calibrated.
- Returns
- The estimate.
sleepFromCoulomb() #
Average sleep current from the charge the counters saw drawn.
The interval is ±1 count. Fewer than kCoulombMeasuredMinCounts counts give only a Quality::
- Parameters
-
Name Direction Meaning drawnUah in Charge drawn during the sleep, µAh (see coulombDrawnUah). sleepS in Sleep length, s. rateHz in ADC rate the counts were taken at.
- Returns
- Estimate; Quality::
Unknown when sleepSorrateHzis 0 or the cell charged.
sleepFromVoltageDrop() #
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
-
Name Direction Meaning in in Inputs. t in Rest-voltage table of the cell.
- Returns
- Estimate.
sleepMethodName() #
Console token of a sleep method.
- Parameters
-
Name Direction Meaning m in Method.
- Returns
- "na", "coulomb", "vdrop", "bound" or "model".
snapshot() [1/3] #
snapshot() [2/3] #
Atomic snapshot of the counters. Safe to call from any task.
- Returns
- Current
Samplevalues.
snapshot() [3/3] #
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() #
State of charge from a rest voltage, piecewise linear and clamped.
- Parameters
-
Name Direction Meaning t in Table. mv in Rest voltage, mV.
- Returns
- SoC in permille, 0..1000 (0 for a null table).
start() #
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::
- Parameters
-
Name Meaning config Sampling configuration. config.streamis honored only on the debug-serial surface; callers reachable from the network must leave itfalse(it drives writes into the debug UART).
- Return values
-
Value Meaning true Sampler started. false A run is already active (or its teardown has not finished), no channels were selected, or an allocation failed.
stateFigure() #
Figures of one state, the open interval included.
- Parameters
-
Name Direction Meaning state in State index. nowMs in Monotonic time, ms.
- Returns
- Figures (all zero for a state never entered).
stop() #
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::
A caller on the UI loop task should pass 0: that latches the stop without blocking (answering StopStatus::
- Parameters
-
Name Meaning timeoutMs Milliseconds to wait for the sampler to exit, 0to 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() #
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
-
Name Direction Meaning nowMs in Monotonic time, ms. sig in Current mode signature.
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
-
Value Meaning true USB present. false No USB, or the meter is not started.
verdictName() #
Console token of a verdict.
- Parameters
-
Name Direction Meaning v in Verdict.
- Returns
- "pass", "fail" or "unknown".
wifiModeName() #
Console token of a Wi-Fi mode.
- Parameters
-
Name Direction Meaning m in Wi-Fi mode.
- Returns
- "off", "ap", "ap_client" or "sta".
Variable Documentation
kGenericLipoOcvMv #
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 #
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 #
SessionRecord wire version.
kSampleQueueDepth #
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 ::
kStopPollSliceMs #
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.