Kleidos API Search

In development. It changes without notice.

Topic

GPIO & Buses

GPIO, I2C, SPI, UART, PWM, I2S and ADC, the USB pads, the die's temperature, and the lock of the crypto hardware.

A function whose name ends in FromIsr is for an interrupt; the others are for a task.

kleidos::platform::i2c::begin( { .sdaPin = kSda, .sclPin = kScl, .frequencyHz = 400000 } );
const bool present = kleidos::platform::i2c::probe( kAddress );
See also
I2C Bus, Serial Transport

Files

file src/platform/peripherals/adc.cpp
One-shot ADC sampling implementation.
file src/platform/peripherals/adc.h
One-shot ADC sampling facade.
file src/platform/peripherals/crypto_hw_lock.h
Mutual exclusion between the hardware crypto engines and audio streaming.
file src/platform/peripherals/crypto_hw_lock_logic.h
The hardware-crypto lock's rules, with no RTOS in them.
file src/platform/peripherals/gpio.cpp
Digital GPIO configuration, level, and interrupt implementation.
file src/platform/peripherals/gpio.h
Digital GPIO configuration, level, and interrupt facade.
file src/platform/peripherals/i2c.cpp
I2C master-bus implementation.
file src/platform/peripherals/i2c.h
I2C master-bus facade.
file src/platform/peripherals/i2s.cpp
I2S standard-mode audio implementation.
file src/platform/peripherals/i2s.h
I2S standard-mode (Philips) audio facade.
file src/platform/peripherals/pwm.cpp
PWM (LEDC) output implementation.
file src/platform/peripherals/pwm.h
PWM (LEDC) output facade.
file src/platform/peripherals/sha_engine.h
The SoC's SHA-256 engine as a PBKDF2 chain drives it.
file src/platform/peripherals/spi.cpp
SPI master bus and device implementation.
file src/platform/peripherals/spi.h
SPI master bus and device facade.
file src/platform/peripherals/temperature.cpp
Internal die-temperature sensor implementation.
file src/platform/peripherals/temperature.h
Internal die-temperature sensor facade.
file src/platform/peripherals/uart.h
UART port facade.
file src/platform/peripherals/usb_phy_pads.h
Whether this build can isolate the SoC's USB PHY pads before a deep sleep.

Classes

struct kleidos::platform::adc::Config
Per-pin ADC configuration. More about kleidos::platform::adc::Config
class kleidos::platform::crypto_hw::ScopedLock
RAII crypto-side take of the lock, for one operation. More about kleidos::platform::crypto_hw::ScopedLock
class kleidos::platform::crypto_hw::AudioHold
The audio side's hold on the lock, kept across the blocks of a sound. More about kleidos::platform::crypto_hw::AudioHold
struct kleidos::platform::crypto_hw::Stats
Counters of the lock since boot (or since resetStats), for the console. More about kleidos::platform::crypto_hw::Stats
struct kleidos::platform::gpio::Config
Full pin configuration descriptor. More about kleidos::platform::gpio::Config
struct kleidos::platform::gpio::PadState
Live state of one pad, read back from the hardware. More about kleidos::platform::gpio::PadState
struct kleidos::platform::i2c::Config
I2C master-bus configuration. More about kleidos::platform::i2c::Config
struct kleidos::platform::i2c::Counters
What the bus has carried since boot: every read, write and write-read a caller asked for, and how many of them failed. Probes are not counted, so a scan of the bus does not move either number. More about kleidos::platform::i2c::Counters
struct kleidos::platform::i2s::Config
I2S standard-mode configuration. More about kleidos::platform::i2s::Config
struct kleidos::platform::i2s::Stats
Counters of the open channels since boot, and the ring they run. More about kleidos::platform::i2s::Stats
struct kleidos::platform::pwm::Config
PWM channel configuration. More about kleidos::platform::pwm::Config
struct kleidos::platform::sha_engine::ResumeRegs
The ESP32-S3 engine's register moves, inline, for the chain template. More about kleidos::platform::sha_engine::ResumeRegs
struct kleidos::platform::spi::BusConfig
SPI bus (shared lines) configuration. More about kleidos::platform::spi::BusConfig
struct kleidos::platform::spi::DeviceConfig
SPI device (per-chip-select) configuration. More about kleidos::platform::spi::DeviceConfig
struct kleidos::platform::spi::QueuedTransaction
Opaque slot for one in-flight queued (interrupt-DMA) SPI transaction. More about kleidos::platform::spi::QueuedTransaction
class kleidos::platform::spi::Device
RAII handle to a configured SPI device; frees the device on destruction. More about kleidos::platform::spi::Device
struct kleidos::platform::uart::Config
UART port configuration (8N1, no flow control). More about kleidos::platform::uart::Config

Macros

#defineKLEIDOS_SLEEP_HAS_USB_PHY_PADS

Typedefs

usingkleidos::platform::crypto_hw::ReentryHandler
Host builds only: what a take by the lock's own holder does instead of stopping.
usingkleidos::platform::crypto_hw::ContentionHook
Called by a crypto caller about to block on the audio side's hold.
usingkleidos::platform::gpio::Pin
GPIO pin number (-1 = unassigned).
usingkleidos::platform::gpio::IsrHandler
GPIO interrupt callback; runs in ISR context.
usingkleidos::platform::gpio::WakeHandler
Level-wake callback; runs in ISR context, gets its pin.

Enumerations

enum class kleidos::platform::adc::Attenuation : uint8_t { kleidos::platform::adc::Attenuation::Db0 , kleidos::platform::adc::Attenuation::Db25 , kleidos::platform::adc::Attenuation::Db6 , kleidos::platform::adc::Attenuation::Db12 }
Input attenuation, setting the full-scale measurable voltage. More about kleidos::platform::adc::Attenuation
enum class kleidos::platform::gpio::Direction : uint8_t { kleidos::platform::gpio::Direction::Disabled , kleidos::platform::gpio::Direction::Input , kleidos::platform::gpio::Direction::Output , kleidos::platform::gpio::Direction::InputOutput }
Pin data direction. More about kleidos::platform::gpio::Direction
enum class kleidos::platform::gpio::Pull : uint8_t { kleidos::platform::gpio::Pull::None , kleidos::platform::gpio::Pull::Up , kleidos::platform::gpio::Pull::Down , kleidos::platform::gpio::Pull::UpDown }
Internal pull-resistor selection. More about kleidos::platform::gpio::Pull
enum class kleidos::platform::gpio::InterruptTrigger : uint8_t { kleidos::platform::gpio::InterruptTrigger::Disabled, kleidos::platform::gpio::InterruptTrigger::RisingEdge, kleidos::platform::gpio::InterruptTrigger::FallingEdge, kleidos::platform::gpio::InterruptTrigger::AnyEdge, kleidos::platform::gpio::InterruptTrigger::LowLevel, kleidos::platform::gpio::InterruptTrigger::HighLevel }
Interrupt trigger condition. More about kleidos::platform::gpio::InterruptTrigger
enum class kleidos::platform::i2s::SlotMode : uint8_t { kleidos::platform::i2s::SlotMode::Mono , kleidos::platform::i2s::SlotMode::Stereo }
Channel slot mode. More about kleidos::platform::i2s::SlotMode
enum class kleidos::platform::i2s::BitsPerSample : uint8_t { kleidos::platform::i2s::BitsPerSample::Bits16 , kleidos::platform::i2s::BitsPerSample::Bits24 , kleidos::platform::i2s::BitsPerSample::Bits32 }
Sample width in bits. More about kleidos::platform::i2s::BitsPerSample
enum class kleidos::platform::pwm::ClockSource : uint8_t { kleidos::platform::pwm::ClockSource::Unknown, kleidos::platform::pwm::ClockSource::Apb, kleidos::platform::pwm::ClockSource::Xtal, kleidos::platform::pwm::ClockSource::RcFast, kleidos::platform::pwm::ClockSource::RefTick }
The clock a PWM timer counts, as the hardware reports it. More about kleidos::platform::pwm::ClockSource
enum class kleidos::platform::sha_engine::Kind : uint8_t { kleidos::platform::sha_engine::Kind::None , kleidos::platform::sha_engine::Kind::Resume , kleidos::platform::sha_engine::Kind::Restart }
What this SoC's SHA engine can do for a PBKDF2 chain. More about kleidos::platform::sha_engine::Kind
enum class kleidos::platform::spi::Host : uint8_t { kleidos::platform::spi::Host::Spi2 , kleidos::platform::spi::Host::Spi3 }
SPI host peripheral selection. More about kleidos::platform::spi::Host

