Kleidos API Search

In development. It changes without notice.

Topic

BLE Stack Integration

The owner of NimBLE on core 0: the stack's task, the queue of commands to it and the bus of events from it.

The host tests run none of this: they use a stand-in for the stack.

See also
BLE Facade & HID Manager, BLE Connection Management, Pairing & Numeric Comparison

Files

file src/ble/stack/advertising_hold.h
Whether the stack may resume advertising on its own.
file src/ble/stack/advertising_restart.h
When a change of the pairing window may restart the running advertising set.
file src/ble/stack/ble_command_queue.h
MPSC typed command queue from FSM/UI/web to the BLE stack task.
file src/ble/stack/ble_event_bus.h
MPMC publish/subscribe channel for BLE events.
file src/ble/stack/ble_stack_task.h
Core 0 task that owns the NimBLE stack and drains BLE commands.
file src/ble/stack/callback_timing.h
How long the NimBLE host task spends in Kleidos' own callbacks.
file src/ble/stack/guard_counts.h
How the debug console's guard reads encode a timing judge and a keystore refusal.
file src/ble/stack/host_access_gate.h
Admits a call into the NimBLE host only while the host's memory exists.
file src/ble/stack/nimble_host.h
NimBLE host adapter (concrete NimBleHostPort) + free-function shim.
file src/ble/stack/nimble_host_port.h
Vendor-free port (hexagonal seam) isolating the BLE host stack.
file src/ble/stack/nimble_host_raw.cpp
The raw Apache NimBLE C-API implementation of kleidos::ble::stack::NimBleHostAdapter, the one host port on the device.
file src/ble/stack/nimble_host_shim.cpp
The NimBLE-free host:: call surface, forwarding each call to the active host port (device and native builds).
file src/ble/stack/reason_tally.h
A fixed-size count of events by reason code, for bench diagnostics.
file src/ble/stack/teardown_budget.h
How long each part of a BLE teardown may take, and their sum.

Classes

class kleidos::ble::stack::AdvertisingHold
The owner's stop over the advertising the stack would resume on its own. More about kleidos::ble::stack::AdvertisingHold
struct kleidos::ble::stack::WindowChangeView
What the adapter knows when the pairing window changes. More about kleidos::ble::stack::WindowChangeView
class kleidos::ble::stack::BleCommandQueue
Static MPSC command queue feeding the BLE stack task. More about kleidos::ble::stack::BleCommandQueue
class kleidos::ble::stack::BleEventBus
Static event bus distributing BleEvent values to subscribers. More about kleidos::ble::stack::BleEventBus
class kleidos::ble::stack::BleStackTask
Static controller for the Core 0 BLE stack task. More about kleidos::ble::stack::BleStackTask
class kleidos::ble::stack::CallbackTiming
One kind of host callback since boot: its worst time, overruns and count. More about kleidos::ble::stack::CallbackTiming
class kleidos::ble::stack::TimedCallback
Times one callback from its construction to its end into a record. More about kleidos::ble::stack::TimedCallback
struct kleidos::ble::stack::guard::JudgedTiming
The last timing judge on a link, as the console prints it. More about kleidos::ble::stack::guard::JudgedTiming
class kleidos::ble::stack::HostAccessGate
The host's lifecycle phase plus the count of callers inside it. More about kleidos::ble::stack::HostAccessGate
class kleidos::ble::stack::HostAccess
One call into the host: admitted on construction, out on destruction. More about kleidos::ble::stack::HostAccess
class kleidos::ble::stack::NimBleHostAdapter
Concrete NimBleHostPort backed by the IDF-bundled Apache NimBLE host. More about kleidos::ble::stack::NimBleHostAdapter
struct kleidos::ble::stack::HostLinkInfo
Vendor-free, read-only snapshot of the live host link. More about kleidos::ble::stack::HostLinkInfo
struct kleidos::ble::stack::HostTaskStack
How much of the NimBLE host task's stack is used, for diagnostics. More about kleidos::ble::stack::HostTaskStack
struct kleidos::ble::stack::NativeBond
One bond in the host's own keystore: its identity, and whether a comparison confirmed its key. More about kleidos::ble::stack::NativeBond
struct kleidos::ble::stack::StoreSweep
What a keystore sweep removed (and, on host-based privacy, restored). More about kleidos::ble::stack::StoreSweep
class kleidos::ble::stack::NimBleHostPort
Abstract BLE-host port: the only seam through which the BLE module drives the underlying host stack. More about kleidos::ble::stack::NimBleHostPort
class kleidos::ble::stack::ReasonTally
A count per reason code, for the first kReasonTallySlots distinct codes. More about kleidos::ble::stack::ReasonTally

Typedefs

usingkleidos::ble::stack::EventHandler
Subscriber callback (shared with Facade).
usingkleidos::ble::stack::SubscriptionId
Subscription handle (shared with Facade).

Enumerations

