API reference
Header file: #include "BleKbdHost.h"
Class BleKbdHost
Instances of BleKbdHost are non-copyable. Internally, begin() spawns a FreeRTOS worker task (6144-byte stack, priority 1) and an event queue holding up to 32 KeyEvent items.
Initialization, pairing, and connection control
All pairing and connection methods are non-blocking. They signal the background worker task and return immediately.
| Method | Description |
|---|---|
void begin(const char* hostName = "ESP32-BleHost", bool initBleStack = true) |
Starts the background BLE host task. Enters WaitingReconnect if bonds exist, otherwise Idle. Set initBleStack = false if your app already called NimBLEDevice::init(). |
void startPairing(uint32_t timeoutMs = 30000) |
Disconnects any active session and scans for new BLE HID keyboards (0x1812) for timeoutMs milliseconds. |
void cancelPairing() |
Cancels an active pairing scan and returns to WaitingReconnect (if bonds exist) or Idle. |
void requestUnpair() |
Disconnects, deletes all saved NimBLE bonds and cached NVS device names, and transitions to Idle. |
bool hasSavedBond() const |
Returns true if flash storage contains at least one paired keyboard bond. Call after begin(). |
int getPairedCount() const |
Returns the total number of stored paired keyboards (0 if called before begin()). |
bool getPairedDevice(int index, PairedDevice& outDevice) const |
Populates outDevice with the MAC address, cached NVS device name, and active connection status for bond index (0 to getPairedCount() - 1). Returns false if called before begin() or if index is out of range. |
Status queries
| Method | Description |
|---|---|
State getState() const |
Returns the current host state (Idle, WaitingReconnect, PairingScan, Connecting, Connected). |
bool pollStateChange(State& outState) |
Returns true on the first call after begin() and once per subsequent state transition, writing the current state to outState. Lets your main loop initialize and update UI indicators in one place. |
bool isConnected() const |
Shorthand for getState() == State::Connected. |
uint32_t getPairingRemainingSec() const |
Returns remaining seconds rounded up while in PairingScan (0 in all other states). |
const char* getDeviceName() const |
Returns the connected keyboard's resolved name, or "" when disconnected. |
Error getLastError() const |
Returns the most recent connection or pairing error (None, PairingTimeout, ConnectFailed, AuthFailed, NoHidService, SubscribeFailed). Resets on startPairing(), requestUnpair(), or a successful connection. |
Key input, LED output, and layout
| Method | Description |
|---|---|
bool pollEvent(KeyEvent& outEvent) |
Pops the next key-down or media press event from the internal queue. Returns false when the queue is empty. Key release reports don't generate events. |
char readChar() |
Consumes queued events until it finds one with ascii != 0, discarding non-printable events. Returns 0 if none are available. |
bool sendLedReport(uint8_t ledMask) |
Writes a 1-byte LED output report to Boot Keyboard Output (0x2A32). Bit 0 (0x01): NumLock, Bit 1 (0x02): CapsLock, Bit 2 (0x04): ScrollLock. Returns true if the write succeeds, or false if disconnected or unsupported by the keyboard. |
void setLayout(Layout layout) |
Switches keymap decoding at runtime between Layout::US (default) and Layout::JIS. |
Layout getLayout() const |
Returns the active keymap layout. |
void setRawReportCallback(RawReportCallback cb) |
Registers a callback void (*)(uint16_t handle, const uint8_t* data, size_t len) invoked on every incoming BLE HID notification before decoding. Pass nullptr to disable. Keep handlers brief because they run in the NimBLE notification task context. |
Data types and enumerations
BleKbdHost::KeyEvent
struct KeyEvent {
char ascii; // Decoded ASCII character (0 for non-printable/special/media keys)
uint8_t keycode; // Raw HID Usage ID (Page 0x07; 0 for consumer events)
uint8_t modifier; // Raw HID modifier bitmask
SpecialKey special; // Decoded special or media key enum (SpecialKey::None if unmapped)
uint16_t consumerCode; // Raw 16-bit HID Consumer Usage ID (Page 0x0C; 0 for standard keys)
bool shiftPressed() const; // Left (0x02) or Right (0x20) Shift
bool ctrlPressed() const; // Left (0x01) or Right (0x10) Ctrl
bool altPressed() const; // Left (0x04) or Right (0x40) Alt
bool guiPressed() const; // Left (0x08) or Right (0x80) GUI (Win / Cmd)
bool isConsumer() const; // True when consumerCode != 0
};
Control keys:
Enter('\n'),Backspace('\b'), andTab('\t') populate bothev.specialandev.ascii. All otherSpecialKeyitems setev.ascii = 0.
BleKbdHost::PairedDevice
struct PairedDevice {
char address[18]; // Null-terminated MAC string, such as "aa:bb:cc:dd:ee:ff"
char name[32]; // Saved device name from NVS (empty string if unknown)
bool connected; // True if this device is currently connected
};
BleKbdHost::State
State::IdleState::WaitingReconnectState::PairingScanState::ConnectingState::Connected
BleKbdHost::Error
Error::NoneError::PairingTimeout: Pairing scan expired (timeoutMs) before a connection completed.Error::ConnectFailed: BLE link connection timed out or failed.Error::AuthFailed:secureConnection()failed (for example, pairing was rejected, the peer lost its bond, or the keyboard requires Passkey Entry).Error::NoHidService: Connected peripheral doesn't expose service0x1812.Error::SubscribeFailed: Host couldn't subscribe to notifications on either0x2A4Dor0x2A22. During a new pairing (PairingScan), any temporary bond is automatically rolled back; during reconnection (WaitingReconnect), saved bonds are preserved.
BleKbdHost::SpecialKey
| Category | Enum values |
|---|---|
| None | None |
| Editing and navigation | Enter, Backspace, Tab, Escape, Delete, Insert, Home, End, PageUp, PageDown, Right, Left, Down, Up |
| Function and lock | CapsLock, F1 to F12, PrintScreen, ScrollLock, Pause |
| JIS and Japanese input | HankakuZenkaku (0x35, JIS mode only), KatakanaHiragana (0x88), Henkan (0x8A), Muhenkan (0x8B), Kana (0x90), Eisu (0x91) |
Consumer Control (0x0C) |
Power (0x0030), BrightnessUp (0x006F), BrightnessDown (0x0070), MediaNext (0x00B5), MediaPrev (0x00B6), MediaStop (0x00B7), MediaPlayPause (0x00CD), VolumeMute (0x00E2), VolumeUp (0x00E9), VolumeDown (0x00EA), AcSearch (0x0221), AcHome (0x0223), AcBack (0x0224), AcForward (0x0225) |
BleKbdHost::Layout
Layout::US: Standard US ANSI keymap (default).Layout::JIS: Japanese JIS keymap, including JIS symbol layers andHankakuZenkaku(0x35).
JIS layout notes (¥, \, and Kana legends)
¥ (Yen) and \ (backslash)
Single-byte ASCII (char) has no separate code point for the Yen sign. Historical Japanese encodings (JIS X 0201) mapped 0x5C to ¥, whereas standard ASCII maps 0x5C to \.
When Layout::JIS is active, both physical keys decode to 0x5C ('\\') when unshifted, while preserving their distinct Shift symbols and raw keycodes:
| Physical JIS key | HID keycode |
Normal ascii |
Shifted ascii |
|---|---|---|---|
| ろ (left of Right Shift) | 0x87 (International1) |
0x5C (\) |
0x5F (_) |
| ¥ (left of Backspace) | 0x89 (International3) |
0x5C (\) |
0x7C (|) |
If your display uses a Japanese UTF-8 font (such as efontJA on M5Unified) and you want to render ¥ specifically for the 0x89 key, check ev.keycode == 0x89 && !ev.shiftPressed() in your application and print UTF-8 "¥" (U+00A5).
Hiragana keycap legends
JIS keyboards print Hiragana legends on standard keys, but hardware keyboards only transmit standard HID keycodes (for example, 0x04 for the A / ち key). On desktop systems, an OS IME converts keycodes into Hiragana characters. Embedded applications that need direct Kana input can map ev.keycode through a lookup table.
Debug logging
The library disables internal serial logs by default so they never interfere with user serial protocols. To turn on connection logs, add -DBLE_KBD_HOST_DEBUG to build_flags in platformio.ini:
build_flags =
-DBLE_KBD_HOST_DEBUG