Functions

boolkleidos::platform::adc::configurePin (const Config &config)
Configure a pin for ADC sampling.
intkleidos::platform::adc::readRaw (int pin)
Read a raw ADC count from a configured pin.
intkleidos::platform::adc::readMilliVolts (int pin)
Read calibrated millivolts from a configured pin.
voidkleidos::platform::adc::end ()
Release ADC resources.
boolkleidos::platform::crypto_hw::cryptoWaiting ()
True while any crypto caller is blocked on the lock.
voidkleidos::platform::crypto_hw::setContentionHook (ContentionHook hook)
Install the hook a crypto caller calls before it blocks on the audio side's hold.
Statskleidos::platform::crypto_hw::stats ()
Read the lock's counters (crypto takes and waits, audio holds, refusals and yields, the longest yield, overruns and re-entries).
voidkleidos::platform::crypto_hw::resetStats ()
Zero the counters; the lock itself is untouched.
voidkleidos::platform::crypto_hw::setReentryHandlerForTest (ReentryHandler handler)
Host builds only: install what a ScopedLock taken by the task that already holds the lock does.
boolkleidos::platform::i2c::begin (const Config &config)
Initialize the I2C master bus.
voidkleidos::platform::i2c::end ()
Tear down the bus.
boolkleidos::platform::i2c::ready ()
True when the I2C bus is initialized.
boolkleidos::platform::i2c::probe (uint8_t address, uint32_t timeoutMs=0)
Probe for a device on the bus by sending its address.
boolkleidos::platform::i2c::read (uint8_t address, void *data, size_t length, uint32_t timeoutMs=0)
Read bytes from an I2C device.
boolkleidos::platform::i2c::write (uint8_t address, const void *data, size_t length, uint32_t timeoutMs=0)
Write bytes to an I2C device.
boolkleidos::platform::i2c::writeParts (uint8_t address, const void *head, size_t headLength, const void *body, size_t bodyLength, uint32_t timeoutMs=0)
Write two buffers to an I2C device as one transaction.
boolkleidos::platform::i2c::setDeviceFrequency (uint8_t address, uint32_t frequencyHz)
Give one device a bus clock of its own.
boolkleidos::platform::i2c::writeRead (uint8_t address, const void *writeData, size_t writeLength, void *readData, size_t readLength, uint32_t timeoutMs=0)
Write then repeated-start read in a single transaction.
Counterskleidos::platform::i2c::counters ()
Return the transfer and error counts since boot.
uint32_tkleidos::platform::i2c::defaultTimeoutMs ()
Return the currently configured default transaction timeout.
constexpr uint32_tkleidos::platform::i2s::ringDescCount (const Config &config)
DMA buffers config asks for, its 0 resolved to ESP-IDF's default.
constexpr uint32_tkleidos::platform::i2s::ringFrameCount (const Config &config)
Frames per DMA buffer config asks for, its 0 resolved to ESP-IDF's default.
constexpr uint64_tkleidos::platform::i2s::ringFrames (const Config &config)
Frames the whole ring holds.
constexpr uint32_tkleidos::platform::i2s::ringMs (const Config &config)
How long the whole ring plays, in milliseconds, rounded up.
constexpr boolkleidos::platform::i2s::sameShape (const Config &a, const Config &b)
Whether two configurations open channels of the same shape.
boolkleidos::platform::i2s::begin (const Config &config)
Open the I2S peripheral in standard (Philips) mode.
voidkleidos::platform::i2s::end ()
Close the channels: stop them and keep them allocated.
Statskleidos::platform::i2s::stats ()
Read the overflow counters and the ring in use.
boolkleidos::platform::i2s::pause ()
Stop the open channels without releasing them.
boolkleidos::platform::i2s::resume ()
Restart the channels pause stopped.
boolkleidos::platform::i2s::ready ()
True when the I2S peripheral is initialized.
boolkleidos::platform::i2s::write (const void *data, size_t length, size_t &bytesWritten, uint32_t timeoutMs)
Write interleaved PCM samples to the codec.
boolkleidos::platform::i2s::read (void *data, size_t length, size_t &bytesRead, uint32_t timeoutMs)
Read interleaved PCM samples from the codec ADC/microphone.
boolkleidos::platform::pwm::configure (const Config &config)
Configure a PWM channel.
boolkleidos::platform::pwm::setDuty (uint8_t channel, uint32_t duty)
Set the raw duty value for a channel.
boolkleidos::platform::pwm::setFrequency (uint8_t timer, uint32_t frequencyHz)
Change a timer's frequency, keeping its clock, its resolution and the raw duty of every channel on it.
boolkleidos::platform::pwm::setDutyPercent (uint8_t channel, uint8_t percent)
Set the duty as a percentage (0-100) for a channel.
boolkleidos::platform::pwm::stop (uint8_t channel, bool idleHigh=false)
Stop PWM output and park the pin at idle level.
ClockSourcekleidos::platform::pwm::timerClockSource (uint8_t timer)
Read back the clock a PWM timer counts.
const char *kleidos::platform::pwm::clockSourceName (ClockSource source)
Name of a timer clock source, as the console prints it.
uint32_tkleidos::platform::pwm::timerFrequencyHz (uint8_t timer)
Read back the frequency a PWM timer runs at.
uint32_tkleidos::platform::pwm::maxDuty (uint8_t resolutionBits)
Return the maximum raw duty value for a given resolution.
boolkleidos::platform::sha_engine::acquire ()
Take the SHA engine for one derivation and set it to SHA-256.
voidkleidos::platform::sha_engine::release ()
Give the engine back (its lock and its clock).
boolkleidos::platform::sha_engine::firstBlockState (const uint8_t *block, uint32_t *stateOut)
Hash block as the first block of a message and return the state the engine holds, in engine order.
voidkleidos::platform::sha_engine::scrub ()
Overwrite what the engine still holds of the last derivation: zeros to the state (SHA_H) and to all 16 text words (SHA_TEXT).
boolkleidos::platform::spi::initializeBus (const BusConfig &config)
Initialize an SPI bus with shared-line pins.
boolkleidos::platform::spi::freeBus (Host host)
Free a previously initialized SPI bus.
boolkleidos::platform::spi::busInitialized (Host host)
Report whether a host's shared bus is currently initialized.
Devicekleidos::platform::spi::addDevice (const DeviceConfig &config)
Attach a device to an initialized SPI bus.
boolkleidos::platform::spi::transmit (Device &device, const uint8_t *txData, size_t txSize, uint8_t *rxData=nullptr, size_t rxSize=0, bool keepCsActive=false)
Perform a full- or half-duplex SPI transfer.
boolkleidos::platform::spi::readWithDummy (Device &device, uint8_t *rxData, size_t rxSize, uint8_t dummyBits, bool keepCsActive=false)
Half-duplex read of rxSize bytes preceded by dummyBits idle clocks.
boolkleidos::platform::spi::queueTransmit (Device &device, QueuedTransaction &transaction, const uint8_t *txData, size_t txSize, bool keepCsActive=false)
Queue a write-only transfer for interrupt-driven DMA (non-blocking).
boolkleidos::platform::spi::acquireBus (Device &device)
Acquire exclusive use of the bus for device until releaseBus.
voidkleidos::platform::spi::releaseBus (Device &device)
Release a bus previously taken with acquireBus.
boolkleidos::platform::spi::awaitQueued (Device &device, QueuedTransaction *&completed)
Block until the next queued transaction completes and reclaim it.
boolkleidos::platform::temperature::readCelsius (float &celsius)
Read the SoC internal die temperature in degrees Celsius.
boolkleidos::platform::uart::begin (const Config &config)
Install the UART driver and configure the port.
voidkleidos::platform::uart::end ()
Delete the driver and release the port (no-op when idle).
boolkleidos::platform::uart::ready ()
True when a port is installed and ready.
intkleidos::platform::uart::read (uint8_t *buffer, size_t maxLen)
Non-blocking read of pending RX bytes.
intkleidos::platform::uart::write (const uint8_t *data, size_t len)
Queue bytes for transmission.
voidkleidos::platform::uart::flushInput ()
Drop all pending RX bytes from the driver ring buffer.
voidkleidos::platform::uart::flushOutput (uint32_t timeoutMs)
Block until the TX FIFO drains, bounded by a timeout.