enum class kleidos::ble::stack::AdvFilter : uint8_t { kleidos::ble::stack::AdvFilter::Open , kleidos::ble::stack::AdvFilter::AcceptList }
The filter policy an advertising set runs with. More about kleidos::ble::stack::AdvFilter
enum class kleidos::ble::stack::WindowRestart : uint8_t { kleidos::ble::stack::WindowRestart::Restart , kleidos::ble::stack::WindowRestart::LinkInProgress , kleidos::ble::stack::WindowRestart::NotAdvertising , kleidos::ble::stack::WindowRestart::FilterUnchanged }
What a change of the pairing window does to the running advertising set. More about kleidos::ble::stack::WindowRestart
enum class kleidos::ble::stack::HostPhase : uint8_t { kleidos::ble::stack::HostPhase::Down , kleidos::ble::stack::HostPhase::Starting , kleidos::ble::stack::HostPhase::Synced , kleidos::ble::stack::HostPhase::Stopping }
Where the NimBLE host stands in one radio session. More about kleidos::ble::stack::HostPhase
enum class kleidos::ble::stack::HostNeed : uint8_t { kleidos::ble::stack::HostNeed::Built , kleidos::ble::stack::HostNeed::Identity }
What a call into the host needs to exist. More about kleidos::ble::stack::HostNeed
enum class kleidos::ble::stack::HostCaller : uint8_t { kleidos::ble::stack::HostCaller::Other , kleidos::ble::stack::HostCaller::HostTask }
Which task a call into the host comes from. More about kleidos::ble::stack::HostCaller

Functions

