Kleidos API Search

In development. It changes without notice.

Topic

Network Services

The time from the network, the Wi-Fi session that fetches it, the portal's network name, and the request for the portal after a restart.

  • The time is one answer of a time server, over a Wi-Fi network saved in the vault, and only when the owner asks, on leaving the portal, or where a code was refused for want of the time. Network time is not authenticated: an answer outside sane bounds is refused, a step backward is refused while a lockout runs, and the clock's trust never rises.
  • The session (kleidos::net::WifiStaSessionGuard) shuts Bluetooth down, joins the network, and restores both on every way out.
  • The portal's network name and password are kept until the owner changes them or a factory reset erases them.
  • The request for the portal outlives a restart and is used by the next unlock, once. It opens nothing by itself.
See also
Wi-Fi Admin Portal, Clock & Time Zone, One-Time Codes, Wi-Fi & HTTP Server

Files

file src/net/admin_ap_identity.cpp
Implementation of the admin access-point identity policy.
file src/net/admin_ap_identity.h
Where the admin access point's SSID and password come from.
file src/net/ntp_sync.h
One-shot WiFi-station + NTP clock-sync engine (async, worker-driven).
file src/net/ntp_sync_logic.h
Pure decision logic for the NTP clock sync (host-testable core).
file src/net/pending_admin_mode.h
RTC-persisted flag that routes the next boot directly to admin mode.
file src/net/station_ble_restore.h
Which Bluetooth session, if any, the Wi-Fi station session gives back when it ends.
file src/net/wifi_join_plan.h
Which access points a clock sync tries, in which order, and for how long.
file src/net/wifi_sta_session_guard.h
RAII guard for a transient WiFi-station session with BLE exclusivity.

Classes

struct kleidos::net::ntp::Status
Read-only snapshot of the running (or last) sync, safe to poll from any task. More about kleidos::net::ntp::Status
struct kleidos::net::JoinScanHit
One access point a scan heard, reduced to what the plan needs. More about kleidos::net::JoinScanHit
struct kleidos::net::JoinAttempt
One access point the plan says to try. More about kleidos::net::JoinAttempt
class kleidos::net::WifiStaSessionGuard
RAII transient STA session: BLE off on entry, WiFi off + BLE restored on exit. More about kleidos::net::WifiStaSessionGuard

Enumerations

enum class kleidos::net::ntp::Phase : uint8_t { kleidos::net::ntp::Phase::Idle, kleidos::net::ntp::Phase::StoppingBle, kleidos::net::ntp::Phase::Scanning, kleidos::net::ntp::Phase::Joining, kleidos::net::ntp::Phase::Querying, kleidos::net::ntp::Phase::Done, kleidos::net::ntp::Phase::Failed, kleidos::net::ntp::Phase::Cancelled }
Lifecycle phase of a one-shot NTP clock sync. More about kleidos::net::ntp::Phase
enum class kleidos::net::ntp::FailReason : uint8_t { kleidos::net::ntp::FailReason::None, kleidos::net::ntp::FailReason::Busy, kleidos::net::ntp::FailReason::NoSavedNetworks, kleidos::net::ntp::FailReason::BleStopFailed, kleidos::net::ntp::FailReason::NoVisibleNetwork, kleidos::net::ntp::FailReason::WifiJoinFailed, kleidos::net::ntp::FailReason::NoServerResponse, kleidos::net::ntp::FailReason::TimeRejected, kleidos::net::ntp::FailReason::Internal }
Why a sync ended in Phase::Failed. More about kleidos::net::ntp::FailReason
enum class kleidos::net::BleRestore : uint8_t { kleidos::net::BleRestore::None , kleidos::net::BleRestore::Bounded , kleidos::net::BleRestore::Standby }
The Bluetooth session the station session restarts when it ends. More about kleidos::net::BleRestore

Functions