Variables

constexpr uint32_tkleidos::platform::crypto_hw::kAudioYieldBudgetMs
Longest a crypto caller may wait for the audio side, in milliseconds.
constexpr uint32_tkleidos::platform::crypto_hw::kAudioBackoffMs
How long the audio side sleeps, in milliseconds, before it looks again while a crypto caller waits.
constexpr uint32_tkleidos::platform::i2s::kDefaultDmaDescCount
ESP-IDF's DMA buffer count, used when Config::dmaDescCount is 0.
constexpr uint32_tkleidos::platform::i2s::kDefaultDmaFrameCount
ESP-IDF's frames per DMA buffer, used when Config::dmaFrameCount is 0.
constexpr Kindkleidos::platform::sha_engine::kKind
This build's engine.
constexpr size_tkleidos::platform::sha_engine::kStateWords
Words in a SHA-256 state, and in each half of a message block.
constexpr size_tkleidos::platform::sha_engine::kBlockBytes
Bytes in one SHA-256 message block.
constexpr uint32_tkleidos::platform::sha_engine::kBusyPollLimit

Configuration

boolkleidos::platform::gpio::configure (const Config &config)
Apply a full pin configuration.
boolkleidos::platform::gpio::isValid (Pin pin)
True when pin is a usable GPIO number.
boolkleidos::platform::gpio::configureInput (Pin pin, Pull pull=Pull::None, InterruptTrigger interrupt=InterruptTrigger::Disabled)
Configure a pin as digital input.
boolkleidos::platform::gpio::configureOutput (Pin pin, bool initialHigh=false, bool openDrain=false)
Configure a pin as digital output.
boolkleidos::platform::gpio::resetPin (Pin pin)
Reset a pin to its default GPIO state.
boolkleidos::platform::gpio::setDirection (Pin pin, Direction direction)
Change a pin's direction, keeping its pulls, interrupt and input routing.

Deep-sleep hold

boolkleidos::platform::gpio::holdEnable (Pin pin)
Latch a pad's current output level so it survives resets and deep sleep.
boolkleidos::platform::gpio::holdDisable (Pin pin)
Release a hold previously latched by holdEnable.
boolkleidos::platform::gpio::isHeld (Pin pin)
True when this facade latched pin and nothing has released it.

Level access

boolkleidos::platform::gpio::setLevel (Pin pin, bool high)
Drive an output pin high or low.
boolkleidos::platform::gpio::level (Pin pin)
Read the current pin level.

Diagnostics

boolkleidos::platform::gpio::readPadState (Pin pin, PadState &out)
Read a pad's live routing and electrical state.

Interrupts

boolkleidos::platform::gpio::attachIsr (Pin pin, InterruptTrigger trigger, IsrHandler handler)
Register an ISR for a GPIO pin.
voidkleidos::platform::gpio::detachIsr (Pin pin)
Remove a previously registered ISR for a GPIO pin.

Light sleep

voidkleidos::platform::gpio::handOver (Pin pin)
Give up this facade's output claim on a pad a driver is about to take.
voidkleidos::platform::gpio::takeBack (Pin pin)
Drop whatever output claim a driver left on a pad it is done with.
voidkleidos::platform::gpio::keepThroughLightSleep (Pin pin)
Keep a pad's configuration while the chip light-sleeps.
boolkleidos::platform::gpio::attachWakeHandler (Pin pin, WakeHandler handler)
Attach the handler a level wake calls, with the pin's interrupt off.
boolkleidos::platform::gpio::armLevelWake (Pin pin, bool wakeHigh)
Arm a pin to raise its interrupt at a level, and to wake a light sleep.
voidkleidos::platform::gpio::disarmLevelWake (Pin pin)
Undo armLevelWake, leaving the pin with no wake and no interrupt.

Back to the top

Macro Definition Documentation

KLEIDOS_SLEEP_HAS_USB_PHY_PADS #

#define KLEIDOS_SLEEP_HAS_USB_PHY_PADS

1 where this build can isolate the SoC's USB PHY pads before a deep sleep (an ESP32-S3 target), 0 where there is no such pad to isolate. Every site that tests it also spells defined( ESP_PLATFORM ), which is redundant (the macro is 0 without it) and there so that a check of the build can see that a reader of an ESP_PLATFORM-only object is itself ESP_PLATFORM-only.

Back to the top

Typedef Documentation

ContentionHook #

using kleidos::platform::crypto_hw::ContentionHook

Called by a crypto caller about to block on the audio side's hold.

Runs on the crypto caller's task, outside any lock. It must not block (the speaker driver posts a wake item with no wait), and it may run more than once for one wait.

Back to the top

Enumeration Type Documentation

Attenuation #

enum class kleidos::platform::adc::Attenuation : uint8_t

Input attenuation, setting the full-scale measurable voltage.

Enumerator
Db0 

0 dB (smallest range).

Db25 

2.5 dB.

Db6 

6 dB.

Db12 

12 dB (largest range).

BitsPerSample #

enum class kleidos::platform::i2s::BitsPerSample : uint8_t

Sample width in bits.

Enumerator
Bits16 

16-bit samples.

Bits24 

24-bit samples.

Bits32 

32-bit samples.

ClockSource #

enum class kleidos::platform::pwm::ClockSource : uint8_t

The clock a PWM timer counts, as the hardware reports it.

Enumerator
Unknown 

Not readable (the native build, or a source this facade never selects).

Apb 

The APB bus clock: 80 MHz off the PLL, the crystal while idle under the floor.

Xtal 

The 40 MHz crystal (ESP32-S3).

RcFast 

The internal fast RC oscillator (about 8 MHz on the classic ESP32).

RefTick 

REF_TICK, 1 MHz whatever the APB clock runs at (classic ESP32).

Direction #

enum class kleidos::platform::gpio::Direction : uint8_t

Pin data direction.

Enumerator
Disabled 

Pad disabled (high-impedance).

Input 

Input only.

Output 

Output only.

InputOutput 

Bidirectional (read-back enabled).

Host #

enum class kleidos::platform::spi::Host : uint8_t

SPI host peripheral selection.

Enumerator
Spi2 

SPI2 host.

Spi3 

SPI3 host.

InterruptTrigger #

enum class kleidos::platform::gpio::InterruptTrigger : uint8_t

Interrupt trigger condition.

Enumerator
Disabled 

No interrupt.

RisingEdge 

Trigger on low-to-high transition.

FallingEdge 

Trigger on high-to-low transition.

AnyEdge 

Trigger on either edge.

LowLevel 

Trigger while the level is low.

HighLevel 

Trigger while the level is high.

Kind #

enum class kleidos::platform::sha_engine::Kind : uint8_t

What this SoC's SHA engine can do for a PBKDF2 chain.

Enumerator
None 

No engine (the native host).

Resume 

Loads a midstate: ESP32-S3 (SOC_SHA_SUPPORT_RESUME).

Restart 

Starts from the initial value only: classic ESP32 (SOC_SHA_SUPPORT_PARALLEL_ENG).

Pull #

enum class kleidos::platform::gpio::Pull : uint8_t

Internal pull-resistor selection.

Enumerator
None 

No internal pull.

Up 