constexpr AdvFilterkleidos::ble::stack::advFilterFor (bool windowOpen, bool acceptListUsable, bool anyBonded)
The filter the window asks of the advertising set.
constexpr WindowRestartkleidos::ble::stack::windowRestartFor (const WindowChangeView &view)
Whether a change of the pairing window restarts the running set.
constexpr boolkleidos::ble::stack::ownerStartsNow (bool linkInHost)
Whether the owner's start may start an advertising set now.
constexpr uint8_tkleidos::ble::stack::guard::judgedCode (connection::LinkTimingStep step)
The judge code of a timing step.
constexpr uint64_tkleidos::ble::stack::guard::packJudgedTiming (connection::LinkTimingStep step, const connection::LiveConnParams &live)
Pack a timing judge into one word.
constexpr JudgedTimingkleidos::ble::stack::guard::unpackJudgedTiming (uint64_t word)
Unpack a word packJudgedTiming made.
constexpr size_tkleidos::ble::stack::guard::gateRefusalSlot (security::store_gate::KeyVerdict verdict)
The count slot of a keystore verdict.
constexpr boolkleidos::ble::stack::hostAdmits (HostPhase phase, HostNeed need, HostCaller caller, bool identity)
Pure decision: whether a call may enter the host.
boolkleidos::ble::stack::host::init (const char *deviceName, bool fastAdvertising, bool pairingWindowOpen)
Initialize NimBLE, build the HID service, start advertising.
voidkleidos::ble::stack::host::deinitFull (bool &peerWasConnected)
Stop advertising, disconnect any peer (waits up to 1500 ms), then fully deinitialize the host stack. Resets all link-state.
voidkleidos::ble::stack::host::clearShuttingDown ()
Cancel any in-flight shutdown attempt (called at start).
boolkleidos::ble::stack::host::isInitialized ()
True once NimBLE has been initialized.
boolkleidos::ble::stack::host::isSynced ()
True once the host+controller have synced (the onSync callback ran).
boolkleidos::ble::stack::host::isConnected ()
True when a peer connection is up (link layer).
boolkleidos::ble::stack::host::isAuthenticated ()
True when the link is encrypted and MITM-authenticated.
boolkleidos::ble::stack::host::isPairing ()
True while a pairing is under way on the live link.
boolkleidos::ble::stack::host::isShuttingDown ()
True while a full teardown is in progress.
boolkleidos::ble::stack::host::isAdvertising ()
True while the host is actively advertising.
boolkleidos::ble::stack::host::deleteBond (const uint8_t addr[6], uint8_t addrType)
Delete a runtime NimBLE bond by identity address.
boolkleidos::ble::stack::host::deletePublicBond (const uint8_t addr[6])
Delete a runtime NimBLE bond using a public-address fallback.
boolkleidos::ble::stack::host::readNativeBonds (NativeBond *out, uint8_t capacity, uint8_t &count)
Read every NimBLE-persisted bond in one pass, or say it could not.
boolkleidos::ble::stack::host::readPersistedBonds (NativeBond *out, uint8_t capacity, uint8_t &count)
Read the bonds the keystore persisted, with the radio fully off (NimBleHostPort::readPersistedBonds).
StoreSweepkleidos::ble::stack::host::sweepStoreOrphans ()
Delete every stored record no whole bond owns (NimBleHostPort::sweepStoreOrphans).
voidkleidos::ble::stack::host::dropLinkOf (const uint8_t addr[6])
Drop the live link when its peer is addr (NimBleHostPort::dropLinkOf).
uint8_tkleidos::ble::stack::host::persistedNativeBondCount ()
Count the bonds NimBLE persisted in NVS, readable while the radio is OFF.
boolkleidos::ble::stack::host::injectNumericComparison (uint16_t connHandle, uint16_t generation, bool accept)
Inject the user's Numeric Comparison decision into the link that asked.
boolkleidos::ble::stack::host::numericComparisonLinkAdmitted (uint16_t connHandle)
True when a yes to a comparison raised on connHandle may confirm it.
voidkleidos::ble::stack::host::startAdvertising (bool fastAdvertising=true)
Start (or restart) advertising.
voidkleidos::ble::stack::host::stopFailedSession ()
Stop a failed session: its advertising, and its link if it never secured.
voidkleidos::ble::stack::host::setPairingWindow (bool open)
Open or close the "add a new host" pairing window.
boolkleidos::ble::stack::host::isPairingWindowOpen ()
True while the "add a new host" pairing window is open.
boolkleidos::ble::stack::host::repairPeer (uint8_t addrOut[6], uint8_t &addrTypeOut)
The identity of the bonded host that raised the re-pair prompt.
boolkleidos::ble::stack::host::keepRepairIdentityKey ()
Keep the identity key of the host whose re-pair the owner allowed, before its old bond is deleted.
voidkleidos::ble::stack::host::dropRepairLink ()
Drop the link of the host whose re-pair the owner allowed.
boolkleidos::ble::stack::host::repairHostPaired ()
Whether the live link is the allowed host's fresh pairing.
voidkleidos::ble::stack::host::endRepair ()
The allowed host's fresh pairing completed: forget its identity.
boolkleidos::ble::stack::host::ownAddressRefused ()
Whether the advertising is refused because privacy could not be set up.
voidkleidos::ble::stack::host::applyPendingConnectionParams ()
Apply any connection parameter update requested by the callbacks. Runs on BleStackTask/Core 0 from the normal update cadence.
voidkleidos::ble::stack::host::applyPendingMtuUpdate ()
Apply any MTU update requested by the callbacks. Runs on BleStackTask/Core 0 from the normal update cadence.
voidkleidos::ble::stack::host::setBatteryLevel (uint8_t level)
Set the battery level the Battery Level characteristic serves.
voidkleidos::ble::stack::host::applyPendingBatteryLevel ()
Notify a subscribed host of a battery level it does not have yet. Runs on BleStackTask/Core 0 from the normal update cadence.
boolkleidos::ble::stack::host::sendReport (uint8_t modifiers, uint8_t keycode)
Send an 8-byte HID keyboard report.
boolkleidos::ble::stack::host::releaseAllKeys ()
Send one all-zero keyboard report, so the host holds no key.
uint8_tkleidos::ble::stack::host::hostKeyboardLeds ()
The keyboard LED byte the host last wrote on the live link.
uint32_tkleidos::ble::stack::host::hostKeyboardLedWrites ()
How many keyboard LED writes the host has made, on any link.
boolkleidos::ble::stack::host::consumeConnectPending (uint8_t addrOut[6], uint8_t &addrTypeOut, uint16_t &mtuOut)
Atomically read-and-clear the connect pending flag. When it returns true, addrOut, addrTypeOut, and mtuOut describe the peer from the onConnect callback.
boolkleidos::ble::stack::host::consumeAuthPending (uint8_t addrOut[6], uint8_t &addrTypeOut, bool &freshPairingOut)
Atomically read-and-clear the auth-complete pending flag. When it returns true, addrOut is filled with the peer address that just authenticated.
boolkleidos::ble::stack::host::consumeUnstoredPairing (uint8_t addrOut[6], security::store_gate::PersistResult &resultOut)
Atomically read-and-clear a confirmed pairing the keystore did not keep.
boolkleidos::ble::stack::host::consumeDisconnectPending ()
Atomically read-and-clear the disconnect pending flag.
boolkleidos::ble::stack::host::consumeCccdPending (connection::CccdChange &out)
Take the oldest CCCD change the subscribe callback parked.
voidkleidos::ble::stack::host::clearPendingMailbox ()
Wipe every pending mailbox: the flags and the CCCD changes (called at stopRuntime entry).
uint32_tkleidos::ble::stack::host::callbackMaxUs ()
Worst-case NimBLE callback wall time.
uint32_tkleidos::ble::stack::host::callbackOverBudgetCount ()
Number of callbacks that exceeded their budget.
uint32_tkleidos::ble::stack::host::storeWriteMaxUs ()
Worst-case keystore write wall time (NimBLE's NVS persistence of a bond).
uint32_tkleidos::ble::stack::host::storeWriteCount ()
Number of keystore write callbacks timed.
uint32_tkleidos::ble::stack::host::cccdMailboxOverwriteCount ()
CCCD changes that gave way to a newer one in a full mailbox.
size_tkleidos::ble::stack::host::formatSecurityTrace (char *out, size_t outLen)
Render a security trace into out.
voidkleidos::ble::stack::host::hostLinkInfo (HostLinkInfo &out)
Fill out with a cheap snapshot of the live host link.
uint32_tkleidos::ble::stack::host::reportsSentCount ()
Total HID keystroke reports successfully sent since boot.
uint32_tkleidos::ble::stack::host::hostDrainOverrunCount ()
Teardowns that freed the host with a caller from another task still inside it, the drain before the free having run out (since boot).
uint8_tkleidos::ble::stack::host::protocolMode ()
Currently selected HOGP Protocol Mode.
voidkleidos::ble::stack::host::setPortForTest (NimBleHostPort *port)
Native-only: inject the NimBleHostPort the host:: shim forwards to.

Variables

constexpr uint32_tkleidos::ble::stack::kCallbackBudgetUs
constexpr std::array< connection::LinkTimingStep, 4 >kleidos::ble::stack::guard::kJudgedSteps
constexpr std::array< security::store_gate::KeyVerdict, 4 >kleidos::ble::stack::guard::kGateRefusedVerdicts
constexpr size_tkleidos::ble::stack::guard::kGateUnboundSlot
The slot that counts bound records refused for want of a confirmed key (unbound).
constexpr size_tkleidos::ble::stack::guard::kGateSlots
Count slots the gate keeps: one per refused verdict, then the unbound one.
constexpr size_tkleidos::ble::stack::guard::kGateNoSlot
What gateRefusalSlot returns for a verdict the gate does not refuse.
constexpr size_tkleidos::ble::stack::kReasonTallySlots
Distinct reason codes a tally keeps before it folds the rest into other.
constexpr uint32_tkleidos::ble::stack::kDeinitDisconnectWaitMs
constexpr uint32_tkleidos::ble::stack::kDeinitDrainBudgetMs
constexpr uint32_tkleidos::ble::stack::kStopSyncWaitMs
constexpr uint32_tkleidos::ble::stack::kHostStopBudgetMs
constexpr uint32_tkleidos::ble::stack::kTeardownSlackMs
constexpr uint32_tkleidos::ble::stack::kTeardownWorstCaseMs
The longest a teardown takes, end to end.

Back to the top

Enumeration Type Documentation

AdvFilter #

enum class kleidos::ble::stack::AdvFilter : uint8_t

The filter policy an advertising set runs with.

Enumerator
Open 

Any central may connect (no filter).

AcceptList 

Only the bonded identities on the controller accept-list.

HostCaller #

enum class kleidos::ble::stack::HostCaller : uint8_t

Which task a call into the host comes from.

Enumerator
Other 

Any task but the host's own: the loop task, the BLE stack task.

HostTask 

The NimBLE host task, inside one of its callbacks.

HostNeed #

enum class kleidos::ble::stack::HostNeed : uint8_t

What a call into the host needs to exist.

Enumerator
Built 

The host mutex and its GAP, connection and store state.

Identity 

All of that plus the identity-address context (first sync).

HostPhase #

enum class kleidos::ble::stack::HostPhase : uint8_t

Where the NimBLE host stands in one radio session.

Enumerator
Down 

Not built, or freed: no host call is safe.

Starting 

Built (mutex, GAP, connections, store); the identity context is not yet.

Synced 

Synced at least once since it was built: the identity context exists too.

Stopping 

Being torn down: no new call from another task is admitted.

WindowRestart #

enum class kleidos::ble::stack::WindowRestart : uint8_t

What a change of the pairing window does to the running advertising set.

Enumerator
Restart 

Stop the set and start it again with the new filter.

LinkInProgress 

A link is being made, paired or is up: the start after it reads the window.

NotAdvertising 

No set runs: the next start reads the window.

FilterUnchanged 

The running set already has the filter the window asks for.

Back to the top

Function Documentation

advFilterFor() #

AdvFilter kleidos::ble::stack::advFilterFor(bool windowOpen, bool acceptListUsable, bool anyBonded)
constexpr

The filter the window asks of the advertising set.

Parameters
NameDirectionMeaning
windowOpeninThe "add a new host" pairing window is open.
acceptListUsableinThe build filters by the controller accept-list (an ESP32-S3; not the classic ESP32's host-based privacy).
anyBondedinThe keystore lists at least one bonded host.
Returns
AdvFilter::AcceptList with the window closed, a usable list and a bonded host; AdvFilter::Open otherwise.

callbackMaxUs() #

uint32_t kleidos::ble::stack::host::callbackMaxUs()

Worst-case NimBLE callback wall time.

The GAP event, attribute access and keystore status callbacks; the keystore write is storeWriteMaxUs().

Returns
Max callback time in microseconds since boot.

callbackOverBudgetCount() #

uint32_t kleidos::ble::stack::host::callbackOverBudgetCount()

Number of callbacks that exceeded their budget.

The same callbacks as callbackMaxUs(), the keystore write left out.

Returns
Total over-budget callback count since boot.

cccdMailboxOverwriteCount() #

uint32_t kleidos::ble::stack::host::cccdMailboxOverwriteCount()

CCCD changes that gave way to a newer one in a full mailbox.

Returns
CCCD changes dropped since boot.

consumeAuthPending() #

bool kleidos::ble::stack::host::consumeAuthPending(uint8_t addrOut[6], uint8_t & addrTypeOut, bool & freshPairingOut)

Atomically read-and-clear the auth-complete pending flag. When it returns true, addrOut is filled with the peer address that just authenticated.

Parameters
NameDirectionMeaning
addrOutout6-byte peer identity address.
addrTypeOutoutAddress type (0 = public, 1 = random).
freshPairingOutoutTrue when the link paired (a numeric comparison ran on it), false when it restored a stored key.
Return values
ValueMeaning
trueA pending auth event was present and consumed; outputs are populated.
falseNo pending auth event.

consumeCccdPending() #

bool kleidos::ble::stack::host::consumeCccdPending(connection::CccdChange & out)

Take the oldest CCCD change the subscribe callback parked.

Parameters
NameDirectionMeaning
outoutReceives the change and the link state it came on.
Return values
ValueMeaning
trueA change was taken.
falseNo change is parked.
Note
Runs on the main task, after the connect and auth drains.

consumeConnectPending() #

bool kleidos::ble::stack::host::consumeConnectPending(uint8_t addrOut[6], uint8_t & addrTypeOut, uint16_t & mtuOut)

Atomically read-and-clear the connect pending flag. When it returns true, addrOut, addrTypeOut, and mtuOut describe the peer from the onConnect callback.

Parameters
NameDirectionMeaning
addrOutout6-byte peer identity address.
addrTypeOutoutAddress type (0 = public, 1 = random).
mtuOutoutNegotiated ATT MTU.
Return values
ValueMeaning
trueA pending connect event was present and consumed; outputs are populated.
falseNo pending connect event.

consumeDisconnectPending() #

bool kleidos::ble::stack::host::consumeDisconnectPending()

Atomically read-and-clear the disconnect pending flag.

Return values
ValueMeaning
trueA pending disconnect event was present and consumed.
falseNo pending disconnect event.

consumeUnstoredPairing() #

bool kleidos::ble::stack::host::consumeUnstoredPairing(uint8_t addrOut[6], security::store_gate::PersistResult & resultOut)

Atomically read-and-clear a confirmed pairing the keystore did not keep.

Parameters
NameDirectionMeaning
addrOutout6-byte peer identity address.
resultOutoutWhy its keys were not kept.
Return values
ValueMeaning
trueOne was pending and consumed; outputs are populated.
falseNone pending.

deinitFull() #

void kleidos::ble::stack::host::deinitFull(bool & peerWasConnected)

Stop advertising, disconnect any peer (waits up to 1500 ms), then fully deinitialize the host stack. Resets all link-state.

Parameters
NameDirectionMeaning
peerWasConnectedoutSet to true if a peer was active when called; used by the bond layer to decide whether to flush NVS post-deinit.

deleteBond() #

bool kleidos::ble::stack::host::deleteBond(const uint8_t addr[6], uint8_t addrType)

Delete a runtime NimBLE bond by identity address.

Parameters
NameDirectionMeaning
addrin6-byte peer identity address.
addrTypein0 = public, 1 = random.
Return values
ValueMeaning
trueThe bond was found and deleted.
falseNo matching bond existed or delete failed.

deletePublicBond() #

bool kleidos::ble::stack::host::deletePublicBond(const uint8_t addr[6])

Delete a runtime NimBLE bond using a public-address fallback.

Parameters
NameDirectionMeaning
addrin6-byte peer address (interpreted as public).
Return values
ValueMeaning
trueThe bond was found and deleted.
falseNo matching bond existed or delete failed.

dropLinkOf() #

void kleidos::ble::stack::host::dropLinkOf(const uint8_t addr[6])

Drop the live link when its peer is addr (NimBleHostPort::dropLinkOf).

Parameters
NameDirectionMeaning
addrin6-byte peer identity address.

dropRepairLink() #

void kleidos::ble::stack::host::dropRepairLink()

Drop the link of the host whose re-pair the owner allowed.

Note
Core 0 (ble::stack::BleStackTask).

formatSecurityTrace() #

size_t kleidos::ble::stack::host::formatSecurityTrace(char * out, size_t outLen)

Render a security trace into out.

Parameters
NameDirectionMeaning
outoutDestination buffer; always NUL-terminated on success.
outLeninCapacity of out in bytes.
Returns
Number of bytes written excluding the NUL terminator.

gateRefusalSlot() #

size_t kleidos::ble::stack::guard::gateRefusalSlot(security::store_gate::KeyVerdict verdict)
constexpr

The count slot of a keystore verdict.

Parameters
NameDirectionMeaning
verdictinThe gate's verdict on a peer record.
Returns
Its place in kGateRefusedVerdicts; kGateNoSlot for Store or a value not listed.

hostAdmits() #

bool kleidos::ble::stack::hostAdmits(HostPhase phase, HostNeed need, HostCaller caller, bool identity)
constexpr

Pure decision: whether a call may enter the host.

Parameters
NameDirectionMeaning
phaseinThe host's phase.
needinWhat the call needs to exist.
callerinWhich task makes the call.
identityinWhether a sync has built the identity context.
Returns
true when the host's memory the call touches exists, and stays until the call leaves.

hostDrainOverrunCount() #

uint32_t kleidos::ble::stack::host::hostDrainOverrunCount()

Teardowns that freed the host with a caller from another task still inside it, the drain before the free having run out (since boot).

Returns
The count; 0 on a sound board.

hostKeyboardLeds() #

uint8_t kleidos::ble::stack::host::hostKeyboardLeds()

The keyboard LED byte the host last wrote on the live link.

Returns
Its bits; 0 when it wrote none.

hostKeyboardLedWrites() #

uint32_t kleidos::ble::stack::host::hostKeyboardLedWrites()

How many keyboard LED writes the host has made, on any link.

Returns
The count; it never goes back, so a change of it means a new write.

hostLinkInfo() #

void kleidos::ble::stack::host::hostLinkInfo(HostLinkInfo & out)

Fill out with a cheap snapshot of the live host link.

Parameters
NameDirectionMeaning
outoutReceives own address, connection params and live security state.
Note
Any task; read-only (no HCI round-trip).

init() #

bool kleidos::ble::stack::host::init(const char * deviceName, bool fastAdvertising, bool pairingWindowOpen)

Initialize NimBLE, build the HID service, start advertising.

Parameters
NameDirectionMeaning
deviceNameinBLE device name string (NUL-terminated).
fastAdvertisingintrue = 30 ms interval; false = 160 ms (power saving).
pairingWindowOpeninThe session opens the "add a new host" window, in force from the first advertising.
Return values
ValueMeaning
trueInit succeeded and advertising is running.
falseNimBLE was already initialized or init failed.

injectNumericComparison() #

bool kleidos::ble::stack::host::injectNumericComparison(uint16_t connHandle, uint16_t generation, bool accept)

Inject the user's Numeric Comparison decision into the link that asked.

Parameters
NameDirectionMeaning
connHandleinThe connection the request was armed for.
generationinThe generation of the request the owner answered.
acceptintrue to confirm the passkey; false to reject.
Return values
ValueMeaning
trueThe decision was applied successfully.
falseThe decision could not be applied (that link is gone or no longer asks that request, or the stack is not ready).

isAdvertising() #

bool kleidos::ble::stack::host::isAdvertising()

True while the host is actively advertising.

Return values
ValueMeaning
trueA NimBLE advertising set is enabled.
falseThe host is not currently advertising.

isAuthenticated() #

bool kleidos::ble::stack::host::isAuthenticated()

True when the link is encrypted and MITM-authenticated.

Return values
ValueMeaning
trueLE Secure Connections Numeric Comparison succeeded.
falseLink is not yet encrypted/authenticated.

isConnected() #

bool kleidos::ble::stack::host::isConnected()

True when a peer connection is up (link layer).

Return values
ValueMeaning
trueA peer has a live BLE connection.
falseNo peer is currently connected.

isInitialized() #

bool kleidos::ble::stack::host::isInitialized()

True once NimBLE has been initialized.

Return values
ValueMeaning
trueinit() has succeeded and the host is up.
falsePre-init or post-deinit.

isPairing() #

bool kleidos::ble::stack::host::isPairing()

True while a pairing is under way on the live link.

Return values
ValueMeaning
trueThe link raised a numeric comparison (or the owner allowed its re-pair) and its encryption has neither completed nor failed, nor has the owner refused the comparison.
falseNo pairing on the link: none started, it ended, or no link.

isPairingWindowOpen() #

bool kleidos::ble::stack::host::isPairingWindowOpen()

True while the "add a new host" pairing window is open.

Return values
ValueMeaning
trueAdvertising is open to any central.
falseBonded-only accept-list is enforced once a host is bonded.

isShuttingDown() #

bool kleidos::ble::stack::host::isShuttingDown()

True while a full teardown is in progress.

Return values
ValueMeaning
trueBetween deinitFull() entry and the actual deinit completion.
falseStack is idle or fully deinitialized.

isSynced() #

bool kleidos::ble::stack::host::isSynced()

True once the host+controller have synced (the onSync callback ran).

Strictly later than isInitialized(): init() returns as soon as the host task is spawned, but the bond store and ble_gap_unpair only become writable after sync. Deferred bond deletions must gate on this, not on isInitialized().

Return values
ValueMeaning
trueThe controller is ready; bond operations take effect.
falsePre-sync (or post-deinit / mid-reset).

judgedCode() #

uint8_t kleidos::ble::stack::guard::judgedCode(connection::LinkTimingStep step)
constexpr

The judge code of a timing step.

Parameters
NameDirectionMeaning
stepinThe step.
Returns
1..4, its place in kJudgedSteps plus one; 0 for a step not listed.

keepRepairIdentityKey() #

bool kleidos::ble::stack::host::keepRepairIdentityKey()

Keep the identity key of the host whose re-pair the owner allowed, before its old bond is deleted.

Return values
ValueMeaning
trueThe old bond held one, and it is kept.
falseIt held none: no pairing under those bytes is stored until the approval ends.
Note
Core 0 (ble::stack::BleStackTask).

numericComparisonLinkAdmitted() #

bool kleidos::ble::stack::host::numericComparisonLinkAdmitted(uint16_t connHandle)

True when a yes to a comparison raised on connHandle may confirm it.

Parameters
NameDirectionMeaning
connHandleinThe link the request was armed for.
Return values
ValueMeaning
trueIt is the live link the host filter admitted.
falseIt is gone, another link is current, or the filter drops it.

ownAddressRefused() #

bool kleidos::ble::stack::host::ownAddressRefused()

Whether the advertising is refused because privacy could not be set up.

Return values
ValueMeaning
trueA shipping build refused to advertise with its identity address.
falsePrivacy is on, or the build allows the fallback.

ownerStartsNow() #

bool kleidos::ble::stack::ownerStartsNow(bool linkInHost)
constexpr

Whether the owner's start may start an advertising set now.

A link NimBLE holds keeps its slot (one connection, CONFIG_BT_NIMBLE_MAX_CONNECTIONS=1): its end restarts advertising (the drain after a disconnect, the end of a link the host filter dropped, a failed attempt), and a start made under it would only be refused (ble_hs_conn_can_alloc).

Parameters
NameDirectionMeaning
linkInHostinNimBLE holds a connection, whatever its stage.
Return values
ValueMeaning
trueStart now.
falseLeave it to the link's end.

packJudgedTiming() #

uint64_t kleidos::ble::stack::guard::packJudgedTiming(connection::LinkTimingStep step, const connection::LiveConnParams & live)
constexpr

Pack a timing judge into one word.

Parameters
NameDirectionMeaning
stepinThe step the judge took.
liveinThe timing it judged.
Returns
code << 48 | interval << 32 | latency << 16 | timeout; never 0 for a listed step.

persistedNativeBondCount() #

uint8_t kleidos::ble::stack::host::persistedNativeBondCount()

Count the bonds NimBLE persisted in NVS, readable while the radio is OFF.

BLE is on-demand on Kleidos: at boot and in PIN_ENTRY the stack is OFF, so readNativeBonds() — which queries the live NimBLE bond store — refuses 0 even though the LTKs are intact in NVS (CONFIG_BT_NIMBLE_NVS_PERSIST). That OFF-window 0 has repeatedly read as "bonds dropped on reboot" in QA when the bonds in fact survive. This helper reads the persisted count directly out of NimBLE's own bond storage (counting the stored peer security records) through the platform NVS facade, so a diagnostic can report the durable bond count when the live stack is down.

Warning
Reads NVS, so it is only safe while BLE is fully OFF — it returns 0 when the stack is up (use readNativeBonds() then) to honor the "NVS only when the radio is down" discipline.
Returns
Number of bonds persisted in NimBLE's NVS store, or 0 when the radio is up, on native builds, or on any NVS error.

protocolMode() #

uint8_t kleidos::ble::stack::host::protocolMode()

Currently selected HOGP Protocol Mode.

Returns
0x00 = Boot Protocol, 0x01 = Report Protocol (default).

readNativeBonds() #

bool kleidos::ble::stack::host::readNativeBonds(NativeBond * out, uint8_t capacity, uint8_t & count)

Read every NimBLE-persisted bond in one pass, or say it could not.

The stack's own view, independent of the Kleidos bond table (kleidos::ble::bond::NameStore), and the only live keystore read: false means the keystore was not read (stack down, being torn down, or the store refused), never that it is empty.

Parameters
NameDirectionMeaning
outoutBonds read.
capacityinEntries out holds.
countoutBonds written (0 on failure).
Return values
ValueMeaning
trueThe keystore was read.
falseIt could not be read.

readPersistedBonds() #

bool kleidos::ble::stack::host::readPersistedBonds(NativeBond * out, uint8_t capacity, uint8_t & count)

Read the bonds the keystore persisted, with the radio fully off (NimBleHostPort::readPersistedBonds).

Parameters
NameDirectionMeaning
outoutBonds read.
capacityinEntries out holds.
countoutBonds written (0 on failure).
Return values
ValueMeaning
trueThe persisted store was read (0 bonds when none was stored).
falseIt could not be read, or the radio is not fully off.

releaseAllKeys() #

bool kleidos::ble::stack::host::releaseAllKeys()

Send one all-zero keyboard report, so the host holds no key.

Return values
ValueMeaning
trueIt went out, or no link is up to hold a key.
falseIt did not; the link was ended, which lifts every key too.

repairHostPaired() #

bool kleidos::ble::stack::host::repairHostPaired()

Whether the live link is the allowed host's fresh pairing.

Return values
ValueMeaning
trueThe host whose re-pair the owner allowed paired fresh on it.
falseAnother host, a restored key, or no link.

repairPeer() #

bool kleidos::ble::stack::host::repairPeer(uint8_t addrOut[6], uint8_t & addrTypeOut)

The identity of the bonded host that raised the re-pair prompt.

Parameters
NameDirectionMeaning
addrOutoutThe identity address (6 bytes).
addrTypeOutoutIts address type.
Return values
ValueMeaning
trueA host asked, and its identity was written.
falseNo re-pair prompt stands.

reportsSentCount() #

uint32_t kleidos::ble::stack::host::reportsSentCount()

Total HID keystroke reports successfully sent since boot.

Returns
Cumulative successful sendReport() count.

sendReport() #

bool kleidos::ble::stack::host::sendReport(uint8_t modifiers, uint8_t keycode)

Send an 8-byte HID keyboard report.

Parameters
NameMeaning
modifiersModifier byte (Shift, Ctrl, Alt, etc.).
keycodeHID usage code for the key.
Return values
ValueMeaning
trueThe report was queued or delivered to the input characteristic.
falseThe link is not up or the input characteristic is unavailable.

setBatteryLevel() #

void kleidos::ble::stack::host::setBatteryLevel(uint8_t level)

Set the battery level the Battery Level characteristic serves.

Parameters
NameDirectionMeaning
levelinBattery level, 0..100 % (the main loop's sample, never a chip read of the host's own).
Note
Any task; lock-free. Kept across a teardown.

setPairingWindow() #

void kleidos::ble::stack::host::setPairingWindow(bool open)

Open or close the "add a new host" pairing window.

Open = advertise to any central so a brand-new host can pair; closed (default) = once at least one host is bonded, only bonded identities may hold the link, so a central that is not bonded cannot pair and pose as a host. Restarts a running advertising set only when its filter changes and no link is at any stage; otherwise the next start applies it.

Parameters
NameDirectionMeaning
openintrue to open the pairing window; false to enforce bonded-only.
Note
Preferred on Core 0 (ble::stack::BleStackTask).

setPortForTest() #

void kleidos::ble::stack::host::setPortForTest(NimBleHostPort * port)

Native-only: inject the NimBleHostPort the host:: shim forwards to.

Lets unit tests drive the upper BLE layers against a FakeNimBleHostPort without any NimBLE coupling. Has no device build (production always resolves the NimBleHostAdapter singleton).

Parameters
NameDirectionMeaning
portinThe fake port to forward to (must outlive the calls).

startAdvertising() #

void kleidos::ble::stack::host::startAdvertising(bool fastAdvertising = true)

Start (or restart) advertising.

Parameters
NameDirectionMeaning
fastAdvertisingintrue = 30 ms interval; false = 160 ms (power saving).
Note
Preferred on Core 0 (ble::stack::BleStackTask).

stopFailedSession() #

void kleidos::ble::stack::host::stopFailedSession()

Stop a failed session: its advertising, and its link if it never secured.

Holds advertising until the owner's next start and ends a live link that is not secured by now (finding C11). Only for a session that failed: a pairing in progress goes with it.

Note
Preferred on Core 0 (ble::stack::BleStackTask).

storeWriteCount() #

uint32_t kleidos::ble::stack::host::storeWriteCount()

Number of keystore write callbacks timed.

Every call, the records the gate refuses (which reach no NVS) included.

Returns
Keystore write callbacks since boot.

storeWriteMaxUs() #

uint32_t kleidos::ble::stack::host::storeWriteMaxUs()

Worst-case keystore write wall time (NimBLE's NVS persistence of a bond).

Returns
Max keystore write time in microseconds since boot.

sweepStoreOrphans() #

StoreSweep kleidos::ble::stack::host::sweepStoreOrphans()

Delete every stored record no whole bond owns (NimBleHostPort::sweepStoreOrphans).

Returns
What was removed and added; all zero when nothing was read.

unpackJudgedTiming() #

JudgedTiming kleidos::ble::stack::guard::unpackJudgedTiming(uint64_t word)
constexpr

Unpack a word packJudgedTiming made.

Parameters
NameDirectionMeaning
wordinThe word; 0 when the link was not judged.
Returns
The judge; all zero for 0.

windowRestartFor() #

WindowRestart kleidos::ble::stack::windowRestartFor(const WindowChangeView & view)
constexpr

Whether a change of the pairing window restarts the running set.

A link at any stage comes first: no stop is ever made under it.

Parameters
NameDirectionMeaning
viewinWhat the adapter knows.
Returns
The verdict.

Back to the top

Variable Documentation

kCallbackBudgetUs #

uint32_t kleidos::ble::stack::kCallbackBudgetUs
inlineconstexpr

A host callback longer than this is counted as over budget (µs). Five milliseconds is a host-responsiveness budget for the GAP event and attribute callbacks. Connection events run in the controller, at a higher priority than the host task, so a host callback past it delays the host's processing of the next event; it does not make the link miss one. NimBLE's NVS persistence of a bond is counted apart (store_max_us).

kDeinitDisconnectWaitMs #

uint32_t kleidos::ble::stack::kDeinitDisconnectWaitMs
inlineconstexpr

The wait for the peer-disconnect GAP event after ble_gap_terminate, so a peer that never acknowledges the disconnect cannot wedge the shutdown.

kDeinitDrainBudgetMs #

uint32_t kleidos::ble::stack::kDeinitDrainBudgetMs
inlineconstexpr

Each of the two waits for the callers already inside the host to leave: one before nimble_port_stop(), one before nimble_port_deinit() frees the host. Each caller is one short host call, a few ms at most.

kGateRefusedVerdicts #

std::array<security::store_gate::KeyVerdict, 4> kleidos::ble::stack::guard::kGateRefusedVerdicts
inlineconstexpr

The keystore verdicts the gate refuses, in the order of their count slots (unconfirmed, bad_identity, identity_taken, identity_unproven).

kHostStopBudgetMs #

uint32_t kleidos::ble::stack::kHostStopBudgetMs
inlineconstexpr

nimble_port_stop() on a controller that does not answer: one HCI command timeout (NimBLE's BLE_HCI_CMD_TIMEOUT_MS, 2 s), which a stop still meets when the host did not sync within kStopSyncWaitMs.

kJudgedSteps #

std::array<connection::LinkTimingStep, 4> kleidos::ble::stack::guard::kJudgedSteps
inlineconstexpr

The timing steps in the order of their judge codes 1..4 (settled, ask_again, end_link, keep); code 0 is "not judged".

kStopSyncWaitMs #

uint32_t kleidos::ble::stack::kStopSyncWaitMs
inlineconstexpr

The wait for the host's first sync before nimble_port_stop(). The host task runs its startup HCI sequence until the sync (some 70 ms after the host is built, on both chip families), and ble_hs_stop() marks the host off at once when no link is up, after which the HCI transport drops every controller reply: a startup command then waits out its whole HCI timeout. Letting the sync land first makes that stop take tens of ms.

kTeardownSlackMs #

uint32_t kleidos::ble::stack::kTeardownSlackMs
inlineconstexpr

The rest of the teardown on the BLE stack task (nimble_port_deinit, the state reset, the command hand-off) and the facade's 20 ms polls.

Back to the top