boolkleidos::net::apidentity::isFixed ()
Whether the owner has pinned the access point's identity.
boolkleidos::net::apidentity::loadFixed (char *ssid, size_t ssidCap, char *password, size_t passCap)
Read the pinned identity.
boolkleidos::net::apidentity::setFixed (const char *ssid, const char *password)
Pin the access point to ssid and password.
boolkleidos::net::apidentity::clearFixed ()
Stop pinning the identity and go back to a random password per session.
boolkleidos::net::apidentity::requestPinOnNextSession ()
Ask for the next session's password to be kept as the fixed one.
boolkleidos::net::apidentity::pinRequested ()
Whether a pin request is waiting for the next password draw.
boolkleidos::net::apidentity::clearPinRequest ()
Drop a pending pin request.
boolkleidos::net::apidentity::armOtaCarryOver (const char *password)
Remember the live password so it survives an OTA reboot.
boolkleidos::net::apidentity::takeOtaCarryOver (char *password, size_t cap)
Take the password carried across an OTA reboot, if there is one.
boolkleidos::net::apidentity::forgetAll ()
Forget every admin access-point identity this device holds.
constexpr boolkleidos::net::ntp::isTerminal (Phase phase)
True for a phase the engine ends in (Done, Failed, Cancelled).
constexpr uint8_tkleidos::net::ntp::progressPercent (Phase phase)
Progress-bar percent for a sync phase.
boolkleidos::net::ntp::begin (const uint8_t *vaultKey, const char *overrideServerIp)
Arm and start a one-shot sync on the Core-0 worker.
voidkleidos::net::ntp::cancel ()
Request cancellation of the running sync (idempotent).
boolkleidos::net::ntp::active ()
True while a sync is running (non-terminal phase).
Statuskleidos::net::ntp::status ()
Copy the current status snapshot.
const char *kleidos::net::ntp::failReasonLabel (FailReason reason)
Compact console label for a FailReason.
constexpr boolkleidos::net::ntp::ntpEpochAcceptable (int64_t epoch)
True when an NTP response epoch lies in the plausible window.
constexpr boolkleidos::net::ntp::ntpCommitAllowed (int64_t newEpoch, int64_t nowEpoch, bool lockoutArmed)
True when a (plausible) NTP epoch may be committed to the clock.
voidkleidos::net::setPendingAdmin ()
Arm the pending-admin flag in RTC memory.
boolkleidos::net::isPendingAdmin ()
True while the pending-admin flag is set.
boolkleidos::net::consumePendingAdmin ()
One-shot read: returns true if the flag was set, and clears it so that subsequent boots take the normal unlock → Home path.
constexpr boolkleidos::net::ownerActedSince (uint32_t epochBefore, uint32_t epochNow, bool guardStopped)
Whether an owner started or stopped the radio while the station session ran.
constexpr BleRestorekleidos::net::bleRestoreAfterStation (kleidos::ble::StackState before, bool standby, bool stopOk, bool ownerActedSince)
What the station session gives back of the Bluetooth session it stopped.
constexpr size_tkleidos::net::planJoinAttempts (std::span< const JoinScanHit > hits, std::span< JoinAttempt > out)
Order the access points a sync should try.
constexpr uint32_tkleidos::net::joinSliceMs (uint32_t spentMs, uint32_t perAttemptMs, uint32_t budgetMs)
How long the next join attempt may take, given what the phase has spent.

Variables