Pull-up enabled.

Down 

Pull-down enabled.

UpDown 

Both pull-up and pull-down enabled.

SlotMode #

enum class kleidos::platform::i2s::SlotMode : uint8_t

Channel slot mode.

Enumerator
Mono 

Single-channel audio.

Stereo 

Two-channel audio.

Back to the top

Function Documentation

acquire() #

bool kleidos::platform::sha_engine::acquire()
nodiscard

Take the SHA engine for one derivation and set it to SHA-256.

Blocks on ESP-IDF's SHA/AES lock, which every user of the engine holds: its clock enable resets the engine and is not reference counted.

Returns
True (the ESP32-S3 lock is a blocking take).

acquireBus() #

bool kleidos::platform::spi::acquireBus(Device & device)

Acquire exclusive use of the bus for device until releaseBus.

Required around a run of queueTransmit calls that use keepCsActive, so the chip-select line stays asserted across the whole run. Blocks other devices on a shared bus for the duration.

Parameters
NameDirectionMeaning
devicein, outDevice handle from addDevice().
Return values
ValueMeaning
trueBus acquired.
falseNo device or the driver reported an error.

addDevice() #

Device kleidos::platform::spi::addDevice(const DeviceConfig & config)

Attach a device to an initialized SPI bus.

Parameters
NameDirectionMeaning
configinDevice chip-select, clock speed, mode, and queue settings.
Returns
RAII Device handle; check valid() before use.

armLevelWake() #

bool kleidos::platform::gpio::armLevelWake(Pin pin, bool wakeHigh)

Arm a pin to raise its interrupt at a level, and to wake a light sleep.

On a build with automatic light sleep the pin is also armed as a light-sleep wake source; on every other build it only raises the interrupt, which is what ends an idle wait there.

Parameters
NameDirectionMeaning
pininGPIO pin number with a handler from attachWakeHandler.
wakeHighinTrue to fire while the pin reads high, false while low.
Return values
ValueMeaning
trueArmed.
falseInvalid pin, no handler attached, the driver refused the configuration, or this is the native build.

attachIsr() #

bool kleidos::platform::gpio::attachIsr(Pin pin, InterruptTrigger trigger, IsrHandler handler)

Register an ISR for a GPIO pin.

Parameters
NameDirectionMeaning
pininGPIO pin number.
triggerinEdge or level condition that fires the interrupt.
handlerinCallback to invoke from ISR context.
Return values
ValueMeaning
trueISR registered successfully.
falseDriver refused the registration (invalid pin, handler, or trigger).
Note
handler runs in ISR context and must only call ISR-safe APIs (the *FromIsr facade helpers, task notifications, etc.). It must not block, allocate, log through a non-DRAM logger, or take a mutex.

attachWakeHandler() #

bool kleidos::platform::gpio::attachWakeHandler(Pin pin, WakeHandler handler)

Attach the handler a level wake calls, with the pin's interrupt off.

The pin's interrupt stays disabled until armLevelWake. When an armed pin fires, the interrupt disables itself before handler runs, so a level that stays asserted raises it once.

Parameters
NameDirectionMeaning
pininGPIO pin number, configured as an input by its owner.
handlerinCallback in ISR context (IRAM); gets pin.
Return values
ValueMeaning
trueAttached.
falseInvalid pin or handler, the ISR service is unavailable, or this is the native build.

awaitQueued() #

bool kleidos::platform::spi::awaitQueued(Device & device, QueuedTransaction *& completed)

Block until the next queued transaction completes and reclaim it.

Reaps one in-flight transaction queued by queueTransmit in FIFO order. The returned slot (and its staging buffer) may be reused for the next chunk.

Parameters
NameDirectionMeaning
devicein, outDevice handle from addDevice().
completedoutSet to the transaction that finished (may be null on error).
Return values
ValueMeaning
trueA transaction completed and is returned via completed.
falseNo device, nothing in flight, or the driver reported an error.

begin() [1/3] #

bool kleidos::platform::i2c::begin(const Config & config)

Initialize the I2C master bus.

The bus is reset once it exists (nine clocks and a STOP), so a chip that a reset of the SoC caught in the middle of a transfer lets go of SDA before the first transfer.

Parameters
NameDirectionMeaning
configinBus pins, frequency, and timeout settings.
Return values
ValueMeaning
trueBus initialized and ready for transactions.
falseDriver reported an initialization error.

begin() [2/3] #

bool kleidos::platform::i2s::begin(const Config & config)

Open the I2S peripheral in standard (Philips) mode.

The first call allocates a TX channel when doutPin >= 0 and an RX channel when dinPin >= 0, with the ring config asks for, and leaves them running. A later call reopens the channels already allocated, stopped first if they run, with config's pins, rate, width and slots; the transmit ring is filled with silence before it restarts.

Parameters
NameDirectionMeaning
configinPort, pins, sample rate, bit-width, slot mode and ring.
Return values
ValueMeaning
trueThe requested channels are open and running.
falseThe driver reported an error, or channels of another shape (sameShape) are allocated: they are never deleted to make room.

begin() [3/3] #

bool kleidos::platform::uart::begin(const Config & config)

Install the UART driver and configure the port.

While the port is open, on a build with power management, the chip neither light-sleeps (ESP_PM_NO_LIGHT_SLEEP: the UART receives nothing while it sleeps) nor drops its APB clock (ESP_PM_APB_FREQ_MAX: the line rate is derived from it, and the idle floor would halve it). end() lets go of both.

Parameters
NameDirectionMeaning
configinPins, line rate, peripheral number, and RX ring size.
Return values
ValueMeaning
truePort installed and ready for reads/writes.
falseDriver error, or the facade is already holding a port (one client at a time; call end() first).

busInitialized() #

bool kleidos::platform::spi::busInitialized(Host host)

Report whether a host's shared bus is currently initialized.

Read-only diagnostic: a debug console can confirm the display/peripheral bus came up without attempting a transfer.

Parameters
NameDirectionMeaning
hostinHost peripheral to query.
Return values
ValueMeaning
trueThe bus for host is initialized.
falseThe bus for host is not initialized.

clockSourceName() #

const char * kleidos::platform::pwm::clockSourceName(ClockSource source)

Name of a timer clock source, as the console prints it.

Parameters
NameDirectionMeaning
sourceinSource.
Returns
"APB", "XTAL", "RC_FAST", "REF_TICK" or "unknown".

configure() [1/2] #

bool kleidos::platform::gpio::configure(const Config & config)

Apply a full pin configuration.

Parameters
NameDirectionMeaning
configinPin direction, pull, and interrupt descriptor.
Return values
ValueMeaning
trueConfiguration applied successfully.
falseConfiguration error reported by the driver.

configure() [2/2] #

bool kleidos::platform::pwm::configure(const Config & config)

Configure a PWM channel.