constexpr size_tkleidos::net::apidentity::kSsidCap
Longest accepted SSID, plus the terminator.
constexpr size_tkleidos::net::apidentity::kPasswordCap
Longest accepted password, plus the terminator: a Wi-Fi passphrase is at most 63 characters.
constexpr size_tkleidos::net::apidentity::kMinPasswordLen
constexpr size_tkleidos::net::ntp::kPhaseCount
Number of Phase values (the enumerators are dense from 0).
constexpr std::array< uint8_t, kPhaseCount >kleidos::net::ntp::kPhaseProgressPercent
Coarse progress-bar fill per Phase, indexed by its value.
constexpr size_tkleidos::net::ntp::kNtpSsidTextLen
Buffer sizes for the status snapshot's text fields.
constexpr size_tkleidos::net::ntp::kNtpIpTextLen
Dotted IPv4 + NUL.
constexpr uint32_tkleidos::net::kPendingAdminMagic
Magic value written to RTC slow memory to request admin mode after reboot.
constexpr size_tkleidos::net::kJoinBssidBytes
Length of an 802.11 basic service set identifier (an access point's MAC).
constexpr size_tkleidos::net::kMaxJoinAttempts
constexpr uint8_tkleidos::net::kNoSavedNetwork
A scan hit that matches no saved network, and an attempt that names none.

Trusted default NTP servers (literal IPs, tried in order)

Public anycast NTP by LITERAL IPv4 only — the engine never resolves a hostname (no DNS on any path), so a rogue AP's resolver cannot redirect the query. Order: Cloudflare (162.159.200.1 / 162.159.200.123, time.cloudflare.com anycast), Google (216.239.35.0, time.google.com anycast), NIST (132.163.97.1, time-*.nist.gov).

constexpr autokleidos::net::ntp::kDefaultNtpServers
The default servers as literal IPv4 addresses, in the order the engine tries them.
constexpr size_tkleidos::net::ntp::kDefaultNtpServerCount
Number of entries in kDefaultNtpServers.

Accepted NTP epoch window

A response outside [2025-01-01, 2100-01-01) UTC is rejected before any clock write — the same idea as the GPS engine's bounded fix-year window (gps::kMinFixYear / kMaxFixYear).

constexpr int64_tkleidos::net::ntp::kNtpMinEpoch
2025-01-01T00:00:00Z (inclusive).
constexpr int64_tkleidos::net::ntp::kNtpMaxEpoch
2100-01-01T00:00:00Z (exclusive).

Back to the top

Enumeration Type Documentation

BleRestore #

enum class kleidos::net::BleRestore : uint8_t

The Bluetooth session the station session restarts when it ends.

Enumerator
None 

Leave the radio off.

Bounded 

Restart a bounded session (a send's).

Standby 

Restart a standby session (a pairing page's open window).

FailReason #

enum class kleidos::net::ntp::FailReason : uint8_t

Why a sync ended in Phase::Failed.

Enumerator
None 

Not failed.

Busy 

Reserved label; a busy begin() leaves the running sync's status untouched.

NoSavedNetworks 

The encrypted WiFi store is empty (or vault locked).

BleStopFailed 

BLE teardown timed out; WiFi was never started.

NoVisibleNetwork 

No saved SSID was found in the scan results.

WifiJoinFailed 

Every access point the plan tried failed to associate or to lease an address inside the joining phase's budget. Status::channel names the last one's channel and Status::attempts how many were tried.

NoServerResponse 

No configured server answered within its window.

TimeRejected 

Response(s) arrived but failed the sanity gates.

Internal 

Worker spawn or another internal error.

Phase #

enum class kleidos::net::ntp::Phase : uint8_t

Lifecycle phase of a one-shot NTP clock sync.

Enumerator
Idle 

No sync ever started (terminal phases latch; begin() re-arms).

StoppingBle 

Tearing the BLE stack down before any WiFi bring-up.

Scanning 

Scanning for a visible saved network.

Joining 

Joining the chosen network (waiting for DHCP).

Querying 

Querying the configured NTP server IPs in order.

Done 

Clock committed; WiFi off; BLE restored. Terminal.

Failed 

See FailReason; WiFi off; BLE restored. Terminal.

Cancelled 

User abort; WiFi off; BLE restored. Terminal.

Back to the top

Function Documentation

active() #

bool kleidos::net::ntp::active()

True while a sync is running (non-terminal phase).

Return values
ValueMeaning
trueThe worker is active.
falseIdle or a terminal phase was published.

armOtaCarryOver() #

bool kleidos::net::apidentity::armOtaCarryOver(const char * password)
nodiscard

Remember the live password so it survives an OTA reboot.

Called when an update is about to restart the device: without it the browser that started the update could not rejoin to see the result. Ignored when the identity is fixed, since that password already survives by definition.

Parameters
NameDirectionMeaning
passwordinThe password the access point is currently using.
Return values
ValueMeaning
trueNothing needed carrying, or the copy is on flash.
falseThe copy was not stored: after the reboot the AP draws a fresh password and the browser that started the update cannot rejoin.

begin() #

bool kleidos::net::ntp::begin(const uint8_t * vaultKey, const char * overrideServerIp)

Arm and start a one-shot sync on the Core-0 worker.

Loads the saved networks AND the user NTP-server list from the encrypted vault store on the CALLING task (so the worker never sees the vault key), then spawns the worker. Server precedence: overrideServerIp (when set) > the vault user list (when non-empty) > the compile-time default table — all literal IPv4, tried in order. Refuses while a sync is active, when the store has no networks, or when overrideServerIp is oversized.

Parameters
NameDirectionMeaning
vaultKeyin32-byte unlocked vault key (read-only; used only during this call to decrypt the store).
overrideServerIpinOptional single literal IPv4 NTP server to use instead of the default table, or nullptr.
Return values
ValueMeaning
trueThe worker started; poll status until a terminal phase.
falseRefused — status carries the FailReason, except on a busy refusal (the running sync's snapshot is left intact; distinguish by active returning true).

bleRestoreAfterStation() #

BleRestore kleidos::net::bleRestoreAfterStation(kleidos::ble::StackState before, bool standby, bool stopOk, bool ownerActedSince)
constexpr

What the station session gives back of the Bluetooth session it stopped.

Parameters
NameDirectionMeaning
beforeinThe stack's state when the station session began.
standbyinThat session ran in standby (its pairing window open).
stopOkinThe station session's own stop completed.
ownerActedSinceinAn owner started or stopped the radio while the station session ran (ownerActedSince).
Returns
The session to restart, or BleRestore::None.

cancel() #

void kleidos::net::ntp::cancel()

Request cancellation of the running sync (idempotent).

The worker observes the flag between steps and at every SNTP wait slice; teardown (WiFi off + BLE restore) still runs on the cancel path. A join in flight completes or times out first (bounded by the join timeout).

clearFixed() #

bool kleidos::net::apidentity::clearFixed()
nodiscard

Stop pinning the identity and go back to a random password per session.

Also disarms a pending requestPinOnNextSession marker, so "stop pinning" cannot be undone by a request recorded before it.

Return values
ValueMeaning
trueThe stored pair and the pending marker are gone (or there was none) — the next session draws a random password.
falseAt least one of them is still on flash, so the AP keeps advertising the pinned password. The caller must not report the identity as unpinned.

clearPinRequest() #

bool kleidos::net::apidentity::clearPinRequest()
nodiscard

Drop a pending pin request.

Called once the request has been honored by a password draw, and by any path that turns the setting back off: a marker left armed would silently re-pin at the next session.

Return values
ValueMeaning
trueNo request is armed any more.
falseThe marker is still on flash and will re-pin the next session.

consumePendingAdmin() #

bool kleidos::net::consumePendingAdmin()

One-shot read: returns true if the flag was set, and clears it so that subsequent boots take the normal unlock → Home path.

Return values
ValueMeaning
trueFlag was set; it has now been cleared.
falseFlag was not set; nothing was changed.
See also
isPendingAdmin(), setPendingAdmin()

failReasonLabel() #

const char * kleidos::net::ntp::failReasonLabel(FailReason reason)

Compact console label for a FailReason.

Parameters
NameDirectionMeaning
reasoninThe reason to label.
Returns
Pointer to a static lowercase string (never nullptr).

forgetAll() #

bool kleidos::net::apidentity::forgetAll()
nodiscard

Forget every admin access-point identity this device holds.

Erases the pinned SSID and password, a deferred pin request, and the one-shot password carried across an OTA reboot. A change of owner runs it: each of those would otherwise let the previous owner's credential reach the next owner's first admin session. Unlike kleidos::net::apidentity::clearFixed, which is the owner choosing to stop pinning, this leaves nothing behind. A key that was never written erases as a success.

Return values
ValueMeaning
trueNone of the identity keys remain.
falseAt least one would not erase; it is logged, and the next session may still advertise or rejoin with it.

isFixed() #

bool kleidos::net::apidentity::isFixed()
nodiscard

Whether the owner has pinned the access point's identity.

Return values
ValueMeaning
trueA stored SSID/password pair is in use for every session.
falseThe default: a fresh random password each session.

isPendingAdmin() #

bool kleidos::net::isPendingAdmin()
nodiscard

True while the pending-admin flag is set.

Non-mutating: prefer consumePendingAdmin() in FSM dispatch code so the flag is cleared exactly once per request.

Return values
ValueMeaning
trueRTC magic word matches kPendingAdminMagic.
falseFlag is unset (cleared, never armed, or lost with power).
See also
consumePendingAdmin()

isTerminal() #

bool kleidos::net::ntp::isTerminal(Phase phase)
constexpr

True for a phase the engine ends in (Done, Failed, Cancelled).

A terminal phase latches until the next begin(); Phase::Idle is not terminal (no sync ever ran).

Parameters
NameDirectionMeaning
phaseinThe phase to classify.
Return values
ValueMeaning
truephase is Done, Failed or Cancelled.
falseA sync is running, or none ever started.

joinSliceMs() #

uint32_t kleidos::net::joinSliceMs(uint32_t spentMs, uint32_t perAttemptMs, uint32_t budgetMs)
constexpr

How long the next join attempt may take, given what the phase has spent.

The whole joining phase has one budget, so a board that fails every attempt costs a bounded amount of radio time whatever the scan found — the sync is driven from a settings screen the user waits in front of and from the admin exit, which cancels it at a ceiling of its own. Each attempt gets the full per-attempt timeout while the budget covers it, and the remainder goes to the next one.

Parameters
NameDirectionMeaning
spentMsinMilliseconds the joining phase has already used.
perAttemptMsinTimeout one attempt may ask for.
budgetMsinBudget for the whole phase.
Returns
The timeout for the next attempt, or 0 when none fits and the phase must give up.

loadFixed() #

bool kleidos::net::apidentity::loadFixed(char * ssid, size_t ssidCap, char * password, size_t passCap)
nodiscard

Read the pinned identity.

Parameters
NameDirectionMeaning
ssidoutDestination for the SSID; untouched when not fixed.
ssidCapinCapacity of ssid.
passwordoutDestination for the password; untouched when not fixed.
passCapinCapacity of password.
Return values
ValueMeaning
trueBoth were read; the caller must zeroize password.
falseNot fixed, or the stored pair is unusable.

ntpCommitAllowed() #

bool kleidos::net::ntp::ntpCommitAllowed(int64_t newEpoch, int64_t nowEpoch, bool lockoutArmed)
constexpr

True when a (plausible) NTP epoch may be committed to the clock.

Refuses a BACKWARD step while a brute-force lockout is armed: an attacker spoofing unauthenticated NTP must not be able to rewind the clock past a lockout-until timestamp. Forward steps are always allowed (the forward-jump lockout model fails closed on its own).

Parameters
NameDirectionMeaning
newEpochinCandidate server UTC time (UNIX seconds).
nowEpochinCurrent device clock (UNIX seconds).
lockoutArmedinTrue while an unlock lockout window is active.
Return values
ValueMeaning
trueThe commit is safe.
falseBackward step under an armed lockout; must be rejected.

ntpEpochAcceptable() #

bool kleidos::net::ntp::ntpEpochAcceptable(int64_t epoch)
constexpr

True when an NTP response epoch lies in the plausible window.

Parameters
NameDirectionMeaning
epochinServer UTC time as UNIX seconds.
Return values
ValueMeaning
trueepoch is within [::kNtpMinEpoch, ::kNtpMaxEpoch).
falseImplausible response; must not reach the clock.

ownerActedSince() #

bool kleidos::net::ownerActedSince(uint32_t epochBefore, uint32_t epochNow, bool guardStopped)
constexpr

Whether an owner started or stopped the radio while the station session ran.

The owner count moves once at every start and stop asked of the Bluetooth facade, the guard's own stop included. Read before that stop and again at the end, it moved by exactly one if only the guard's stop ran, and by none if the guard stopped nothing; any other change is an owner's.

Parameters
NameDirectionMeaning
epochBeforeinThe count read before the guard's own stop.
epochNowinThe count read when the station session ends.
guardStoppedinThe guard asked the facade to stop the radio.
Return values
ValueMeaning
trueAn owner acted: what the guard stopped is not its to give back.
falseOnly the guard's own stop moved the count.

pinRequested() #

bool kleidos::net::apidentity::pinRequested()
nodiscard

Whether a pin request is waiting for the next password draw.

Return values
ValueMeaning
trueThe next drawn password will be stored as the fixed one.
falseNo request is pending.

planJoinAttempts() #

size_t kleidos::net::planJoinAttempts(std::span< const JoinScanHit > hits, std::span< JoinAttempt > out)
constexpr

Order the access points a sync should try.

hits comes in the order the scan returned, which is strongest-RSSI first. The first hit that matches a saved network is the first attempt, unpinned. Each later attempt is the strongest remaining match on a channel no earlier attempt was heard on — channel diversity rather than signal, because the one failure a board can do nothing else about is channel-wide, and because a loaded channel is loaded for every access point on it. Two access points of one channel are therefore never both planned: the time a second one would spend buys more on another channel.

A hit whose channel is 0 (a scan that did not report one) can match at most once, since there is no channel to tell it apart from another such hit.

Parameters
NameDirectionMeaning
hitsinScan hits, strongest first, each already resolved against the saved networks.
outoutDestination for the planned attempts, in order.
Returns
Number of attempts written to out: 0 when no hit matches a saved network, and never more than the lesser of out's size and kMaxJoinAttempts.

progressPercent() #

uint8_t kleidos::net::ntp::progressPercent(Phase phase)
constexpr

Progress-bar percent for a sync phase.

Parameters
NameDirectionMeaning
phaseinThe engine phase to show.
Returns
0..100 from kPhaseProgressPercent; 0 for a value outside the enumeration.

requestPinOnNextSession() #

bool kleidos::net::apidentity::requestPinOnNextSession()
nodiscard

Ask for the next session's password to be kept as the fixed one.

The device's own settings menu offers the same choice the portal does, but it cannot draw the password itself: the draw lives in WifiApLink::generateApPassword, which is reached only by bringing an admin session up.

So the menu records the intent here and the draw stays where it is: the next admin session draws a fresh password as usual and pins that one. That session therefore still shows a new password; every session after it shows the same one.

The draw needs no radio state of its own: the entropy draw is taken once at startup to seed the CSPRNG behind VaultCrypto::generateRandom, and every secret, this password included, comes from that CSPRNG without bracketing the hardware entropy source, so drawing it with the radios up is as sound as drawing it with them down.

Idempotent, and a no-op in effect when the identity is already fixed.

Return values
ValueMeaning
trueThe marker is on flash; the next drawn password will be pinned.
falseThe marker was not stored — the next session draws a random password and the owner's choice never happens.

setFixed() #

bool kleidos::net::apidentity::setFixed(const char * ssid, const char * password)
nodiscard

Pin the access point to ssid and password.

Parameters
NameDirectionMeaning
ssidinNetwork name; empty keeps the device-derived default.
passwordinPassphrase, kMinPasswordLen to 63 characters.
Return values
ValueMeaning
trueStored; it applies from the next admin session.
falseRejected (length) or storage failed; nothing changed.

status() #

Status kleidos::net::ntp::status()

Copy the current status snapshot.

Returns
A coherent copy of the running/last sync state.

takeOtaCarryOver() #

bool kleidos::net::apidentity::takeOtaCarryOver(char * password, size_t cap)
nodiscard

Take the password carried across an OTA reboot, if there is one.

One shot: the stored copy is erased by this call whether or not it is used, so a carried password can never outlive the reconnection it exists for.

Parameters
NameDirectionMeaning
passwordoutDestination for the carried password.
capinCapacity of password.
Return values
ValueMeaning
trueA carried password was taken; the caller must zeroize it.
falseNothing was carried.

Back to the top

Variable Documentation

kMaxJoinAttempts #

size_t kleidos::net::kMaxJoinAttempts
inlineconstexpr

The most access points one sync plans to try. Three covers the saved networks of a home on the three non-overlapping channels; the time budget (joinSliceMs) is what actually stops the loop, and it usually stops it sooner.

kMinPasswordLen #

size_t kleidos::net::apidentity::kMinPasswordLen
inlineconstexpr

Shortest accepted password. Above WPA's own floor of 8: this one is typed once and then reused for every session, so it is held to a higher bar.

kNtpSsidTextLen #

size_t kleidos::net::ntp::kNtpSsidTextLen
inlineconstexpr

Buffer sizes for the status snapshot's text fields.

SSID + NUL.

kPhaseProgressPercent #

std::array<uint8_t, kPhaseCount> kleidos::net::ntp::kPhaseProgressPercent
inlineconstexpr

Coarse progress-bar fill per Phase, indexed by its value.

Linear over the four working steps (10/35/60/85), full on Done, empty on Idle, Failed and Cancelled.

Back to the top