With automatic light sleep built the timer runs from the internal fast RC oscillator, the one clock that keeps running through a light sleep, and the channel is kept alive through it (frequency times 2^bits up to the oscillator's rate: about 8 MHz on the classic ESP32, 17.5 MHz on the ESP32-S3). Otherwise, without the idle floor the driver picks the timer's clock; with it the timer runs from a clock that does not follow the APB bus: the crystal on the ESP32-S3; on the classic ESP32, whose LEDC has no crystal input, REF_TICK when it can make the rate at the resolution asked (frequency times 2^bits up to 1 MHz), the internal fast RC oscillator otherwise.

Parameters
NameDirectionMeaning
configinChannel, timer, frequency, resolution, and polarity settings.
Return values
ValueMeaning
truePWM channel configured successfully.
falseDriver reported a configuration error.

configureInput() #

bool kleidos::platform::gpio::configureInput(Pin pin, Pull pull = Pull::None, InterruptTrigger interrupt = InterruptTrigger::Disabled)

Configure a pin as digital input.

Parameters
NameDirectionMeaning
pininGPIO pin number to configure.
pullinInternal pull-resistor selection.
interruptinEdge or level interrupt trigger.
Return values
ValueMeaning
truePin configured as input.
falseConfiguration error reported by the driver.

configureOutput() #

bool kleidos::platform::gpio::configureOutput(Pin pin, bool initialHigh = false, bool openDrain = false)

Configure a pin as digital output.

The level is written before the driver is enabled, so the pin goes straight from what it was to initialHigh: no edge to the level it was last set to.

Parameters
NameDirectionMeaning
pininGPIO pin number to configure.
initialHighinInitial level; true drives the pin high on configure.
openDraininTrue to use open-drain mode.
Return values
ValueMeaning
truePin configured as output.
falseConfiguration error reported by the driver.

configurePin() #

bool kleidos::platform::adc::configurePin(const Config & config)

Configure a pin for ADC sampling.

Parameters
NameDirectionMeaning
configinPin and attenuation settings.
Return values
ValueMeaning
truePin configured for ADC sampling.
falseDriver reported a configuration error.

counters() #

Counters kleidos::platform::i2c::counters()

Return the transfer and error counts since boot.

Returns
Both counts; zero on the native host build.

cryptoWaiting() #

bool kleidos::platform::crypto_hw::cryptoWaiting()

True while any crypto caller is blocked on the lock.

The audio side reads it between blocks: when it turns true, the player yields within kAudioYieldBudgetMs.

Return values
ValueMeaning
trueA crypto caller is waiting.
falseNone is.

defaultTimeoutMs() #

uint32_t kleidos::platform::i2c::defaultTimeoutMs()

Return the currently configured default transaction timeout.

Returns
Default timeout in milliseconds.

detachIsr() #

void kleidos::platform::gpio::detachIsr(Pin pin)

Remove a previously registered ISR for a GPIO pin.

Parameters
NameDirectionMeaning
pininGPIO pin number.
Note
Must be called from task context (not from the ISR it unregisters); the GPIO ISR service treats handler removal as a deferred operation that requires the scheduler to be running.

disarmLevelWake() #

void kleidos::platform::gpio::disarmLevelWake(Pin pin)

Undo armLevelWake, leaving the pin with no wake and no interrupt.

Parameters
NameDirectionMeaning
pininGPIO pin number.

end() [1/2] #

void kleidos::platform::i2s::end()

Close the channels: stop them and keep them allocated.

Stops their bit clock and DMA (and the power-management lock a running channel holds) and marks the facade not ready, so write refuses until the next begin. Nothing is deleted (see the file comment). Safe to call repeatedly, and before begin.

end() [2/2] #

void kleidos::platform::uart::end()

Delete the driver and release the port (no-op when idle).

Also returns both pads to hi-Z inputs (no pulls) so a peripheral whose power rail is later cut is not backfed through a still-driven TX line, and releases the clock holds begin() took.

firstBlockState() #

bool kleidos::platform::sha_engine::firstBlockState(const uint8_t * block, uint32_t * stateOut)
nodiscard

Hash block as the first block of a message and return the state the engine holds, in engine order.

Our own register sequence: the 16 text words, START, a bounded wait, the eight state words.

Parameters
NameDirectionMeaning
blockinOne ::kBlockBytes-byte block (an HMAC pad block).
stateOutoutReceives ::kStateWords words; wiped on a refusal.
Return values
ValueMeaning
truestateOut holds the state.
falseThe engine stayed busy past ::kBusyPollLimit polls, or the state read back all zero.

flushOutput() #

void kleidos::platform::uart::flushOutput(uint32_t timeoutMs)

Block until the TX FIFO drains, bounded by a timeout.

Parameters
NameDirectionMeaning
timeoutMsinMaximum time to wait for the drain, in milliseconds.

freeBus() #

bool kleidos::platform::spi::freeBus(Host host)

Free a previously initialized SPI bus.

Parameters
NameDirectionMeaning
hostinHost peripheral to release.
Return values
ValueMeaning
trueBus was initialized and has been released.
falseBus was not initialized for host.

handOver() #

void kleidos::platform::gpio::handOver(Pin pin)

Give up this facade's output claim on a pad a driver is about to take.

Since ESP-IDF 6.1, configuring a pad as an output records a claim on it, and a driver (SPI, I2C) that then routes the pad reports a conflict when it finds the claim. A board parks a chip select or a bus pad from here before the driver that owns it comes up; the SPI and I2C facades call this for every pad they hand to ESP-IDF so that hand-over is not reported as a conflict. Only the record of the claim goes: the pad keeps its level and direction.

Parameters
NameDirectionMeaning
pininGPIO pin number; a negative or invalid one is ignored.

holdDisable() #

bool kleidos::platform::gpio::holdDisable(Pin pin)

Release a hold previously latched by holdEnable.

Parameters
NameDirectionMeaning
pininGPIO pin number.
Return values
ValueMeaning
trueHold released (or the pad was not held).
falseInvalid pin or the driver reported an error.

holdEnable() #

bool kleidos::platform::gpio::holdEnable(Pin pin)

Latch a pad's current output level so it survives resets and deep sleep.

Wraps gpio_hold_en. Once held, the pad freezes at its present drive level and ignores further direction/level changes until holdDisable (or resetPin) releases it. Use to keep an unused peripheral's control pins pinned to a safe state (a radio RST held low, a codec MCLK held low, a peripheral power rail held off) while the SoC is in deep sleep, protecting the production sleep's floor. For the latch to persist through deep sleep the deep-sleep hold must also be armed, which kleidos::platform::sleep::deepSleepStart does before entering sleep.

Parameters
NameDirectionMeaning
pininGPIO pin number. Must be a hold-capable pad and already driven to the intended level before this call.
Return values
ValueMeaning
trueHold latched.
falseInvalid pin or the driver rejected the hold.

initializeBus() #

bool kleidos::platform::spi::initializeBus(const BusConfig & config)

Initialize an SPI bus with shared-line pins.

Parameters
NameDirectionMeaning
configinHost, clock, MISO/MOSI pins, and DMA settings.
Return values
ValueMeaning
trueBus initialized successfully.
falseBus was already initialized or the driver reported an error.

isHeld() #

bool kleidos::platform::gpio::isHeld(Pin pin)
nodiscard

True when this facade latched pin and nothing has released it.

A hold is otherwise write-only: ESP-IDF exposes no way to read back RTC_CNTL_PAD_HOLD_REG or the digital hold, so the facade remembers what it latched. That makes the answer trustworthy for every deliberate hold in the firmware, which all go through holdEnable, and blind to one latched by a raw ESP-IDF call or left over from a previous boot. kleidos::platform::sleep::isolateUsbPadsForDeepSleep reads it so a pad a board holds on purpose is never isolated out from under it.

Declared only where KLEIDOS_SLEEP_HAS_USB_PHY_PADS is 1 (platform/ usb_phy_pads.h), which is to say only where that one caller is compiled. The record costs static DRAM in every image that keeps it, and on a board with no USB PHY pad nothing would ever read it — but the reason the declaration goes rather than the answer being hardcoded to false is correctness, not bytes: an unconditional false reads as "this pad is free to isolate", which is the one answer that could strand a board asleep. A caller on a board that keeps no record gets a compile error instead, and every such caller is in a position to say what it should do there.

Parameters
NameDirectionMeaning
pininGPIO pin number.
Return values
ValueMeaning
trueholdEnable latched this pin since boot and no holdDisable or resetPin released it.
falseNot held by this facade, or an invalid pin.

isValid() #

bool kleidos::platform::gpio::isValid(Pin pin)

True when pin is a usable GPIO number.

Parameters
NameDirectionMeaning
pininGPIO pin number to validate.
Return values
ValueMeaning
truepin is a valid GPIO number on the target.
falsepin is reserved, out of range, or otherwise unusable.

keepThroughLightSleep() #

void kleidos::platform::gpio::keepThroughLightSleep(Pin pin)

Keep a pad's configuration while the chip light-sleeps.

On a build with automatic light sleep where ESP-IDF isolates every pad for the length of a sleep (its light-sleep GPIO reset workaround, the ESP32-S3 default), exempts pin so it keeps driving, reading and pulling as it does awake: a chip select stays deasserted, a reset line high, a power enable on, a key readable. Every pad a platform facade configures goes through here; pads nothing configured stay isolated. A no-op on every other build.

Parameters
NameDirectionMeaning
pininGPIO pin number; a negative or invalid one is ignored.

level() #

bool kleidos::platform::gpio::level(Pin pin)

Read the current pin level.

Parameters
NameDirectionMeaning
pininGPIO pin number.
Return values
ValueMeaning
truePin reads high.
falsePin reads low.

maxDuty() #

uint32_t kleidos::platform::pwm::maxDuty(uint8_t resolutionBits)

Return the maximum raw duty value for a given resolution.

Parameters
NameDirectionMeaning
resolutionBitsinDuty resolution in bits (e.g., 8 for 0-255).
Returns
Maximum duty count ((1 << resolutionBits) - 1).

pause() #

bool kleidos::platform::i2s::pause()

Stop the open channels without releasing them.

Stops their bit clock and DMA, and with them ESP-IDF's power-management lock a running channel holds: a running I2S channel keeps the APB clock at 80 MHz, which on a board built with the CPU idle floor keeps the cores off the floor for as long as it runs. Unlike end it keeps the channels allocated and configured, so resume restarts them without a new begin. No-op on channels already stopped, and before begin.

Return values
ValueMeaning
trueEvery open channel is stopped.
falseA channel refused to stop (or the native build).

probe() #

bool kleidos::platform::i2c::probe(uint8_t address, uint32_t timeoutMs = 0)

Probe for a device on the bus by sending its address.

Parameters
NameDirectionMeaning
addressin7-bit I2C device address.
timeoutMsinTimeout in ms; 0 uses the default.
Return values
ValueMeaning
trueDevice acknowledged the probe.
falseNACK, timeout, or bus error.

queueTransmit() #

bool kleidos::platform::spi::queueTransmit(Device & device, QueuedTransaction & transaction, const uint8_t * txData, size_t txSize, bool keepCsActive = false)

Queue a write-only transfer for interrupt-driven DMA (non-blocking).

Hands transaction to the SPI driver's interrupt queue and returns immediately, leaving the CPU free to do other work (e.g. pack the next chunk) while the DMA runs. Completion is reaped with awaitQueued. The device must have been created with DeviceConfig::queueSize >= the number of slots kept in flight at once.

Both transaction and txData must remain valid and untouched until the matching awaitQueued call returns this transaction.

When keepCsActive is true the chip-select line is held asserted after this transfer completes, so a sequence of chunks streams as one continuous CS frame (required by some panel controllers, e.g. ST7789V2, which desync their GRAM column pointer on a CS edge mid-RAMWR). The caller must bracket such a run with acquireBus / releaseBus and clear keepCsActive on the final chunk so CS deasserts normally.

Parameters
NameDirectionMeaning
devicein, outDevice handle from addDevice().
transactionin, outCaller-owned slot, reused across frames.
txDatainDMA-capable bytes to transmit (must be non-null).
txSizeinNumber of bytes to transmit (must be non-zero).
keepCsActiveinHold CS asserted after this transfer (continuous run).
Return values
ValueMeaning
trueThe transaction was queued.
falseBad arguments, no device, or the driver rejected the queue.

read() [1/3] #

bool kleidos::platform::i2c::read(uint8_t address, void * data, size_t length, uint32_t timeoutMs = 0)

Read bytes from an I2C device.

Parameters
NameDirectionMeaning
addressin7-bit device address.
dataoutDestination buffer.
lengthinNumber of bytes to read.
timeoutMsinTimeout in ms; 0 uses the default.
Return values
ValueMeaning
trueRead completed successfully.
falseNACK, timeout, or bus error.

read() [2/3] #

bool kleidos::platform::i2s::read(void * data, size_t length, size_t & bytesRead, uint32_t timeoutMs)

Read interleaved PCM samples from the codec ADC/microphone.

Same semantics as write(). Requires the config to have provided dinPin >= 0.

Parameters
NameDirectionMeaning
dataoutDestination buffer for interleaved PCM samples.
lengthinBuffer size in bytes.
bytesReadoutSet to the number of bytes actually received.
timeoutMsinMaximum time to block in milliseconds.
Return values
ValueMeaning
trueRead succeeded or a short read fit within timeoutMs.
falseBackend reported a hard error (e.g. not initialized, no RX channel configured, null buffer, or non-recoverable I/O fault).

read() [3/3] #

int kleidos::platform::uart::read(uint8_t * buffer, size_t maxLen)

Non-blocking read of pending RX bytes.

Parameters
NameDirectionMeaning
bufferoutDestination buffer.
maxLeninCapacity of buffer in bytes.
Returns
Number of bytes read (0 when nothing is pending), or -1 when the port is not ready or the arguments are invalid.

readCelsius() #

bool kleidos::platform::temperature::readCelsius(float & celsius)

Read the SoC internal die temperature in degrees Celsius.

Performs a self-contained install → enable → read → disable → uninstall cycle, leaving the sensor driver uninstalled on return. Safe to call from the UI task; does not touch any peripheral other than the temperature sensor.

Parameters
NameDirectionMeaning
celsiusoutReceives the temperature in °C on success; untouched on failure.
Return values
ValueMeaning
trueA sample was read and written to celsius.
falseNo internal sensor on this SoC (e.g. classic ESP32), the native build, or a driver error.

readMilliVolts() #

int kleidos::platform::adc::readMilliVolts(int pin)

Read calibrated millivolts from a configured pin.

Parameters
NameDirectionMeaning
pininGPIO pin number.
Returns
Millivolts, or -1 on error, uncalibrated pin, or native build.

readPadState() #

bool kleidos::platform::gpio::readPadState(Pin pin, PadState & out)

Read a pad's live routing and electrical state.

For diagnostics: it answers who drives a pin now (a peripheral signal or the plain GPIO level), which a configuration call can change behind the owner's back. Reads only; changes nothing.

Parameters
NameDirectionMeaning
pininGPIO pin number.
outoutThe pad's state; untouched on failure.
Return values
ValueMeaning
trueout holds the pad's state.
falseInvalid pin, or no hardware (native build).

readRaw() #

int kleidos::platform::adc::readRaw(int pin)

Read a raw ADC count from a configured pin.

Parameters
NameDirectionMeaning
pininGPIO pin number.
Returns
Raw ADC count, or -1 on error or on the native build.

readWithDummy() #

bool kleidos::platform::spi::readWithDummy(Device & device, uint8_t * rxData, size_t rxSize, uint8_t dummyBits, bool keepCsActive = false)

Half-duplex read of rxSize bytes preceded by dummyBits idle clocks.

A read-only transaction (no write phase) for panels that return data on the shared data line — either a dedicated MISO pin or a 3-wire panel whose SDA (MOSI) line turns around after the command. Because the transaction has no write phase, the SPI hardware can insert dummyBits dummy clocks before the read (ESP-IDF forbids dummy bits only when a transaction has both a read and a write phase). During the dummy clocks the Host does not latch data but the Device keeps shifting — this compensates for the panel's read setup time and, for ST7789, skips the one dummy clock that precedes every multi-parameter read (RDDID/RDDST).

The caller drives D/C and holds chip-select: bracket a preceding command write (via transmit with keepCsActive) and this read inside one acquireBus / releaseBus span so both phases form a single CS frame (SPI_TRANS_CS_KEEP_ACTIVE requires the bus be acquired first).

Parameters
NameDirectionMeaning
devicein, outDevice handle from addDevice() (half-duplex config).
rxDataoutBuffer receiving rxSize bytes.
rxSizeinNumber of bytes to read (must be non-zero).
dummyBitsinIdle clocks to insert before the read (0 for none).
keepCsActiveinHold CS asserted after this read (rarely needed; normally the read is the final phase of the frame).
Return values
ValueMeaning
trueRead completed successfully.
falseBad arguments, no device, or the driver reported a transfer error.

ready() [1/3] #

bool kleidos::platform::i2c::ready()

True when the I2C bus is initialized.

Return values
ValueMeaning
trueBus is initialized and ready for transactions.
falseBus has not been initialized (no successful begin() call).

ready() [2/3] #

bool kleidos::platform::i2s::ready()

True when the I2S peripheral is initialized.

Return values
ValueMeaning
truePeripheral was successfully initialized by begin().
falsePeripheral is uninitialized.

ready() [3/3] #

bool kleidos::platform::uart::ready()

True when a port is installed and ready.

Return values
ValueMeaning
trueA successful begin() is active.
falseNo port held (never begun, or torn down via end()).

releaseBus() #

void kleidos::platform::spi::releaseBus(Device & device)

Release a bus previously taken with acquireBus.

Parameters
NameDirectionMeaning
devicein, outDevice handle from addDevice().

resetPin() #

bool kleidos::platform::gpio::resetPin(Pin pin)

Reset a pin to its default GPIO state.

Detaches any peripheral signal (LEDC, SPI, matrix) previously routed to the pad and releases any deep-sleep hold. Use before reclaiming a pin for direct GPIO control.

Parameters
NameDirectionMeaning
pininGPIO pin number.
Return values
ValueMeaning
truePin reset successfully.
falseDriver reported an error resetting the pin.

resume() #

bool kleidos::platform::i2s::resume()

Restart the channels pause stopped.

begin leaves the channels running; this is only needed after pause. The transmit channel restarts on silence: the samples a pause left queued are overwritten, not sent. No-op on channels already running, and before begin.

Return values
ValueMeaning
trueEvery open channel runs.
falseA channel refused to start (or the native build).

ringDescCount() #

uint32_t kleidos::platform::i2s::ringDescCount(const Config & config)
constexpr

DMA buffers config asks for, its 0 resolved to ESP-IDF's default.

Parameters
NameDirectionMeaning
configinThe configuration.
Returns
The buffer count.

ringFrameCount() #

uint32_t kleidos::platform::i2s::ringFrameCount(const Config & config)
constexpr

Frames per DMA buffer config asks for, its 0 resolved to ESP-IDF's default.

Parameters
NameDirectionMeaning
configinThe configuration.
Returns
The frame count.

ringFrames() #

uint64_t kleidos::platform::i2s::ringFrames(const Config & config)
constexpr

Frames the whole ring holds.

Computed in 64 bits, so no pair of 32-bit counts wraps.

Parameters
NameDirectionMeaning
configinThe configuration.
Returns
Buffers times frames per buffer.

ringMs() #

uint32_t kleidos::platform::i2s::ringMs(const Config & config)
constexpr

How long the whole ring plays, in milliseconds, rounded up.

What a sample written now waits before it reaches the pin, at most, and the silence a stream must end with so that a pause discards only silence.

Parameters
NameDirectionMeaning
configinThe configuration.
Returns
The ring's length in milliseconds, UINT32_MAX for a length that does not fit; 0 when the sample rate is 0.

sameShape() #

bool kleidos::platform::i2s::sameShape(const Config & a, const Config & b)
constexpr

Whether two configurations open channels of the same shape.

The shape is what a channel is allocated with and cannot change without a delete: the port, which directions exist (transmit, receive) and the ring. Pins, rate, width and slots can change on a closed channel.

Parameters
NameDirectionMeaning
ainOne configuration.
binThe other.
Return values
ValueMeaning
truebegin may reopen channels allocated for a with b.
falseIt must refuse.

scrub() #

void kleidos::platform::sha_engine::scrub()

Overwrite what the engine still holds of the last derivation: zeros to the state (SHA_H) and to all 16 text words (SHA_TEXT).

After a chain the state holds its last U and the text its last inner digest; the salt and the count are public, so either is a PIN-guess oracle. Every driver calls this before release, on every exit.

setContentionHook() #

void kleidos::platform::crypto_hw::setContentionHook(ContentionHook hook)

Install the hook a crypto caller calls before it blocks on the audio side's hold.

The speaker driver posts a wake item from it, so a task blocked between sounds (the hang) reacts at once instead of polling. The hook must not block, and may run more than once for one wait. A waiter that read the hook just before it was replaced or removed may still call it once after this returns, so whatever the hook touches (the speaker's queue) must outlive the hook, never be deleted as it is removed.

Parameters
NameDirectionMeaning
hookinThe hook, or nullptr to remove it.

setDeviceFrequency() #

bool kleidos::platform::i2c::setDeviceFrequency(uint8_t address, uint32_t frequencyHz)

Give one device a bus clock of its own.

Every device is clocked at the bus's Config::frequencyHz unless this names another rate for it; the bus changes clock per transaction, so the other devices keep theirs and only see faster traffic addressed elsewhere. Call it before the device's transfers begin or from the one task that makes them: the next transfer to address uses the new rate.

Parameters
NameDirectionMeaning
addressin7-bit device address.
frequencyHzinIts clock in Hz.
Return values
ValueMeaning
trueThe rate is recorded (and applies from the next transfer).
falseInvalid address or rate, or no room left to record one.

setDirection() #

bool kleidos::platform::gpio::setDirection(Pin pin, Direction direction)

Change a pin's direction, keeping its pulls, interrupt and input routing.

Lighter than configure, which rewrites the whole pad. A pad whose input feeds a peripheral through the GPIO matrix (an SPI MISO) keeps feeding it in either direction, so a pad two owners share — driven as an output by one, read as an input by the other — is switched here around each owner's use.

Warning
An output direction makes the pad a plain GPIO output: any peripheral output signal routed to it (an SPI device's hardware chip-select) is disconnected. Never point this, configure or configureOutput at a pin a peripheral drives; use readPadState to see which one does.
Parameters
NameDirectionMeaning
pininGPIO pin number.
directioninNew direction (push-pull when an output).
Return values
ValueMeaning
trueDirection applied.
falseInvalid pin or the driver reported an error.

setDuty() #

bool kleidos::platform::pwm::setDuty(uint8_t channel, uint32_t duty)

Set the raw duty value for a channel.

Parameters
NameDirectionMeaning
channelinLEDC channel index.
dutyinRaw duty count (0..maxDuty(resolutionBits)).
Return values
ValueMeaning
trueDriver accepted the new duty value.
falseDriver reported an error updating the duty.

setDutyPercent() #

bool kleidos::platform::pwm::setDutyPercent(uint8_t channel, uint8_t percent)

Set the duty as a percentage (0-100) for a channel.

Parameters
NameDirectionMeaning
channelinLEDC channel index.
percentinDuty cycle percentage (0 = off, 100 = full on).
Return values
ValueMeaning
trueDriver accepted the new duty percentage.
falseDriver reported an error updating the duty.

setFrequency() #

bool kleidos::platform::pwm::setFrequency(uint8_t timer, uint32_t frequencyHz)

Change a timer's frequency, keeping its clock, its resolution and the raw duty of every channel on it.

One register update (ESP-IDF's ledc_set_freq), so a sound that steps its pitch does not run configure again on every step. The raw duty counts stay, so each channel keeps its duty fraction at the new frequency: a buzzer note keeps its volume through a glide. Raw duty goes through setDuty, at the resolution the channel was configured with (10 bits for the buzzer: the low volumes need 1 to 3 %, which whole percents cannot say).

Parameters
NameDirectionMeaning
timerinLEDC timer index; a channel must have been configured on it.
frequencyHzinNew frequency in Hz. Frequency times 2^bits must stay within the timer's clock (about 8 MHz for RC_FAST on the classic ESP32); the driver refuses a rate it cannot make.
Return values
ValueMeaning
trueThe timer runs at frequencyHz.
falseNo channel is configured on timer, frequencyHz is 0, or the driver refused the rate; the timer keeps its frequency.

setLevel() #

bool kleidos::platform::gpio::setLevel(Pin pin, bool high)

Drive an output pin high or low.

Parameters
NameDirectionMeaning
pininGPIO pin number.
highinTrue to drive high, false to drive low.
Return values
ValueMeaning
trueDriver accepted the new level.
falseDriver reported an error setting the level.

setReentryHandlerForTest() #

void kleidos::platform::crypto_hw::setReentryHandlerForTest(ReentryHandler handler)

Host builds only: install what a ScopedLock taken by the task that already holds the lock does.

The device stops the firmware there. The host stops the test program the same way by default (a log line, then std::abort), so a nested take fails whichever native suite runs into it, not only one that reads Stats::reentries. A test that takes the lock twice on purpose installs a handler for the length of the test.

Parameters
NameDirectionMeaning
handlerinCalled instead of stopping, or nullptr for the default.

stats() [1/2] #

Stats kleidos::platform::crypto_hw::stats()

Read the lock's counters (crypto takes and waits, audio holds, refusals and yields, the longest yield, overruns and re-entries).

Returns
A snapshot of the counters.

stats() [2/2] #

Stats kleidos::platform::i2s::stats()

Read the overflow counters and the ring in use.

Safe from any task; the counters are raised by the driver's interrupt. The ring is read without a lock: it is written by the first begin and only ever rewritten with the same counts (sameShape), so only a read that races that first begin can report a stale one.

Returns
The counters since boot; zeros on the native build.

stop() #

bool kleidos::platform::pwm::stop(uint8_t channel, bool idleHigh = false)

Stop PWM output and park the pin at idle level.

Parameters
NameDirectionMeaning
channelinLEDC channel index.
idleHighinTrue to park the pin high, false to park low.
Return values
ValueMeaning
truePWM output stopped and pin parked at the requested level.
falseDriver reported an error stopping the channel.

takeBack() #

void kleidos::platform::gpio::takeBack(Pin pin)

Drop whatever output claim a driver left on a pad it is done with.

For a driver that keeps its claim when it lets a pad go: ESP-IDF's SD SPI host configures its chip select as an output and never withdraws that claim, so its own release and the next bring-up each report a conflict on the pad. Called right before such a driver releases the pad. Only the record of the claim goes: the pad keeps its level and direction.

Parameters
NameDirectionMeaning
pininGPIO pin number; a negative or invalid one is ignored.

timerClockSource() #

ClockSource kleidos::platform::pwm::timerClockSource(uint8_t timer)

Read back the clock a PWM timer counts.

Read from the LEDC registers, not from what configure asked for, so it shows the source the hardware actually uses.

Parameters
NameDirectionMeaning
timerinLEDC timer index.
Returns
The source; ClockSource::Unknown on the native build.

timerFrequencyHz() #

uint32_t kleidos::platform::pwm::timerFrequencyHz(uint8_t timer)

Read back the frequency a PWM timer runs at.

Computed from the timer's divider and its source as the source runs at the moment of the call. A caller is a running task, so an APB source reads its busy rate here; the rate it falls to while the cores idle is the reason to read timerClockSource beside it.

Parameters
NameDirectionMeaning
timerinLEDC timer index.
Returns
Frequency in Hz; 0 for a timer no configured channel uses. On the native build, the frequency last configured or set.

transmit() #

bool kleidos::platform::spi::transmit(Device & device, const uint8_t * txData, size_t txSize, uint8_t * rxData = nullptr, size_t rxSize = 0, bool keepCsActive = false)

Perform a full- or half-duplex SPI transfer.

Parameters
NameDirectionMeaning
devicein, outDevice handle from addDevice().
txDatainBytes to transmit (may be nullptr for read-only).
txSizeinNumber of bytes to transmit.
rxDataoutBuffer to receive bytes (may be nullptr for write-only).
rxSizeinNumber of bytes to receive.
keepCsActiveinHold CS asserted after this transfer so a run of polling chunks streams as one continuous CS frame. Bracket such a run with acquireBus / releaseBus and clear it on the final chunk.
Return values
ValueMeaning
trueTransfer completed successfully.
falseDriver reported a transfer error.

write() [1/3] #

bool kleidos::platform::i2c::write(uint8_t address, const void * data, size_t length, uint32_t timeoutMs = 0)

Write bytes to an I2C device.

Parameters
NameDirectionMeaning
addressin7-bit device address.
datainSource buffer.
lengthinNumber of bytes to write.
timeoutMsinTimeout in ms; 0 uses the default.
Return values
ValueMeaning
trueWrite completed successfully.
falseNACK, timeout, or bus error.

write() [2/3] #

bool kleidos::platform::i2s::write(const void * data, size_t length, size_t & bytesWritten, uint32_t timeoutMs)

Write interleaved PCM samples to the codec.

Blocks until all bytes are queued or timeoutMs elapses; bytesWritten reports the actual count. Returns false on error; a short write (timeout) still returns true with bytesWritten < length. A channel stopped by pause takes no samples until resume.

Parameters
NameDirectionMeaning
datainPointer to interleaved PCM sample data.
lengthinNumber of bytes to write.
bytesWrittenoutSet to the number of bytes actually queued.
timeoutMsinMaximum time to block in milliseconds.
Return values
ValueMeaning
trueWrite succeeded or a short write fit within timeoutMs.
falseBackend reported a hard error (e.g. not initialized, no TX channel configured, null buffer, or non-recoverable I/O fault).

write() [3/3] #

int kleidos::platform::uart::write(const uint8_t * data, size_t len)

Queue bytes for transmission.

Parameters
NameDirectionMeaning
datainSource buffer.
leninNumber of bytes to send.
Returns
Number of bytes queued, or -1 when the port is not ready or the arguments are invalid.

writeParts() #

bool kleidos::platform::i2c::writeParts(uint8_t address, const void * head, size_t headLength, const void * body, size_t bodyLength, uint32_t timeoutMs = 0)

Write two buffers to an I2C device as one transaction.

One START, the address, head then body, one STOP: what a register write is (the register address, then its data) without copying the data behind the address first, so its length has no bound but the timeout.

Parameters
NameDirectionMeaning
addressin7-bit device address.
headinFirst bytes on the wire (a register address).
headLengthinNumber of bytes in head.
bodyinBytes that follow.
bodyLengthinNumber of bytes in body.
timeoutMsinTimeout in ms; 0 uses the default.
Return values
ValueMeaning
trueWrite completed successfully.
falseNACK, timeout, or bus error.

writeRead() #

bool kleidos::platform::i2c::writeRead(uint8_t address, const void * writeData, size_t writeLength, void * readData, size_t readLength, uint32_t timeoutMs = 0)

Write then repeated-start read in a single transaction.

Parameters
NameDirectionMeaning
addressin7-bit device address.
writeDatainSource buffer for the write phase.
writeLengthinNumber of bytes to write.
readDataoutDestination buffer for the read phase.
readLengthinNumber of bytes to read.
timeoutMsinTimeout in ms; 0 uses the default.
Return values
ValueMeaning
trueTransaction completed successfully.
falseNACK, timeout, or bus error.

Back to the top

Variable Documentation

kAudioBackoffMs #

uint32_t kleidos::platform::crypto_hw::kAudioBackoffMs
inlineconstexpr

How long the audio side sleeps, in milliseconds, before it looks again while a crypto caller waits.

Sleeping rather than retrying the mutex is what keeps it from taking the lock back from a waiter of lower priority that has been woken but has not run yet.

kAudioYieldBudgetMs #

uint32_t kleidos::platform::crypto_hw::kAudioYieldBudgetMs
inlineconstexpr

Longest a crypto caller may wait for the audio side, in milliseconds.

The audio side's yield: the block being written (8 ms) and the close of the stream (the amplifier's gate write, whose shutdown cuts the sound, the codec's mute and the channel's pause), with room for the player to be preempted while it does so. A longer yield is counted in Stats::yieldOverruns. It is also the slice a waiting crypto caller blocks for between two calls of the contention hook.

kBusyPollLimit #

uint32_t kleidos::platform::sha_engine::kBusyPollLimit
inlineconstexpr

Most times a wait reads the engine's busy flag before it calls the engine hung. A compression takes about a microsecond; the limit is some milliseconds of polling.

Back to the top