BLE API

This is the per-class, per-method reference for BLE. The signatures and descriptions are rendered from the Doxygen comments in the headers through esp-docs and Breathe.

See BLE for concepts, setup, examples and behavior.

BTAddress.h

class BTAddress

Unified Bluetooth address type for both BLE and BT Classic.

Replaces the separate BLEAddress and BTAddress classes. Internally stores 6 bytes in LSB-first (Bluetooth standard) order, matching NimBLE’s native format.

Displayed as “AA:BB:CC:DD:EE:FF” (MSB-first, human-readable convention).

Public Types

enum Type

Address types per Bluetooth Core Spec Vol 6, Part B, 1.3.

Values:

enumerator Public
enumerator Random
enumerator PublicID
enumerator RandomID

Public Functions

BTAddress()

Constructs a zero address (all bytes 0x00, type Public).

BTAddress(const uint8_t addr[6], Type type = Public)

Construct from raw 6-byte array in LSB-first order.

Parameters:
  • addr – 6-byte address array (addr[0] = LSB).

  • type – Address type.

BTAddress(const char *str)

Construct from “AA:BB:CC:DD:EE:FF” string. Also accepts “AABBCCDDEEFF” (no separators).

Parameters:

str – Address string (case-insensitive).

BTAddress(const String &str)

Construct from Arduino String.

explicit operator bool() const

Returns true if the address is non-zero.

const uint8_t *data() const

Returns pointer to the internal 6-byte array (LSB-first).

void toEspBdAddr(uint8_t out[6]) const

Copy the address into a mutable 6-byte buffer as MSB-first.

Reverses the internal LSB-first bytes into the MSB-first order that esp_bd_addr_t uses, for the many ESP-IDF Bluetooth APIs that take a non-const esp_bd_addr_t by pointer. Never memcpy() data() into an esp_bd_addr_t: that skips the byte swap and targets the reversed address.

Parameters:

out – Destination 6-byte array (e.g. an esp_bd_addr_t).

bool equalsEspBdAddr(const uint8_t bda[6]) const

Compare against an MSB-first esp_bd_addr_t, ignoring the type.

For matching a stored address against the esp_bd_addr_t carried by a Bluedroid event, where the event gives no address type to compare.

Parameters:

bda – 6-byte address array (bda[0] = MSB).

Type type() const

Returns the address type.

String toString(bool uppercase = false) const

Convert to “AA:BB:CC:DD:EE:FF” string representation.

Parameters:

uppercase – If true, use uppercase hex digits.

bool isZero() const

Returns true if all 6 address bytes are zero.

Public Static Functions

static BTAddress fromEspBdAddr(const uint8_t bda[6], Type type = Public)

Construct from an esp_bd_addr_t, which is MSB-first.

Bluedroid (BLE and BR/EDR) stores addresses MSB-first (bda[0] = bits 47-40), the opposite of the LSB-first order used internally and by NimBLE. Use this instead of the raw-array constructor for any address coming out of an esp_bd_addr_t, and toEspBdAddr() to convert back.

Parameters:
  • bda – 6-byte address array (bda[0] = MSB).

  • type – Address type.

BTStatus.h

class BTStatus

Unified Bluetooth status/error type for BLE and BT Classic.

Wraps a compact error code with an Arduino-natural boolean conversion: explicit operator bool() returns true on success (OK == 0).

Usage:

if (BLE.begin("MyDevice")) { Serial.println("OK"); }

BTStatus s = client.connect(addr);
if (!s) { Serial.printf("Failed: %s\n", s.toString()); }
if (s == BTStatus::Timeout) { Serial.println("Timed out"); }

Public Functions

inline explicit operator bool() const

Returns true when status is OK (Arduino convention: success = true).

inline explicit operator int() const

Explicit conversion to a plain int.

Lets static_cast<int>(status) and int(status) produce the underlying numeric code — useful for logging (d) or for interop with APIs that expect an integer. The conversion is explicit so it can’t accidentally fire in arithmetic or conditional contexts; use .code() if you want the strongly-typed enum, or .toString() for a human-readable message.

inline Code code() const

Returns the underlying error code.

const char *toString() const

Returns a human-readable string for the status code.

BLE.h

class BLEClass

Global BLE singleton &#8212; the entry point for all BLE operations.

Follows the Arduino convention used by WiFi, Serial, Wire, etc. The class is BLEClass; users interact via the global BLE object.

Thread safety: the BLE singleton methods (begin, end, whitelist operations, etc.) are NOT internally synchronized. Call them from a single task — typically the Arduino loop task. BLE callbacks execute on the stack’s own task (NimBLE host task or Bluedroid BTC task) and must not block. end from a callback is supported (it defers teardown); do not call begin from a callback.

Usage:

#include <BLE.h>

void setup() {
    BLE.begin("MyDevice");
    BLEServer server = BLE.createServer();
    // ...
}

Public Types

using RawEventHandler = std::function<int(void *event, void *arg)>

Signature for raw stack event handlers.

Param event:

Pointer to the backend-specific event structure.

Param arg:

Backend-specific context argument.

Return:

0 on success; non-zero to signal an error to the stack.

Public Functions

BTStatus begin(const String &deviceName = "")

Initialize the BLE stack and set the device name.

Must be called before any other BLE operation. Starts the Bluetooth controller, host stack, and GATT/GAP services.

Parameters:

deviceName – Advertised device name. Empty string keeps the default.

Returns:

BTStatus indicating success or the specific initialization error. InvalidState if end is in progress, including a callback-context end whose teardown worker has not finished.

void end(bool releaseMemory = false)

Shut down the BLE stack.

Stops advertising, disconnects all peers, and deinitializes the host. Local GATT services created since the last begin are released; handles the sketch still holds become detached shells (still non-null, but with no parent or native handle). createServer returns the same server after a later begin — rebuild the database before start().

From the stack callback task this claims shutdown immediately so a following begin returns InvalidState, then defers the teardown body to a worker. If that worker cannot be created, the next user-thread end completes it.

Parameters:

releaseMemory – If true, also releases the Bluetooth controller memory. After this, begin() cannot reinitialize BLE without a full reboot.

bool isInitialized() const

Check whether the BLE stack has been initialized.

Returns:

true if begin() completed successfully and end() has not yet cleared the public session. A deferred callback-context end() may still report true until teardown runs (the worker, or a later user-thread end if the worker could not be created); begin returns InvalidState for that window.

bool isEnding() const

Whether shutdown has claimed the current BLE session.

Primarily used by retained subsystem handles to reject native operations during callback-deferred teardown.

explicit operator bool() const

Boolean conversion — equivalent to isInitialized().

Returns:

true if BLE is initialized and ready.

BTAddress getAddress() const

Get the local Bluetooth address currently in use.

Returns:

The device’s BTAddress (public or random, depending on own-address type).

String getDeviceName() const

Get the device name that was set via begin().

Returns:

The current device name as a String.

BTStatus setOwnAddressType(BTAddress::Type type)

Set the own-address type used for advertising and connections.

Parameters:

type – Address type (Public, Random, RPA with public fallback, etc.).

Returns:

BTStatus indicating success or failure.

BTAddress::Type getOwnAddressType() const

Get the currently configured own-address type.

Returns:

The BTAddress::Type in use.

bool getOwnRandomAddress(uint8_t out[6]) const

Random device address programmed by setOwnAddressType(BTAddress::Random).

BTStatus setOwnAddress(const BTAddress &addr)

Override the local Bluetooth address.

Note

Must be called before begin(), or the stack may ignore the change.

Parameters:

addr – The address to use.

Returns:

BTStatus indicating success or failure.

BLEServer createServer()

Create (or retrieve) the GATT server singleton.

The first call allocates internal state; subsequent calls return a handle to the same underlying server.

Returns:

A BLEServer handle. Check with operator bool() for validity.

BLEScan getScan()

Get the BLE scan singleton.

Returns:

A BLEScan handle used to configure and start scanning.

BLEAdvertising getAdvertising()

Get the advertising singleton.

Returns:

A BLEAdvertising handle used to configure and start advertising.

BLESecurity getSecurity()

Get the security/pairing singleton.

Returns:

A BLESecurity handle for configuring pairing and bonding.

BLEAudio getAudioController()

Get the LE Audio controller handle (GAF entry point).

Declared in the core so a sketch that does not use LE Audio never compiles the audio engine. Include <BLEAudio.h> from the separate BLEAudio library before using the returned handle; without it BLEAudio is only forward-declared here.

The first call allocates the single engine-backed implementation; subsequent calls return a handle to the same instance. Only valid after begin(). Named “controller” because it manages the audio subsystem &#8212; it does not itself carry audio data.

Returns:

A BLEAudio handle. Check with operator bool() for validity.

BLEIso getIsoController()

Get the ISO transport controller handle (raw CIS/BIS entry point).

The first call allocates the single transport-backed implementation; subsequent calls return a handle to the same instance. Only valid after begin().

Returns:

A BLEIso handle. Check with operator bool() for validity.

BLEClient createClient()

Create a new GATT client instance.

Each call allocates a new client. The caller is responsible for connecting and eventually disconnecting.

Returns:

A BLEClient handle. Check with operator bool() for validity.

uint16_t getConnHandle(const BTAddress &peerAddress) const

Find the connection handle for a connected peer.

This is the same handle reported by BLEClient::getHandle() and BLEConnInfo::getHandle(), and the one connection-scoped APIs take. Accepts the peer’s OTA address (the one reported by BLEConnInfo::getAddress()); NimBLE also matches the resolved identity address.

Parameters:

peerAddress – Peer address.

Returns:

The connection handle, or 0xFFFF if the peer is not connected.

std::vector<uint16_t> getConnHandles(const BTAddress &peerAddress) const

Find the live connection handle for a connected peer.

Returns one handle per ACL. Bluedroid may have several GATTC client objects and a GATTS server link on one ACL; the first client handle is returned, otherwise the server handle. Use the owning handle when you need a specific GATT application’s connection.

Parameters:

peerAddress – Peer address.

Returns:

Unique handles in client-before-server order; empty when the peer is not connected.

std::vector<BLEConnInfo> getConnections(const BTAddress &peerAddress) const

Find the connection descriptor for a connected peer.

Returns one descriptor per ACL on both backends. A local device can be both GATT client and server on that ACL; the descriptor’s GAP role is the link role, and the handle is the application connection that owns the link. Use the owning BLEClient/BLEServer handle for a specific GATT application.

Note

PHY/RSSI are normalized as in getConnInfo(const BTAddress &).

Parameters:

peerAddress – Peer address.

Returns:

A valid descriptor, or an empty vector when the peer is not connected.

BLEConnInfo getConnInfo(const BTAddress &peerAddress) const

Find connection information for a connected peer.

Note

The address lookup normalizes the volatile fields: TX/RX PHY are reported as PHY_1M and RSSI as 0 on both backends. Use the owning BLEClient/BLEServer handle for live PHY/RSSI values.

Parameters:

peerAddress – Peer address (OTA, or the identity address on NimBLE).

Returns:

A valid BLEConnInfo snapshot, or an invalid one when the peer is not connected.

BLEL2CAPServer createL2CAPServer(uint16_t psm, uint16_t mtu = 512)

Create an L2CAP Connection-Oriented Channel server.

Listens for incoming L2CAP CoC connections on the given PSM.

Parameters:
  • psm – Protocol/Service Multiplexer value to listen on.

  • mtu – Maximum Transmission Unit for the channel (default 512).

Returns:

A BLEL2CAPServer handle.

BLEL2CAPChannel connectL2CAP(uint16_t connHandle, uint16_t psm, uint16_t mtu = 512)

Open an outgoing L2CAP CoC channel to a connected peer.

Parameters:
  • connHandle – BLE connection handle of the already-connected peer.

  • psm – Protocol/Service Multiplexer on the remote device.

  • mtu – Maximum Transmission Unit for the channel (default 512).

Returns:

A BLEL2CAPChannel handle for the new channel.

void setPower(int8_t txPowerDbm)

Set the BLE transmit power.

Note

No-op if the BLE stack has not been initialized. On hosted-HCI platforms (e.g. ESP32-P4) this is unsupported and logs a warning.

Parameters:

txPowerDbm – Transmit power in dBm. Quantized to the nearest supported level: -12, -9, -6, -3, 0, +3, +6, or +9 dBm.

int8_t getPower() const

Get the current BLE transmit power.

Note

On hosted-HCI platforms the power level is not queryable and this returns 0.

Returns:

Transmit power in dBm, or -128 if the stack is not initialized.

BTStatus setMTU(uint16_t mtu)

Set the preferred ATT MTU for future connections.

Note

Does not affect already-established connections.

Parameters:

mtu – Preferred MTU size (23–517).

Returns:

BTStatus indicating success or failure.

uint16_t getMTU() const

Get the configured preferred ATT MTU.

Returns:

The preferred MTU value.

bool getLocalIRK(uint8_t irk[16]) const

Copy the local Identity Resolving Key into the provided buffer.

Parameters:

irk – Output buffer of at least 16 bytes.

Returns:

true if the IRK was successfully retrieved.

String getLocalIRKString() const

Get the local IRK as a hex string.

Returns:

Hex-encoded IRK, or an empty string on failure.

String getLocalIRKBase64() const

Get the local IRK as a Base64-encoded string.

Returns:

Base64-encoded IRK, or an empty string on failure.

bool getPeerIRK(const BTAddress &peer, uint8_t irk[16]) const

Copy a bonded peer’s IRK into the provided buffer.

Parameters:
  • peer – Address of the bonded peer.

  • irk – Output buffer of at least 16 bytes.

Returns:

true if the IRK was found and copied.

String getPeerIRKString(const BTAddress &peer) const

Get a bonded peer’s IRK as a hex string.

Parameters:

peer – Address of the bonded peer.

Returns:

Hex-encoded IRK, or an empty string if not found.

String getPeerIRKBase64(const BTAddress &peer) const

Get a bonded peer’s IRK as a Base64-encoded string.

Parameters:

peer – Address of the bonded peer.

Returns:

Base64-encoded IRK, or an empty string if not found.

String getPeerIRKReverse(const BTAddress &peer) const

Get a bonded peer’s IRK as a byte-reversed hex string.

Useful for systems that expect the IRK in reverse byte order (e.g., some Home Assistant integrations).

Parameters:

peer – Address of the bonded peer.

Returns:

Reversed hex-encoded IRK, or an empty string if not found.

BTStatus setDefaultPhy(BLEPhy txPhy, BLEPhy rxPhy)

Set the default PHY preferences for new connections.

Parameters:
  • txPhy – Preferred transmit PHY (1M, 2M, or Coded).

  • rxPhy – Preferred receive PHY (1M, 2M, or Coded).

Returns:

BTStatus indicating success or failure.

BTStatus getDefaultPhy(BLEPhy &txPhy, BLEPhy &rxPhy) const

Get the current default PHY preferences.

Parameters:
  • txPhy – Output: current default transmit PHY.

  • rxPhy – Output: current default receive PHY.

Returns:

BTStatus indicating success or failure.

BTStatus whiteListAdd(const BTAddress &address)

Add a device address to the BLE whitelist.

Note

Blocks until the controller whitelist update completes.

Parameters:

address – The peer address to add.

Returns:

BTStatus indicating success or failure.

BTStatus whiteListRemove(const BTAddress &address)

Remove a device address from the BLE whitelist.

Note

Blocks until the controller whitelist update completes.

Parameters:

address – The peer address to remove.

Returns:

BTStatus indicating success or failure.

bool isOnWhiteList(const BTAddress &address) const

Check whether an address is on the whitelist.

Parameters:

address – The peer address to look up.

Returns:

true if the address is currently on the whitelist.

BTStatus startAdvertising()

Start advertising using the current advertising configuration.

Returns:

BTStatus indicating success or failure.

BTStatus stopAdvertising()

Stop advertising.

Returns:

BTStatus indicating success or failure.

Stack getStack() const

Get the Bluetooth stack in use at compile time.

Returns:

Stack::NimBLE or Stack::Bluedroid.

const char *getStackName() const

Get the Bluetooth stack name as a C-string.

Returns:

“NimBLE” or “Bluedroid”.

bool isHostedBLE() const

Check whether BLE is running over esp-hosted (e.g., on ESP32-P4).

Returns:

true if the BLE stack is hosted on a remote co-processor.

BTStatus setPins(int8_t clk, int8_t cmd, int8_t d0, int8_t d1, int8_t d2, int8_t d3, int8_t rst)

Configure the SDIO/SPI pins for the esp-hosted co-processor.

Note

Only relevant on chips that use esp-hosted for BLE (e.g., ESP32-P4). Must be called before begin().

Parameters:
  • clk – Clock pin.

  • cmd – Command pin.

  • d0 – Data line 0.

  • d1 – Data line 1.

  • d2 – Data line 2.

  • d3 – Data line 3.

  • rst – Reset pin.

Returns:

BTStatus indicating success or failure.

BTStatus setCustomGapHandler(RawEventHandler handler)

Register a custom handler for raw GAP events.

Parameters:

handler – Callback invoked for every GAP event from the stack.

Returns:

BTStatus indicating success or failure.

BTStatus setCustomGattcHandler(RawEventHandler handler)

Register a custom handler for raw GATT-client events.

Parameters:

handler – Callback invoked for every GATT-client event from the stack.

Returns:

BTStatus indicating success or failure.

BTStatus setCustomGattsHandler(RawEventHandler handler)

Register a custom handler for raw GATT-server events.

Parameters:

handler – Callback invoked for every GATT-server event from the stack.

Returns:

BTStatus indicating success or failure.

BLEAdvertisementData.h

class BLEAdvertisementData

Builder for raw BLE advertisement data payloads.

Constructs AD structures per Core Spec Vol 3, Part C, Section 11. By default a payload targets the 31-octet legacy advertising/scan-response limit; construct with BLEAdvertisementData(size_t) to build a larger extended-advertising payload. A field that would overflow the active limit is skipped with a warning. setName() falls back to a Shortened Local Name (0x08) when the full name does not fit. UUID and multi-byte values are emitted in little-endian wire order.

Public Functions

BLEAdvertisementData() = default

Construct a legacy (31-octet) advertisement payload.

explicit BLEAdvertisementData(size_t maxPayloadLen)

Construct an extended-advertising payload with a larger byte budget.

Parameters:

maxPayloadLen – Payload cap in bytes; clamped to [LEGACY_MAX_PAYLOAD, EXTENDED_MAX_PAYLOAD]. Use this only for data fed to the BLE5 setExt*/setPeriodicAdvData paths.

void setFlags(BLEAdvFlag flags)

Set the AD Flags field (typically GeneralDisc | BrEdrNotSupported).

Parameters:

flags – Bitmask of BLEAdvFlag values.

void addServiceUUID(const BLEUUID &uuid)

Add a service UUID to the Complete List of Service UUIDs field.

Parameters:

uuid – The service UUID to advertise.

void setPartialServices(const BLEUUID &uuid)

Set a Partial (Incomplete) List of Service UUIDs field.

Parameters:

uuid – The service UUID to advertise.

void setServiceData(const BLEUUID &uuid, const uint8_t *data, size_t len)

Set a Service Data field.

Parameters:
  • uuid – The service UUID this data belongs to.

  • data – Pointer to the service data payload.

  • len – Length of data in bytes.

void setManufacturerData(uint16_t companyId, const uint8_t *data, size_t len)

Set a Manufacturer Specific Data field.

Parameters:
  • companyId – The Bluetooth SIG-assigned company identifier.

  • data – Pointer to the manufacturer-specific payload (after the company ID).

  • len – Length of data in bytes.

void setName(const String &name, bool complete = true)

Set the local name field.

Parameters:
  • name – The device name string.

  • complete – If true, emits a Complete Local Name; if false, a Shortened Local Name.

void setBroadcastName(const String &name)

Set the Broadcast Name AD field (type 0x30, BAP/PBP).

Auracast UIs (Galaxy Listen, etc.) display this — not Complete Local Name. BAP requires 4–128 UTF-8 octets; shorter names are space-padded to 4.

void setAppearance(uint16_t appearance)

Set the Appearance field.

Parameters:

appearance – GAP appearance value (e.g., 0x0340 for Generic Remote Control).

void setPreferredParams(uint16_t minInterval, uint16_t maxInterval)

Set the Slave Connection Interval Range AD field (0x12).

Parameters:
  • minInterval – Minimum connection interval in units of 1.25 ms.

  • maxInterval – Maximum connection interval in units of 1.25 ms.

void setTxPower(int8_t txPower)

Set the TX Power Level field.

Parameters:

txPower – Transmit power in dBm.

void addRaw(const uint8_t *data, size_t len)

Append a raw AD structure to the payload.

Note

Rejected with a warning if it would push the payload past the active payload limit (31 octets by default; larger when constructed extended).

Parameters:
  • data – Pointer to a complete AD structure (length + type + value).

  • len – Total length of the AD structure in bytes.

void clear()

Clear all previously set AD structures.

const uint8_t *data() const

Get a pointer to the assembled advertisement payload.

Returns:

Pointer to the raw payload bytes.

size_t length() const

Get the total length of the assembled advertisement payload.

Returns:

Length in bytes.

Public Static Attributes

static size_t LEGACY_MAX_PAYLOAD = 31

Maximum AD bytes in a legacy advertising / scan-response PDU (Vol 6, Part B, §2.3.1.2).

static size_t EXTENDED_MAX_PAYLOAD = 1650

Maximum AD bytes the host can stage for one extended advertising set (Vol 4, Part E, §7.8.54).

enum class BLEAdvFlag : uint8_t

AD Flags &#8212; Core Spec Vol 3, Part C, Section 11.1.3.

Combine with bitwise OR: BLEAdvFlag::GeneralDisc | BLEAdvFlag::BrEdrNotSupported.

Values:

enumerator LimitedDisc

LE Limited Discoverable Mode.

enumerator GeneralDisc

LE General Discoverable Mode.

enumerator BrEdrNotSupported

BR/EDR Not Supported (BLE-only device).

inline BLEAdvFlag operator|(BLEAdvFlag a, BLEAdvFlag b)

BLEAdvertising.h

class BLEAdvertising

Unified BLE advertising class covering legacy, extended, and periodic advertising.

Legacy advertising is the simple default. BLE5 extended/periodic features are available with explicit opt-in and guarded by BLE5_SUPPORTED.

Public Types

using CompleteHandler = std::function<void(uint8_t instance)>

Callback invoked when an advertising instance completes (duration or maxEvents reached).

Param instance:

The advertising instance index that completed.

Public Functions

explicit operator bool() const

Check whether this handle references a valid advertising instance.

Returns:

true if the handle is backed by an initialized implementation, false otherwise.

void addServiceUUID(const BLEUUID &uuid)

Append a service UUID to the advertisement payload.

Note

Duplicates are not checked; the same UUID may be added more than once.

Parameters:

uuid – Service UUID to advertise.

void removeServiceUUID(const BLEUUID &uuid)

Remove a service UUID from the advertisement payload.

Note

Removes all occurrences of uuid.

Parameters:

uuid – Service UUID to remove.

void clearServiceUUIDs()

Remove all service UUIDs from the advertisement payload.

void setName(const String &name)

Set the local name included in the advertisement.

Note

The host stack keeps its own GAP name; the backend may copy this string for the AD data rather than querying the GAP name API at broadcast time, so do not assume other getters always match the on-air name byte-for-byte on every target.

Parameters:

name – Device name string. May be truncated to fit the payload.

void setScanResponse(bool enable)

Enable or disable sending a scan-response payload.

Parameters:

enable – If true, the stack will transmit scan-response data when queried.

void setType(BLEAdvType type)

Set the advertising PDU type.

Parameters:

type – Advertising type (connectable, scannable, etc.).

void setDirectedAddress(const BTAddress &address)

Set the peer address used as InitA in directed advertising PDUs.

Directed types (DirectedHighDuty, DirectedLowDuty, ConnectableDirected) require a non-zero address before start() (BT Core Spec Vol 6, Part B, §4.4.2.4). High-duty directed advertising is also limited to 1.28 s (§4.4.2.4.2). A zero address clears the stored peer.

Parameters:

address – Target initiator address (typically the central’s identity).

BTAddress getDirectedAddress() const

Peer address last passed to setDirectedAddress.

Returns:

The stored InitA, or a zero address if none was set.

void setInterval(uint16_t minMs, uint16_t maxMs)

Set the legacy advertising interval range.

Parameters:
  • minMs – Minimum advertising interval in milliseconds (converted to 0.625 ms units).

  • maxMs – Maximum advertising interval in milliseconds (converted to 0.625 ms units).

void setMinPreferred(uint16_t minPreferred)

Set the minimum preferred connection interval advertised to centrals.

Note

Emits Slave Connection Interval Range AD (0x12) when either bound is non-zero.

Parameters:

minPreferred – Minimum preferred interval value (in 1.25 ms units).

void setMaxPreferred(uint16_t maxPreferred)

Set the maximum preferred connection interval advertised to centrals.

Note

Emits Slave Connection Interval Range AD (0x12) when either bound is non-zero.

Parameters:

maxPreferred – Maximum preferred interval value (in 1.25 ms units).

void setTxPower(bool include)

Include or exclude the TX power level in the advertisement.

Parameters:

include – If true, the TX power level is added to the payload.

void setAppearance(uint16_t appearance)

Set the GAP appearance value in the advertisement.

Parameters:

appearance – 16-bit appearance value as defined by the Bluetooth SIG. Use the named BLE_APPEARANCE_* values from advertising/BLEAppearance.h, e.g. BLE_APPEARANCE_AUDIO_SINK_STANDALONE_SPEAKER.

void setScanFilter(bool scanRequestWhitelistOnly, bool connectWhitelistOnly)

Configure the scan-request and connect whitelist filters.

Parameters:
  • scanRequestWhitelistOnly – If true, only accept scan requests from whitelisted devices.

  • connectWhitelistOnly – If true, only accept connections from whitelisted devices.

void reset()

Reset all legacy advertising parameters to defaults.

void setAdvertisementData(const BLEAdvertisementData &data)

Replace the advertisement payload with custom data.

Parameters:

data – Pre-built advertisement data to use.

void setScanResponseData(const BLEAdvertisementData &data)

Replace the scan-response payload with custom data.

Parameters:

data – Pre-built scan-response data to use.

BTStatus start(uint32_t durationMs = 0)

Start legacy advertising.

Parameters:

durationMs – Duration in milliseconds. 0 = advertise indefinitely. Finite values that exceed the HCI 16-bit 10 ms unit field (~655.35 s) return InvalidParam. High-duty directed advertising is limited to 1.28 s. Directed types with a zero setDirectedAddress also return InvalidParam.

Returns:

BTStatus indicating success or error.

BTStatus stop()

Stop legacy advertising.

Returns:

BTStatus indicating success or error.

bool isAdvertising() const

Check whether any advertising set is currently active.

True when the legacy set is running, or when any extended advertising instance is running. stop() still stops only the legacy set; use stopExtended() for a specific extended instance.

Returns:

true if advertising is running, false otherwise.

void setExtType(uint8_t instance, BLEAdvType type)

Set the PDU type for an extended advertising instance.

Parameters:
  • instance – Advertising instance index.

  • type – Advertising type (connectable, scannable, etc.).

void setExtPhy(uint8_t instance, BLEPhy primaryPhy, BLEPhy secondaryPhy)

Set the primary and secondary PHY for an extended advertising instance.

Parameters:
  • instance – Advertising instance index.

  • primaryPhy – Primary advertising PHY (used for initial advertisement).

  • secondaryPhy – Secondary (aux) advertising PHY.

void setExtTxPower(uint8_t instance, int8_t txPower)

Set the TX power for an extended advertising instance.

Parameters:
  • instance – Advertising instance index.

  • txPower – Transmit power in dBm (127 = no preference, use controller default).

void setExtInterval(uint8_t instance, uint16_t minInterval, uint16_t maxInterval)

Set the advertising interval range for an extended advertising instance.

Note

Unlike setInterval(), these arguments are already in 0.625 ms units.

Parameters:
  • instance – Advertising instance index.

  • minInterval – Minimum advertising interval in controller units (0.625 ms each), not milliseconds.

  • maxInterval – Maximum advertising interval in controller units (0.625 ms each), not milliseconds.

void setExtChannelMap(uint8_t instance, uint8_t channelMap)

Set the channel map for an extended advertising instance.

Parameters:
  • instance – Advertising instance index.

  • channelMap – Bitmask of advertising channels: bit 0 = ch 37, bit 1 = ch 38, bit 2 = ch 39.

void setExtSID(uint8_t instance, uint8_t sid)

Set the Advertising Set Identifier (SID) for an extended advertising instance.

Parameters:
  • instance – Advertising instance index.

  • sid – SID value (used by scanners for filtering and periodic sync).

void setExtAnonymous(uint8_t instance, bool anonymous)

Enable or disable anonymous advertising (omit advertiser address).

Parameters:
  • instance – Advertising instance index.

  • anonymous – If true, the advertiser address is omitted from PDUs.

void setExtIncludeTxPower(uint8_t instance, bool include)

Include or exclude TX power level in the extended advertising header.

Parameters:
  • instance – Advertising instance index.

  • include – If true, TX power is included in the extended header.

void setExtScanReqNotify(uint8_t instance, bool enable)

Enable or disable scan request notifications for an extended advertising instance.

Parameters:
  • instance – Advertising instance index.

  • enable – If true, the stack notifies on incoming scan requests.

BTStatus setExtAdvertisementData(uint8_t instance, const BLEAdvertisementData &data)

Set the advertisement data for an extended advertising instance.

Parameters:
  • instance – Advertising instance index.

  • data – Advertisement payload.

Returns:

BTStatus indicating success or error.

BTStatus setExtScanResponseData(uint8_t instance, const BLEAdvertisementData &data)

Set the scan-response data for an extended advertising instance.

Parameters:
  • instance – Advertising instance index.

  • data – Scan-response payload.

Returns:

BTStatus indicating success or error.

BTStatus setExtInstanceAddress(uint8_t instance, const BTAddress &addr)

Set a random address for an extended advertising instance.

Parameters:
  • instance – Advertising instance index.

  • addr – Address to assign to the instance.

Returns:

BTStatus indicating success or error.

BTStatus startExtended(uint8_t instance, uint32_t durationMs = 0, uint8_t maxEvents = 0)

Start an extended advertising instance.

Parameters:
  • instance – Advertising instance index.

  • durationMs – Duration in milliseconds. 0 = advertise indefinitely.

  • maxEvents – Maximum number of advertising events. 0 = no limit.

Returns:

BTStatus indicating success or error.

BTStatus stopExtended(uint8_t instance)

Stop an extended advertising instance.

Parameters:

instance – Advertising instance index.

Returns:

BTStatus indicating success or error.

BTStatus removeExtended(uint8_t instance)

Remove an extended advertising instance and free its resources.

Parameters:

instance – Advertising instance index to remove.

Returns:

BTStatus indicating success or error.

BTStatus clearExtended()

Remove all extended advertising instances.

Blocks until the controller has finished the clear. Fails and leaves advertising flags unchanged if any set is still enabled (stop first). After BLE.end(), returns OK without a native call (stop-like).

Returns:

BTStatus indicating success or error.

void setPeriodicAdvInterval(uint8_t instance, uint16_t minInterval, uint16_t maxInterval)

Set the periodic advertising interval for an extended instance.

Parameters:
  • instance – Extended advertising instance to attach to.

  • minInterval – Minimum periodic interval (1.25 ms units).

  • maxInterval – Maximum periodic interval (1.25 ms units).

void setPeriodicAdvTxPower(uint8_t instance, bool include)

Include or exclude TX power in periodic advertising PDUs.

Parameters:
  • instance – Extended advertising instance to attach to.

  • include – If true, TX power is included in periodic PDUs.

BTStatus setPeriodicAdvData(uint8_t instance, const BLEAdvertisementData &data)

Set the payload for periodic advertising.

Parameters:
  • instance – Extended advertising instance index.

  • data – Periodic advertising payload.

Returns:

BTStatus indicating success or error.

BTStatus startPeriodicAdv(uint8_t instance)

Start periodic advertising on an extended instance.

Parameters:

instance – Extended advertising instance index.

Returns:

BTStatus indicating success or error.

BTStatus stopPeriodicAdv(uint8_t instance)

Stop periodic advertising on an extended instance.

Parameters:

instance – Extended advertising instance index.

Returns:

BTStatus indicating success or error.

void onComplete(CompleteHandler handler)

Register a handler for advertising completion events.

Parameters:

handler – The handler to invoke, or nullptr to clear.

void resetCallbacks()

Remove all registered advertising callbacks.

BLEBeacon.h

class BLEBeacon

Apple iBeacon helper.

Builds/parses iBeacon advertisement data. The manufacturer-specific data follows the Apple iBeacon format (company ID 0x004C, type 0x0215).

Public Functions

BLEBeacon()

Construct an iBeacon with default values (Apple company ID 0x004C, signal power -59 dBm).

BLEUUID getProximityUUID() const

Get the 128-bit Proximity UUID.

Returns:

The proximity UUID that identifies the beacon group.

void setProximityUUID(const BLEUUID &uuid)

Set the 128-bit Proximity UUID.

Parameters:

uuid – The proximity UUID identifying this beacon group (promoted to 128-bit via to128()).

uint16_t getMajor() const

Get the major identifier value.

Returns:

The 16-bit major value.

void setMajor(uint16_t major)

Set the major identifier value.

Parameters:

major – 16-bit major value for grouping beacons.

uint16_t getMinor() const

Get the minor identifier value.

Returns:

The 16-bit minor value.

void setMinor(uint16_t minor)

Set the minor identifier value.

Parameters:

minor – 16-bit minor value for identifying individual beacons.

uint16_t getManufacturerId() const

Get the manufacturer ID (company code).

Returns:

The 16-bit manufacturer ID (default: 0x004C for Apple).

void setManufacturerId(uint16_t id)

Set the manufacturer ID (company code).

Parameters:

id – 16-bit Bluetooth SIG company identifier.

int8_t getSignalPower() const

Get the measured signal power at 1 meter.

Returns:

Calibrated TX power in dBm.

void setSignalPower(int8_t power)

Set the measured signal power at 1 meter.

Parameters:

power – Calibrated TX power in dBm (typically -40 to -80).

BLEAdvertisementData getAdvertisementData() const

Build a BLEAdvertisementData payload from the current iBeacon fields.

Returns:

Advertisement data ready to pass to BLEAdvertising.

void setFromPayload(const uint8_t *payload, size_t len)

Parse iBeacon fields from a raw manufacturer-specific payload.

Note

No-op unless the payload contains a valid 23-byte iBeacon body starting with 0x02 0x15.

Parameters:
  • payload – Pointer to the manufacturer-specific data bytes (either 25+ bytes including the 2-byte company ID, or 23+ bytes starting at the iBeacon type/length header 0x02 0x15).

  • len – Length of the payload in bytes.

BLEEddystone.h

class BLEEddystoneTLM

Eddystone TLM (telemetry) frame builder/parser.

Public Functions

BLEEddystoneTLM()

Construct an Eddystone-TLM frame with zeroed telemetry values.

void setBatteryVoltage(uint16_t millivolts)

Set the battery voltage.

Parameters:

millivolts – Battery voltage in millivolts (0 = not supported).

uint16_t getBatteryVoltage() const

Get the battery voltage.

Returns:

Battery voltage in millivolts.

void setTemperature(float celsius)

Set the beacon temperature.

Parameters:

celsius – Temperature in degrees Celsius.

float getTemperature() const

Get the beacon temperature.

Returns:

Temperature in degrees Celsius.

void setAdvertisingCount(uint32_t count)

Set the advertising PDU count since power-on or reboot.

Parameters:

count – Number of advertisement frames sent.

uint32_t getAdvertisingCount() const

Get the advertising PDU count.

Returns:

Number of advertisement frames sent since last reboot.

void setUptime(uint32_t deciseconds)

Set the time since power-on or reboot.

Parameters:

deciseconds – Uptime in units of 0.1 seconds.

uint32_t getUptime() const

Get the time since power-on or reboot.

Returns:

Uptime in units of 0.1 seconds.

BLEAdvertisementData getAdvertisementData() const

Build a BLEAdvertisementData payload from the current TLM fields.

Returns:

Advertisement data ready to pass to BLEAdvertising.

void setFromServiceData(const uint8_t *data, size_t len)

Parse Eddystone-TLM fields from raw service data.

Note

No-op unless len >= 14 and the frame type is 0x20 (TLM). Multi-byte fields are decoded from big-endian wire format.

Parameters:
  • data – Pointer to the Eddystone service data bytes (byte 0 = frame type).

  • len – Length of the service data in bytes.

String toString() const

Get a human-readable summary of the TLM frame.

Returns:

Formatted string with voltage, temperature, count, and uptime.

Public Static Functions

static BLEUUID serviceUUID()

Get the Eddystone service UUID (0xFEAA).

Returns:

The 16-bit Eddystone service UUID.

class BLEEddystoneURL

Eddystone URL frame builder/parser.

Public Functions

BLEEddystoneURL()

Construct an Eddystone-URL frame with default TX power (-20 dBm).

void setURL(const String &url)

Set the URL to advertise.

Parameters:

url – Full URL string (e.g. “https://example.com”). Prefix and known suffixes are automatically compressed per the Eddystone-URL spec.

String getURL() const

Get the currently configured URL.

Returns:

The decoded URL string.

void setTxPower(int8_t txPower)

Set the calibrated TX power at 0 meters.

Parameters:

txPower – TX power in dBm.

int8_t getTxPower() const

Get the calibrated TX power at 0 meters.

Returns:

TX power in dBm.

BLEAdvertisementData getAdvertisementData() const

Build a BLEAdvertisementData payload from the current Eddystone-URL fields.

Returns:

Advertisement data ready to pass to BLEAdvertising.

void setFromServiceData(const uint8_t *data, size_t len)

Parse Eddystone-URL fields from raw service data.

Note

No-op unless len >= 3 and the frame type is 0x10 (URL). Suffix codes < 14 are expanded; other bytes are treated as literal ASCII.

Parameters:
  • data – Pointer to the Eddystone service data bytes (byte 0 = frame type).

  • len – Length of the service data in bytes.

Public Static Functions

static BLEUUID serviceUUID()

Get the Eddystone service UUID (0xFEAA).

Returns:

The 16-bit Eddystone service UUID.

BLEClient.h

class BLEClient

GATT client &#8212; multi-instance, connect to remote peripherals.

Create via BLE.createClient(). Each instance manages one connection. Multiple BLEClient instances can coexist for multi-connection use cases.

Callback threading: client callbacks (onConnect, onDisconnect, notify callbacks, etc.) execute on the BLE stack task. They are invoked outside the client mutex and must not block for extended periods.

GATT operation limitation: only one read or write can be in-flight per client at a time (Bluedroid delivers completions without a per-operation token). Concurrent reads/writes from multiple tasks will collide.

Public Types

using ConnectHandler = std::function<void(BLEClient &client, const BLEConnInfo &conn)>

Callback invoked when a connection is established.

Param client:

The BLEClient that connected.

Param conn:

Connection information for the new link.

using DisconnectHandler = std::function<void(BLEClient &client, const BLEConnInfo &conn, uint8_t reason)>

Callback invoked when a connection is terminated.

Param client:

The BLEClient that was disconnected.

Param conn:

Connection information for the terminated link.

Param reason:

BLE HCI disconnect reason code.

using ConnectFailHandler = std::function<void(BLEClient &client, int reason)>

Callback invoked when a connection attempt fails.

Param client:

The BLEClient whose connection attempt failed.

Param reason:

Backend-specific error code.

using MtuChangedHandler = std::function<void(BLEClient &client, const BLEConnInfo &conn, uint16_t mtu)>

Callback invoked when the ATT MTU changes after negotiation.

Param client:

The BLEClient whose MTU changed.

Param conn:

Connection information for the link.

Param mtu:

The new effective MTU size.

using ConnParamsReqHandler = std::function<bool(BLEClient &client, const BLEConnParams &params)>

Callback invoked when the remote peer requests a connection parameter update.

Param client:

The BLEClient receiving the request.

Param params:

The requested connection parameters.

Return:

true to accept the parameters; false to reject.

using IdentityHandler = std::function<void(BLEClient &client, const BLEConnInfo &conn)>

Callback invoked when the peer’s identity is resolved (after bonding/pairing).

Param client:

The BLEClient whose peer identity was resolved.

Param conn:

Updated connection information including the resolved address.

Public Functions

explicit operator bool() const

Boolean conversion — true if this handle references a valid client.

Returns:

true if the underlying implementation exists.

BTStatus connect(const BTAddress &address, uint32_t timeoutMs = 5000)

Connect to a peripheral by address (blocking).

Blocks the calling task until the connection completes or the timeout expires. Uses the default 1M PHY.

Parameters:
  • address – Address of the remote peripheral.

  • timeoutMs – Maximum time to wait for the connection (ms).

Returns:

BTStatus indicating success or the connection error.

BTStatus connect(const BLEAdvertisedDevice &device, uint32_t timeoutMs = 5000)

Connect to a previously scanned device (blocking).

Parameters:
  • device – An advertised device obtained from a BLEScan.

  • timeoutMs – Maximum time to wait for the connection (ms).

Returns:

BTStatus indicating success or the connection error.

BTStatus connect(const BTAddress &address, BLEPhy phy, uint32_t timeoutMs = 5000)

Connect to a peripheral by address on a specific PHY (blocking).

Parameters:
  • address – Address of the remote peripheral.

  • phy – PHY to use for the connection (1M, 2M, or Coded).

  • timeoutMs – Maximum time to wait for the connection (ms).

Returns:

BTStatus indicating success or the connection error.

BTStatus connect(const BLEAdvertisedDevice &device, BLEPhy phy, uint32_t timeoutMs = 5000)

Connect to a previously scanned device on a specific PHY (blocking).

Parameters:
  • device – An advertised device obtained from a BLEScan.

  • phy – PHY to use for the connection (1M, 2M, or Coded).

  • timeoutMs – Maximum time to wait for the connection (ms).

Returns:

BTStatus indicating success or the connection error.

BTStatus connectAsync(const BTAddress &address, BLEPhy phy = BLEPhy::PHY_1M)

Initiate connection by address without blocking.

The result is delivered via the ConnectHandler or ConnectFailHandler callbacks.

Parameters:
  • address – Address of the remote peripheral.

  • phy – PHY to use for the connection (default 1M).

Returns:

BTStatus indicating whether the connect request was accepted.

BTStatus connectAsync(const BLEAdvertisedDevice &device, BLEPhy phy = BLEPhy::PHY_1M)

Initiate connection to a scanned device without blocking.

Parameters:
  • device – An advertised device obtained from a BLEScan.

  • phy – PHY to use for the connection (default 1M).

Returns:

BTStatus indicating whether the connect request was accepted.

BTStatus cancelConnect()

Cancel a pending connection attempt.

Returns:

BTStatus indicating success or failure.

BTStatus disconnect()

Disconnect from the remote peripheral.

Returns:

BTStatus indicating success or failure.

bool isConnected() const

Check whether this client is currently connected.

Returns:

true if connected.

BTStatus secureConnection()

Initiate or upgrade security on the current connection (pairing/bonding).

Returns:

BTStatus indicating success or failure.

BLERemoteService getService(const BLEUUID &uuid) const

Get a remote service by UUID from the discovered service cache.

Note

Call discoverServices() first, or this may return an invalid handle.

Parameters:

uuid – UUID of the service to look up.

Returns:

A BLERemoteService handle. Check with operator bool() for validity.

std::vector<BLERemoteService> getServices() const

Get all discovered remote services.

Returns:

A vector of BLERemoteService handles (empty if none discovered).

BTStatus discoverServices()

Perform GATT service discovery on the connected peripheral.

Populates the internal service cache used by getService() and getServices().

Returns:

BTStatus indicating success or failure.

String getValue(const BLEUUID &serviceUUID, const BLEUUID &charUUID)

Read a characteristic value by service and characteristic UUID.

Convenience wrapper that locates the service and characteristic, then reads.

Note

getService() may run service discovery if the cache is empty, so the first call can block longer than a simple read.

Parameters:
  • serviceUUID – UUID of the containing service.

  • charUUID – UUID of the characteristic to read.

Returns:

The characteristic value as a String, or an empty String on failure.

BTStatus setValue(const BLEUUID &serviceUUID, const BLEUUID &charUUID, const String &value)

Write a characteristic value by service and characteristic UUID.

Note

Same lazy-discovery behavior as getValue().

Parameters:
  • serviceUUID – UUID of the containing service.

  • charUUID – UUID of the characteristic to write.

  • value – The value to write.

Returns:

BTStatus::NotFound if the service is not in the discovered cache, otherwise the status of the underlying write.

void onConnect(ConnectHandler handler)

Set the callback invoked when a connection is established.

Parameters:

handler – ConnectHandler callback, or nullptr to clear.

void onDisconnect(DisconnectHandler handler)

Set the callback invoked when a connection is terminated.

Parameters:

handler – DisconnectHandler callback, or nullptr to clear.

void onConnectFail(ConnectFailHandler handler)

Set the callback invoked when a connection attempt fails.

Parameters:

handler – ConnectFailHandler callback, or nullptr to clear.

void onMtuChanged(MtuChangedHandler handler)

Set the callback invoked when the ATT MTU changes.

Parameters:

handler – MtuChangedHandler callback, or nullptr to clear.

void onConnParamsUpdateRequest(ConnParamsReqHandler handler)

Set the callback for remote connection-parameter update requests.

Note

Backend asymmetry: NimBLE surfaces the peer’s L2CAP Connection Parameter Update Request and lets this handler accept or reject it before it is applied. Bluedroid has no pre-acceptance hook &#8212; the controller applies the update and only reports completion, so on Bluedroid this handler is never invoked and its return value has no effect. Register it for NimBLE gating.

Parameters:

handler – ConnParamsReqHandler callback, or nullptr to clear.

void onIdentity(IdentityHandler handler)

Set the callback invoked when the peer’s identity is resolved.

Parameters:

handler – IdentityHandler callback, or nullptr to clear.

void resetCallbacks()

Remove all registered callbacks.

void setMTU(uint16_t mtu)

Set the preferred ATT MTU to request during MTU exchange.

Parameters:

mtu – Preferred MTU size.

uint16_t getMTU() const

Get the current effective ATT MTU for this connection.

Returns:

The negotiated MTU, or the default (23) if not yet exchanged.

int8_t getRSSI() const

Read the RSSI of the current connection.

Returns:

RSSI in dBm, or 0 if not connected.

BTAddress getPeerAddress() const

Get the address of the connected peer.

Returns:

The peer’s BTAddress.

uint16_t getHandle() const

Get the BLE connection handle for this link.

Returns:

The connection handle, or 0 if not connected.

BLEConnInfo getConnInfo() const

Get detailed connection information.

Returns:

A BLEConnInfo snapshot of the current connection state.

BTStatus updateConnParams(const BLEConnParams &params)

Request a connection parameter update.

Parameters:

params – The desired connection parameters.

Returns:

BTStatus indicating success or failure.

BTStatus setPhy(BLEPhy txPhy, BLEPhy rxPhy)

Set the preferred PHY for this connection.

Parameters:
  • txPhy – Preferred transmit PHY (1M, 2M, or Coded).

  • rxPhy – Preferred receive PHY (1M, 2M, or Coded).

Returns:

BTStatus indicating success or failure.

BTStatus getPhy(BLEPhy &txPhy, BLEPhy &rxPhy) const

Get the active PHY for this connection.

Parameters:
  • txPhy – Output: current transmit PHY.

  • rxPhy – Output: current receive PHY.

Returns:

BTStatus indicating success or failure.

BTStatus setDataLen(uint16_t txOctets, uint16_t txTime)

Set the Data Length Extension parameters for this connection.

Parameters:
  • txOctets – Maximum number of payload octets per TX PDU (27–251).

  • txTime – Maximum TX time per PDU in microseconds (328–17040).

Returns:

BTStatus indicating success or failure.

String toString() const

Get a human-readable description of this client.

Returns:

A String with the peer address and connection state.

BLECharacteristic.h

class BLECharacteristic

GATT Characteristic handle.

Lightweight shared handle wrapping a BLECharacteristic::Impl. Create via service.createCharacteristic(uuid, properties).

Public Types

enum NotifyStatus

Status codes for onStatus() after notify() or indicate().

Values:

enumerator SUCCESS_INDICATE

Indication sent and confirmed.

enumerator SUCCESS_NOTIFY

Notification sent.

enumerator ERROR_INDICATE_DISABLED

Target client has not enabled indications.

enumerator ERROR_NOTIFY_DISABLED

Target client has not enabled notifications.

enumerator ERROR_GATT

Low-level GATT error.

enumerator ERROR_NO_CLIENT

No client connected, target handle invalid, or the link dropped before delivery.

enumerator ERROR_NO_SUBSCRIBER

Clients are connected but none is subscribed.

enumerator ERROR_INDICATE_TIMEOUT

Indication not confirmed within 30 s (the link is then closed).

enumerator ERROR_INDICATE_FAILURE

Indication could not be sent, was rejected, or the queue was full.

using ReadHandler = std::function<void(BLECharacteristic &chr, const BLEConnInfo &conn)>

Callback invoked when a client reads this characteristic.

Note

Invoked once per client read. A long read (value larger than MTU - 1) is served from the value set here; the follow-up Read Blob requests do not invoke the handler again. The library keeps a per-connection copy of that value until the read completes, so a concurrent setValue() cannot mix two values in one long read.

Note

The mutable chr reference is borrowed for the callback. Copy the handle to retain it; do not retain a pointer or reference to the callback parameter itself. This rule applies to every handler below.

Param chr:

The characteristic being read. Calling chr.setValue() here sets the value returned in this read response.

Param conn:

Information about the connected client.

using WriteHandler = std::function<void(BLECharacteristic &chr, const BLEConnInfo &conn)>

Callback invoked when a client writes to this characteristic.

Param chr:

The characteristic being written (value already updated).

Param conn:

Information about the connected client.

using NotifyHandler = std::function<void(BLECharacteristic &chr)>

Callback invoked once per notify() / indicate() call, right before the payload is built, when there is at least one recipient.

Param chr:

The characteristic about to be sent. When notify() / indicate() was called without a payload, a value set here with chr.setValue() is the one sent to every recipient.

using SubscribeHandler = std::function<void(BLECharacteristic &chr, const BLEConnInfo &conn, uint16_t subValue)>

Callback invoked when a client subscribes to or unsubscribes from notifications/indications (CCCD write).

Param chr:

The characteristic whose subscription state changed.

Param conn:

Information about the connected client.

Param subValue:

Bitmask: bit 0 = notifications, bit 1 = indications. 0 means the client unsubscribed.

using StatusHandler = std::function<void(BLECharacteristic &chr, NotifyStatus status, uint32_t code)>

Callback invoked with the delivery status of a notification or indication.

Note

May run on the calling task (NimBLE reports notification results before notify() returns) or on the BLE stack task.

Param chr:

The characteristic that sent the notification/indication.

Param status:

Outcome of the operation: SUCCESS_NOTIFY once a notification is sent, SUCCESS_INDICATE once the client confirms an indication, an ERROR_* value otherwise. A broadcast notify() / indicate() with no recipient reports ERROR_NO_CLIENT (nobody connected) or ERROR_NO_SUBSCRIBER (nobody subscribed); the per-connection overloads report ERROR_NO_CLIENT or ERROR_NOTIFY_DISABLED / ERROR_INDICATE_DISABLED.

Param code:

Backend-specific error code (0 on success).

Public Functions

explicit operator bool() const

Check whether this handle refers to a valid characteristic.

Returns:

true if the handle is backed by a live Impl, false otherwise.

void onRead(ReadHandler handler)

Register a callback invoked when a client reads this characteristic.

Parameters:

handler – The read callback, or nullptr to clear.

void onWrite(WriteHandler handler)

Register a callback invoked when a client writes to this characteristic.

Note

On NimBLE, the stack typically sends the ATT write response after this handler returns; keep the callback short so peers are not stalled.

Parameters:

handler – The write callback, or nullptr to clear.

void onNotify(NotifyHandler handler)

Register a callback invoked once per notify() / indicate() call, before sending.

Parameters:

handler – The notify callback, or nullptr to clear.

void onSubscribe(SubscribeHandler handler)

Register a callback invoked when a client subscribes or unsubscribes.

Parameters:

handler – The subscribe callback, or nullptr to clear.

void onStatus(StatusHandler handler)

Register a callback invoked with notification/indication delivery status.

Parameters:

handler – The status callback, or nullptr to clear.

void resetCallbacks()

Remove all previously registered callbacks from this characteristic.

void setValue(const uint8_t *data, size_t length)

Set the characteristic value from a raw byte buffer.

Note

Thread-safe: the internal value buffer is guarded by a mutex. The convenience overloads store their argument in host (little-endian) byte order with no endian conversion; the String overload copies the raw bytes and does not store a null terminator.

Parameters:
  • data – Pointer to the data bytes.

  • length – Number of bytes to copy.

template<typename T>
inline void setValue(const T &value)

Set the characteristic value from an arbitrary trivially-copyable type.

Template Parameters:

T – A trivially-copyable type.

Parameters:

value – The value to store (copied byte-for-byte).

const uint8_t *getValue(size_t *length = nullptr) const

Get a pointer to the raw characteristic value.

Note

Thread-safe. The returned pointer is invalidated by a concurrent setValue().

Parameters:

length – If non-null, receives the length of the value in bytes (0 when invalid or empty).

Returns:

Pointer to the internal value buffer, or nullptr if the handle is invalid or the value is empty.

String getStringValue() const

Get the characteristic value as an Arduino String.

Returns:

The value interpreted as a UTF-8 string.

template<typename T>
inline T getValue() const

Get the characteristic value reinterpreted as type T.

Template Parameters:

T – A trivially-copyable type to reinterpret the value as.

Returns:

The value, or a value-initialized T if the stored data is shorter than sizeof(T).

BTStatus notify(const uint8_t *data = nullptr, size_t length = 0)

Send a notification to all clients that enabled notifications.

Parameters:
  • data – Optional payload. If nullptr, the current stored value is sent.

  • length – Number of bytes in data (ignored when data is nullptr).

Returns:

BTStatus::OK when the call was accepted, including when there is no recipient (reported through onStatus()); per-client delivery results are reported through onStatus().

BTStatus notify(uint16_t connHandle, const uint8_t *data = nullptr, size_t length = 0)

Send a notification to a specific client.

Parameters:
  • connHandle – Connection handle of the target client.

  • data – Optional payload. If nullptr, the current stored value is sent.

  • length – Number of bytes in data (ignored when data is nullptr).

Returns:

BTStatus::OK if sent, BTStatus::NotConnected if connHandle is not connected, BTStatus::InvalidState if that client has not enabled notifications, or another error status.

BTStatus indicate(const uint8_t *data = nullptr, size_t length = 0)

Send an indication to all clients that enabled indications.

Note

Does not block. ATT allows one unconfirmed indication per client, so an indication sent while another is awaiting confirmation is queued behind it (1 in-flight + up to 8 queued per client, 9 accepted in total before BTStatus::Busy) and sent in order. onStatus() reports SUCCESS_INDICATE once each one is confirmed. An indication the stack refuses because it is still waiting on one it sent itself (such as Service Changed) is retried until the ATT transaction timeout (30 s) passes.

Parameters:
  • data – Optional payload. If nullptr, the current stored value is sent.

  • length – Number of bytes in data (ignored when data is nullptr).

Returns:

BTStatus::OK when every recipient accepted or queued the call (including when there is no recipient), or BTStatus::Busy if any client’s queue is full; outcomes are reported through onStatus().

BTStatus indicate(uint16_t connHandle, const uint8_t *data = nullptr, size_t length = 0)

Send an indication to a specific client.

Note

Queued like the broadcast overload.

Parameters:
  • connHandle – Connection handle of the target client.

  • data – Optional payload. If nullptr, the current stored value is sent.

  • length – Number of bytes in data (ignored when data is nullptr).

Returns:

BTStatus::OK if sent or queued, BTStatus::NotConnected if connHandle is not connected, BTStatus::InvalidState if that client has not enabled indications, BTStatus::Busy if its queue is full, or another error status.

BLEProperty getProperties() const

Get the GATT properties of this characteristic.

Returns:

Bitmask of BLEProperty flags (Read, Write, Notify, etc.).

void setPermissions(BLEPermission permissions)

Set the ATT permissions for this characteristic value.

Parameters:

permissions – Bitmask of BLEPermission flags.

BLEPermission getPermissions() const

Get the ATT permissions for this characteristic value.

Returns:

Bitmask of BLEPermission flags.

BLEDescriptor createDescriptor(const BLEUUID &uuid, BLEPermission perms = BLEPermission::ReadOpen, size_t maxLen = 100)

Create and add a new descriptor to this characteristic.

Parameters:
  • uuid – UUID of the descriptor.

  • perms – ATT permissions for the descriptor.

  • maxLen – Maximum value length in bytes.

Returns:

Handle to the newly created descriptor.

BLEDescriptor getDescriptor(const BLEUUID &uuid) const

Find a descriptor by UUID.

Parameters:

uuid – UUID to search for.

Returns:

Handle to the descriptor, or an invalid handle if not found.

std::vector<BLEDescriptor> getDescriptors() const

Get all descriptors attached to this characteristic.

Returns:

Vector of descriptor handles.

void removeDescriptor(const BLEDescriptor &desc)

Remove a descriptor from this characteristic.

Note

This is a pre-start database-building operation. It is a no-op after the owning service starts. A retained descriptor handle becomes a detached shell.

Parameters:

desc – Handle to the descriptor to remove.

size_t getSubscribedCount() const

Get the number of clients currently subscribed (notify or indicate).

Returns:

Subscriber count.

std::vector<uint16_t> getSubscribedConnections() const

Get the connection handles of all subscribed clients.

Returns:

Vector of connection handles.

bool isSubscribed(uint16_t connHandle) const

Check whether a specific client is subscribed.

Parameters:

connHandle – Connection handle to query.

Returns:

true if the client is subscribed for notifications or indications.

BLEUUID getUUID() const

Get the UUID of this characteristic.

Returns:

The characteristic UUID.

uint16_t getHandle() const

Get the ATT attribute handle of this characteristic.

Returns:

The 16-bit attribute handle.

BLEService getService() const

Get the parent service that owns this characteristic.

Returns:

Handle to the parent BLEService.

void setDescription(const String &desc)

Set the Characteristic User Description (0x2901 descriptor).

Note

Creates or updates the 0x2901 descriptor automatically.

Parameters:

desc – Human-readable description string.

String toString() const

Get a human-readable string representation of this characteristic.

Returns:

String containing UUID, handle, and properties.

BLEDescriptor.h

class BLEDescriptor

GATT Descriptor handle.

Lightweight shared handle wrapping a BLEDescriptor::Impl. Create via characteristic.createDescriptor(uuid, permissions).

Standard descriptor factories:

  • CCCD (0x2902) is auto-created for Notify/Indicate characteristics

  • createUserDescription(text) creates 0x2901

  • createPresentationFormat() creates 0x2904

Public Types

using ReadHandler = std::function<void(BLEDescriptor &desc, const BLEConnInfo &conn)>

Callback invoked when a client reads this descriptor.

Note

Invoked once per client read, including long reads (see BLECharacteristic::ReadHandler).

Note

The mutable desc reference is borrowed for the callback. Copy the handle to retain it; do not retain a pointer or reference to the callback parameter itself. This also applies to WriteHandler.

Param desc:

The descriptor being read. Calling desc.setValue() here sets the value returned in this read response.

Param conn:

Information about the connected client.

using WriteHandler = std::function<void(BLEDescriptor &desc, const BLEConnInfo &conn)>

Callback invoked when a client writes to this descriptor.

Param desc:

The descriptor being written (value already updated).

Param conn:

Information about the connected client.

Public Functions

BLEDescriptor(const BLEUUID &uuid, uint16_t maxLength = 100)

Construct a standalone descriptor with a given UUID and max value length.

Note

Prefer BLECharacteristic::createDescriptor() to add a descriptor to a characteristic directly.

Parameters:
  • uuid – UUID for the descriptor.

  • maxLength – Maximum value length in bytes.

explicit operator bool() const

Check whether this handle refers to a valid descriptor.

Returns:

true if the handle is backed by a live Impl, false otherwise.

void onRead(ReadHandler handler)

Register a callback invoked when a client reads this descriptor.

Parameters:

handler – The read callback, or nullptr to clear.

void onWrite(WriteHandler handler)

Register a callback invoked when a client writes to this descriptor.

Parameters:

handler – The write callback, or nullptr to clear.

void resetCallbacks()

Remove all previously registered callbacks from this descriptor.

void setValue(const uint8_t *data, size_t length)

Set the descriptor value from a raw byte buffer.

Note

Thread-safe: the internal value buffer is guarded by a mutex. The String overload copies the raw bytes and stores no null terminator.

Parameters:
  • data – Pointer to the data bytes.

  • length – Number of bytes to copy.

const uint8_t *getValue(size_t *length = nullptr) const

Get a pointer to the raw descriptor value.

Note

Thread-safe. The returned pointer is invalidated by a concurrent setValue().

Parameters:

length – If non-null, receives the length of the value in bytes (0 when invalid).

Returns:

Pointer to the internal value buffer, or nullptr if the handle is invalid or empty.

size_t getLength() const

Get the current value length.

Returns:

Number of bytes stored in the descriptor value.

void setPermissions(BLEPermission perms)

Set the ATT permissions for this descriptor.

Parameters:

perms – Bitmask of BLEPermission flags.

BLEUUID getUUID() const

Get the UUID of this descriptor.

Returns:

The descriptor UUID.

uint16_t getHandle() const

Get the ATT attribute handle of this descriptor.

Returns:

The 16-bit attribute handle.

BLECharacteristic getCharacteristic() const

Get the parent characteristic that owns this descriptor.

Returns:

Handle to the parent BLECharacteristic.

String toString() const

Get a human-readable string representation of this descriptor.

Returns:

String containing UUID, handle, and value summary.

void setUserDescription(const String &description)

Set the User Description string (0x2901).

Note

No-op unless this descriptor is a 0x2901 User Description.

Parameters:

description – Human-readable description text.

String getUserDescription() const

Get the User Description string (0x2901).

Returns:

The stored description text, or an empty string if this is not a 0x2901 descriptor or the handle is invalid.

bool getNotifications() const

Check whether notifications are enabled in this CCCD.

Returns:

true if the notifications bit is set.

bool getIndications() const

Check whether indications are enabled in this CCCD.

Returns:

true if the indications bit is set.

void setNotifications(bool enable)

Enable or disable notifications in this CCCD.

Note

No-op unless this descriptor is a CCCD (0x2902); auto-resizes the value to 2 bytes.

Parameters:

enable – true to set the notifications bit, false to clear it.

void setIndications(bool enable)

Enable or disable indications in this CCCD.

Note

No-op unless this descriptor is a CCCD (0x2902); auto-resizes the value to 2 bytes.

Parameters:

enable – true to set the indications bit, false to clear it.

void setFormat(uint8_t format)

Set the format field of a Presentation Format descriptor.

Note

No-op unless this is a 0x2904 descriptor with a value of at least 7 bytes.

Parameters:

format – One of the FORMAT_* constants.

void setExponent(int8_t exponent)

Set the exponent field of a Presentation Format descriptor.

Note

No-op unless this is a 0x2904 descriptor with a value of at least 7 bytes.

Parameters:

exponent – Signed exponent applied to the characteristic value.

void setUnit(uint16_t unit)

Set the unit field of a Presentation Format descriptor.

Note

No-op unless this is a 0x2904 descriptor with a value of at least 7 bytes.

Parameters:

unit – Bluetooth Assigned Number for the unit (e.g., 0x2700 for unitless).

void setNamespace(uint8_t ns)

Set the namespace field of a Presentation Format descriptor.

Note

No-op unless this is a 0x2904 descriptor with a value of at least 7 bytes.

Parameters:

ns – Bluetooth namespace (typically 0x01 for Bluetooth SIG).

void setFormatDescription(uint16_t description)

Set the description field of a Presentation Format descriptor.

Note

No-op unless this is a 0x2904 descriptor with a value of at least 7 bytes.

Parameters:

description – Bluetooth SIG-defined description enumeration value.

uint8_t getFormat() const

Get the format field of a Presentation Format descriptor (0x2904).

Returns:

Format code, or 0 if not a valid 7-byte 0x2904 descriptor.

int8_t getExponent() const

Get the exponent field of a Presentation Format descriptor (0x2904).

Returns:

Signed exponent, or 0 if not a valid 7-byte 0x2904 descriptor.

uint16_t getUnit() const

Get the unit field of a Presentation Format descriptor (0x2904).

Returns:

Bluetooth Assigned Number for the unit, or 0 if not a valid 7-byte 0x2904 descriptor.

uint8_t getNamespace() const

Get the namespace field of a Presentation Format descriptor (0x2904).

Returns:

Bluetooth namespace code, or 0 if not a valid 7-byte 0x2904 descriptor.

uint16_t getFormatDescription() const

Get the description field of a Presentation Format descriptor (0x2904).

Returns:

Bluetooth SIG description value, or 0 if not a valid 7-byte 0x2904 descriptor.

bool isUserDescription() const

Check whether this descriptor is a User Description (UUID 0x2901).

Returns:

true if UUID matches 0x2901.

bool isCCCD() const

Check whether this descriptor is a CCCD (UUID 0x2902).

Returns:

true if UUID matches 0x2902.

bool isPresentationFormat() const

Check whether this descriptor is a Presentation Format (UUID 0x2904).

Returns:

true if UUID matches 0x2904.

Public Static Functions

static BLEDescriptor createUserDescription(const String &description)

Create a Characteristic User Description descriptor (UUID 0x2901).

Parameters:

description – Human-readable description text.

Returns:

A new BLEDescriptor configured as a User Description.

static BLEDescriptor createCCCD()

Create a Client Characteristic Configuration Descriptor (UUID 0x2902).

Note

A CCCD is auto-created for characteristics with Notify or Indicate properties; use this factory only when manual control is needed. On NimBLE, manually adding a CCCD to a NOTIFY/INDICATE characteristic causes a validation error.

Returns:

A new BLEDescriptor configured as a CCCD.

static BLEDescriptor createPresentationFormat()

Create a Characteristic Presentation Format descriptor (UUID 0x2904).

Returns:

A new BLEDescriptor configured as a Presentation Format.

Public Static Attributes

static uint8_t FORMAT_BOOLEAN = 1

Boolean.

static uint8_t FORMAT_UINT8 = 4

Unsigned 8-bit integer.

static uint8_t FORMAT_UINT16 = 6

Unsigned 16-bit integer.

static uint8_t FORMAT_UINT32 = 8

Unsigned 32-bit integer.

static uint8_t FORMAT_SINT8 = 12

Signed 8-bit integer.

static uint8_t FORMAT_SINT16 = 14

Signed 16-bit integer.

static uint8_t FORMAT_SINT32 = 16

Signed 32-bit integer.

static uint8_t FORMAT_FLOAT32 = 20

IEEE-754 32-bit float.

static uint8_t FORMAT_FLOAT64 = 21

IEEE-754 64-bit float.

static uint8_t FORMAT_UTF8 = 25

UTF-8 string.

static uint8_t FORMAT_UTF16 = 26

UTF-16 string.

BLEService.h

class BLEService

GATT Service handle.

Lightweight shared handle wrapping a BLEService::Impl. Create via server.createService(uuid).

Public Functions

BLEService()

Construct an empty (invalid) handle; obtain a live one via BLEServer::createService().

explicit operator bool() const

Check whether this handle references a valid service implementation.

Returns:

true if backed by a live Impl; false if default-constructed or moved-from.

BLECharacteristic createCharacteristic(const BLEUUID &uuid, BLEProperty properties, BLEPermission permissions)

Add a characteristic to this service.

Properties and permissions are declared separately (Bluetooth Core Spec Vol 3 §3.3.1.1 and §3.2.5). Permissions are required and the mapping is fail-closed: a read or write property is only exposed if the matching permission direction is declared. Most characteristics need a single BLEPermission value such as BLEPermission::ReadWriteOpen or BLEPermission::ReadEncrypted.

For notify- or indicate-only characteristics (which don’t involve a GATT read/write) pass BLEPermission::None.

Note

Multiple characteristics may share a UUID (differentiated by handle; HID Report characteristics rely on this). Property/permission combinations are validated at construction; invalid combinations return an invalid handle.

Parameters:
  • uuid – UUID of the characteristic to create.

  • properties – Characteristic properties (read, write, notify, etc.).

  • permissions – ATT permission flags controlling access security.

Returns:

A BLECharacteristic handle for the new characteristic, or an invalid handle on failure.

void addIncludedService(const BLEService &service)

Declare another service as included by this service.

An Include Declaration (Core Spec Vol 3, Part G, §3.2) creates a GATT attribute that tells clients the included service is logically part of this service. HIDS requires this for the Battery Service.

Note

The included service must be created on the same server; the include declaration is registered when the server is started.

Parameters:

service – The service to include.

BLECharacteristic getCharacteristic(const BLEUUID &uuid) const

Look up a characteristic in this service by UUID.

Parameters:

uuid – UUID of the characteristic to find.

Returns:

The matching BLECharacteristic handle, or an invalid handle if not found.

std::vector<BLECharacteristic> getCharacteristics() const

Get all characteristics belonging to this service.

Returns:

A vector of BLECharacteristic handles.

void removeCharacteristic(const BLECharacteristic &chr)

Remove a characteristic from this service.

Note

This is a pre-start database-building operation. It is a no-op after the service starts. Only the first matching characteristic is removed. A retained handle to the removed characteristic becomes a detached shell.

Parameters:

chr – The characteristic to remove.

bool isStarted() const

Check whether this service has been started.

Returns:

true after the service is registered in the GATT database (via BLEServer::start()); false otherwise.

BLEUUID getUUID() const

Get the UUID of this service.

Returns:

The service UUID.

uint16_t getHandle() const

Get the attribute handle assigned to this service.

Returns:

The GATT attribute handle.

BLEServer getServer() const

Get the server that owns this service.

Returns:

A BLEServer handle for the parent server, or an invalid handle if this service is not attached to a server.

BLEHIDDevice.h

class BLEHIDDevice

HID-over-GATT (HOGP) device helper.

Creates and manages the standard GATT services for a BLE HID device:

  • Device Information Service (0x180A)

  • HID Service (0x1812)

  • Battery Service (0x180F)

Usage:

BLEServer server = BLE.createServer();
BLEHIDDevice hid(server);
hid.manufacturer("MyCompany");
hid.pnp(0x02, 0x1234, 0x5678, 0x0100);
hid.hidInfo(0x00, 0x01);
hid.reportMap(myDescriptor, sizeof(myDescriptor));
server.start();

Public Functions

explicit BLEHIDDevice(BLEServer server)

Construct a HID device and create all required GATT services.

Note

Creates Device Information (0x180A), HID (0x1812), and Battery (0x180F) services. The HID Service includes the Battery Service via an Include Declaration (HIDS 1.0 §3) and an External Report Reference descriptor on the Report Map pointing to the Battery Level UUID (HIDS 1.0 §3.6). All characteristics default to open (unencrypted) permissions; for HOGP compliance configure BLEServer-level security. Protocol Mode is initialized to Report Protocol Mode (1). The HID Service UUID (0x1812) is automatically added to the advertising payload (HOGP §4.3.1 / HIDS 1.0 §3) so hosts can discover the device by service class.

Parameters:

server – The BLE server to host the HID, Device Information, and Battery services on.

inline explicit operator bool() const

Check whether this HID device was constructed with a valid server.

Returns:

true if the underlying server handle is valid.

void reportMap(const uint8_t *map, uint16_t size)

Set the HID Report Map (report descriptor).

Parameters:
  • map – Pointer to the HID report descriptor byte array.

  • size – Length of the report descriptor in bytes.

BLEService deviceInfoService()

Get the Device Information Service (UUID 0x180A).

Returns:

Handle to the Device Information Service.

BLEService hidService()

Get the HID Service (UUID 0x1812).

Returns:

Handle to the HID Service.

BLEService batteryService()

Get the Battery Service (UUID 0x180F).

Returns:

Handle to the Battery Service.

BLECharacteristic manufacturer()

Get the Manufacturer Name characteristic.

Returns:

Handle to the Manufacturer Name String characteristic.

void manufacturer(const String &name)

Set the Manufacturer Name String value.

Parameters:

name – Manufacturer name to write into the Device Information Service.

void pnp(uint8_t sig, uint16_t vendorId, uint16_t productId, uint16_t version)

Set the PnP ID characteristic of the Device Information Service.

Note

vendorId, productId, and version are stored little-endian per the PnP ID format.

Parameters:
  • sig – Vendor ID source (0x01 = Bluetooth SIG, 0x02 = USB Implementers Forum).

  • vendorId – Vendor ID assigned by the source indicated by sig.

  • productId – Product ID assigned by the vendor.

  • version – Product version (BCD, e.g. 0x0100 = 1.0.0).

void hidInfo(uint8_t country, uint8_t flags)

Set the HID Information characteristic.

Note

bcdHID is fixed at 0x0111 (HID version 1.11).

Parameters:
  • country – HID country code (0x00 = not localized).

  • flags – HID information flags (bit 0: RemoteWake, bit 1: NormallyConnectable).

void setBatteryLevel(uint8_t level)

Update the battery level characteristic and notify subscribed clients.

Note

Notification is only delivered to clients that enabled the Battery Level CCCD; without it the value is updated but no notification is sent.

Parameters:

level – Battery percentage (0–100).

BLECharacteristic hidControl()

Get the HID Control Point characteristic.

Returns:

Handle to the HID Control Point characteristic (Suspend / Exit Suspend).

BLECharacteristic protocolMode()

Get the Protocol Mode characteristic.

Returns:

Handle to the Protocol Mode characteristic (Boot / Report protocol).

BLECharacteristic inputReport(uint8_t reportId)

Create and return an Input Report characteristic (Read + Notify).

Note

Uses open (unencrypted) permissions so HOGP hosts can enumerate before encryption.

Parameters:

reportId – HID Report ID to assign via the Report Reference descriptor.

Returns:

Handle to the new Input Report characteristic.

BLECharacteristic outputReport(uint8_t reportId)

Create and return an Output Report characteristic (Read + Write + WriteNR).

Note

Uses open (unencrypted) permissions so HOGP hosts can enumerate before encryption.

Parameters:

reportId – HID Report ID to assign via the Report Reference descriptor.

Returns:

Handle to the new Output Report characteristic.

BLECharacteristic featureReport(uint8_t reportId)

Create and return a Feature Report characteristic (Read + Write).

Note

Uses open (unencrypted) permissions so HOGP hosts can enumerate before encryption.

Parameters:

reportId – HID Report ID to assign via the Report Reference descriptor.

Returns:

Handle to the new Feature Report characteristic.

BLECharacteristic bootInput()

Get the Boot Keyboard Input Report characteristic (Read + Notify).

Note

Created lazily on first call (HIDS 1.0 §3.4); subsequent calls return the cached handle.

Returns:

Handle to the Boot Keyboard Input Report characteristic.

BLECharacteristic bootOutput()

Get the Boot Keyboard Output Report characteristic (Read + Write + WriteNR).

Note

Created lazily on first call; subsequent calls return the cached handle.

Returns:

Handle to the Boot Keyboard Output Report characteristic.

HIDKeyboardTypes.h

struct KEYMAP

Mapping from an ASCII character to its HID usage code and modifier bitmask.

Public Members

unsigned char usage

HID usage ID (Keyboard/Keypad page 0x07).

unsigned char modifier

Modifier bitmask (see MODIFIER_KEY).

enum FUNCTION_KEY

Function, navigation, and lock key codes.

Values start at 128 to avoid collision with printable ASCII codes in the KEYMAP table.

Values:

enumerator KEY_F1
enumerator KEY_F2
enumerator KEY_F3
enumerator KEY_F4
enumerator KEY_F5
enumerator KEY_F6
enumerator KEY_F7
enumerator KEY_F8
enumerator KEY_F9
enumerator KEY_F10
enumerator KEY_F11
enumerator KEY_F12
enumerator KEY_PRINT_SCREEN
enumerator KEY_SCROLL_LOCK
enumerator KEY_CAPS_LOCK
enumerator KEY_NUM_LOCK
enumerator KEY_INSERT
enumerator KEY_HOME
enumerator KEY_PAGE_UP
enumerator KEY_PAGE_DOWN
enumerator RIGHT_ARROW
enumerator LEFT_ARROW
enumerator DOWN_ARROW
enumerator UP_ARROW
enum MEDIA_KEY

HID Consumer Control (media) key codes.

These map to HID Usage Page 0x0C (Consumer) usages for media playback and volume control.

Values:

enumerator KEY_NEXT_TRACK

Next Track Button

enumerator KEY_PREVIOUS_TRACK

Previous Track Button

enumerator KEY_STOP

Stop Button

enumerator KEY_PLAY_PAUSE

Play/Pause Button

enumerator KEY_MUTE

Mute Button

enumerator KEY_VOLUME_UP

Volume Up Button

enumerator KEY_VOLUME_DOWN

Volume Down Button

enum MODIFIER_KEY

Keyboard modifier key bitmask values.

Each value is a single bit in the modifier byte of an HID keyboard report. Combine with bitwise OR to press multiple modifiers.

Values:

enumerator KEY_CTRL
enumerator KEY_SHIFT
enumerator KEY_ALT
enumerator KEY_GUI

GUI key (Command on macOS, Windows key on Windows)

enumerator KEY_LEFT_CTRL
enumerator KEY_LEFT_SHIFT
enumerator KEY_LEFT_ALT
enumerator KEY_LEFT_GUI
enumerator KEY_RIGHT_CTRL
enumerator KEY_RIGHT_SHIFT
enumerator KEY_RIGHT_ALT
enumerator KEY_RIGHT_GUI

HIDTypes.h

struct HID_REPORT

Fixed-size buffer for a single HID report.

data holds only the report payload; the Report ID is conveyed by the Report Reference descriptor and must not be prepended to data.

Public Members

uint32_t length

Number of valid bytes in data.

uint8_t data[MAX_HID_REPORT_SIZE]

Report payload (excluding the Report ID).

BLEIso.h

class BLEIso

Public Types

enum class Phy : uint8_t

PHY selector for ISO QoS.

Values:

enumerator Phy1M
enumerator Phy2M
enumerator PhyCoded

Public Functions

explicit operator bool() const

Whether this handle references the live transport (minted after BLE.begin()).

BTStatus begin()

Bring the transport up (idempotent). Call after BLE.begin().

Initializes ISO on the host, or attaches to it when the LE Audio engine already owns it. Every channel from a previous session is dropped. When a previous end() failed partway (channels left behind), begin() retries the release instead of reporting a clean start over a wedged session.

BTStatus end()

Terminate every group and release every channel.

Also releases the host ISO layer when this transport initialized it. Called from a Bluetooth stack/ISO callback, end() is refused with Busy because it must wait for asynchronous ISO disconnect; defer it to loop().

Returns:

BTStatus::OK (also when not active); Busy from a stack callback; Timeout/Fail when an ISO channel or group could not be released.

bool isActive() const

Whether begin() succeeded and end() has not run.

Channel connectCis(uint16_t connHandle, const CisParams &params)

Create the CIG and connect a CIS as Central on an existing ACL link.

Only one Central CIS at a time: after it went down, calling this again reconnects with a new handle (possibly with new QoS).

Parameters:

connHandle – ACL connection handle (e.g. BLEClient::getHandle()). Stale handles (0xFFFF, dead or recycled links) are refused before any CIG is created: a CIG/CIS over a dead link wastes HCI commands and could bind the channel to the wrong peer after a controller recycle.

Returns:

The channel handle, empty on error. onConnected fires when the CIS is up.

Channel connectCis(uint16_t connHandle)

As connectCis(), with default QoS.

Channel listenCis(const CisParams &params)

Register the ISO server and accept an inbound CIS as Peripheral.

Only sduSize and returnSduSize are used: the Central chooses the rest of the QoS. The channel keeps listening after its CIS disconnects; a second call reserves an additional concurrent channel, it is not a re-arm. Never-started listening is stopped with disconnect().

Returns:

The channel handle, empty on error. onConnected fires on acceptance.

Channel listenCis()

As listenCis(), with default QoS.

Channel createBig(uint8_t advHandle, const BigParams &params)

Create a single-BIS BIG (Broadcaster) on a running extended + periodic advertising set.

Only one BIG at a time: after disconnect() and onDisconnected, calling this again creates a new BIG with a new handle.

Parameters:

advHandle – Advertising instance carrying the periodic train.

Returns:

The channel handle, empty on error. onConnected fires when the BIS is up.

Channel createBig(uint8_t advHandle)

As createBig(), with default QoS.

Channel syncBig(uint8_t bisIndex, const BigParams &params)

Arm a BIG sync (Receiver) for one BIS index on the synced periodic train.

Only sduSize and broadcastCode are used; the BIGInfo supplies the rest. The code is applied only if the BIGInfo reports an encrypted BIG. While armed, a lost sync is re-issued on the next BIGInfo report. Calling this again while not synced replaces the armed sync.

Parameters:

bisIndex – 1-based BIS index to receive.

Returns:

The channel handle, empty on error. onConnected fires when synced.

Channel syncBig(uint8_t bisIndex)

As syncBig(), with default QoS.

struct SduInfo

Receive metadata for one transparent SDU.

Public Members

uint32_t timestampUs = 0

Controller timestamp (only if timestampValid).

uint16_t seqNum = 0

SDU sequence number of the first fragment.

bool valid = false

Payload is complete and error-free.

bool timestampValid = false

The timestamp field is meaningful.

class Channel

One ISO channel (a CIS or a single BIS).

A shared handle: copies share the same channel, and a handle outliving its channel (disconnect, end(), slot reuse) becomes a detached shell whose operations fail safe with InvalidState.

Not directly constructed: the factories below return a handle to a pool-owned channel, empty when the role is disabled or no slot is free. Calling the same factory again after the channel went down (CIS Central, BIS Broadcaster, BIS Receiver) mints a new handle and drops the old channel’s callbacks, so register them again.

Callbacks fire from the ISO host task and must not block.

Public Functions

explicit operator bool() const

Whether this handle references a live channel (minted by a factory and not yet detached).

int slot() const

Pool slot index (stable while the handle is attached), or -1.

Diagnostic only: a reused slot mints a new handle, so an index match does not imply the same channel.

bool isConnected() const

Whether the underlying CIS/BIS is currently established.

bool canSend() const

Whether this side transmits on the channel.

True for a CIS Central with a nonzero sduSize, a CIS Peripheral with a nonzero returnSduSize, and a BIS Broadcaster.

BTStatus send(const uint8_t *sdu, uint16_t len)

Send one transparent SDU with the next sequence number.

The channel numbers SDUs itself: the counter restarts at 0 on every connection and advances only when the stack accepts the SDU. Call once per SDU interval.

Returns:

OK, InvalidState for a detached handle, Fail when the stack refused (not connected, no Tx direction, no buffer).

BTStatus send(const uint8_t *sdu, uint16_t len, uint16_t seqNum)

Send one transparent SDU with a caller-managed sequence number.

Parameters:

seqNum – SDU sequence number; the next send(sdu, len) continues from seqNum + 1.

Returns:

As send(const uint8_t *, uint16_t).

BTStatus disconnect()

Take the channel down.

CIS: disconnects it. BIS Broadcaster: terminates the BIG. BIS Receiver: terminates the BIG sync, or disarms a sync that was not issued yet. onDisconnected follows once the controller confirms (not for a disarm).

Returns:

OK, InvalidState for a detached handle, Fail when the stack refused.

void onConnected(ConnectedCb cb)

The CIS/BIS is up and its data path is set up.

void onDisconnected(DisconnectedCb cb)

The CIS/BIS went down (or failed to come up); reason is the HCI reason.

void onReceive(ReceiveCb cb)

One SDU received; check SduInfo::valid, damaged SDUs are delivered too.

void onSent(SentCb cb)

The controller consumed one SDU passed to send().

void resetCallbacks()

Drop every callback.

struct CisParams

Connected Isochronous Stream (CIS) QoS.

Use the same values on both sides. The Central’s QoS defines the CIS; the Peripheral only uses the two SDU sizes to size its directions.

Public Members

uint32_t sduIntervalUs = 10000

SDU interval, microseconds (both directions).

uint16_t latencyMs = 10

Max transport latency, milliseconds (both directions).

uint16_t sduSize = 120

Max SDU size Central to Peripheral, octets (0: no data this way).

uint16_t returnSduSize = 0

Max SDU size Peripheral to Central, octets (0: no data this way).

uint8_t rtn = 2

Retransmission number.

uint8_t packing = 0

0 sequential, 1 interleaved.

uint8_t framing = 0

0 unframed, 1 framed.

struct BigParams

Broadcast Isochronous Group (BIG) QoS; one BIS per group.

Public Members

uint32_t sduIntervalUs = 10000

SDU interval, microseconds.

uint16_t latencyMs = 10

Max transport latency, milliseconds.

uint16_t sduSize = 120

Max SDU size, octets.

uint8_t rtn = 2

Retransmission number.

uint8_t packing = 0

0 sequential, 1 interleaved.

uint8_t framing = 0

0 unframed, 1 framed.

String broadcastCode

Up to 16 characters; empty for an unencrypted BIG.

BLEL2CAP.h

class BLEL2CAPChannel

L2CAP Connection-Oriented Channel (CoC) handle.

Represents a single bidirectional L2CAP CoC channel. Channels are created by BLEL2CAPServer (server side) or BLEClass::connectL2CAP() (client side).

L2CAP CoC channels provide a higher-throughput alternative to GATT for bulk data transfer, bypassing the GATT attribute protocol overhead.

Public Types

using DataHandler = std::function<void(BLEL2CAPChannel &channel, const uint8_t *data, size_t len)>

Callback invoked when data arrives on the channel.

Param channel:

The channel that received data.

Param data:

Pointer to the received bytes.

Param len:

Number of bytes received.

using DisconnectHandler = std::function<void(BLEL2CAPChannel &channel)>

Callback invoked when the channel is disconnected.

Param channel:

The channel that was disconnected.

Public Functions

explicit operator bool() const

Test whether this handle refers to a valid channel.

Returns:

true if the channel is initialized and usable, false otherwise.

BTStatus write(const uint8_t *data, size_t len)

Send data over the L2CAP channel.

Note

Payloads larger than the peer CoC MTU are split into MTU-sized SDUs. Multi-SDU writes may block briefly while waiting for peer credits between chunks (BLE_L2CAP_EVENT_COC_TX_UNSTALLED) when called outside a BLE host callback.

Parameters:
  • data – Pointer to the bytes to send.

  • len – Number of bytes to send.

Returns:

BTStatus::OK on success, BTStatus::Busy when called from a host callback and completion would require waiting for peer credits, or BTStatus::NotConnected after channel teardown.

BTStatus disconnect()

Disconnect this L2CAP channel.

Returns:

BTStatus::OK on success, BTStatus::Busy if another channel operation is active in a host callback, or BTStatus::NotConnected if the channel is already detached.

BTStatus onData(DataHandler handler)

Register a handler for incoming data on this channel.

Parameters:

handler – Callback to invoke when data is received.

Returns:

BTStatus::OK on success.

BTStatus onDisconnect(DisconnectHandler handler)

Register a handler for disconnection of this channel.

Parameters:

handler – Callback to invoke on disconnect.

Returns:

BTStatus::OK on success.

BTStatus resetCallbacks()

Remove all registered callbacks from this channel.

Returns:

BTStatus::OK on success.

bool isConnected() const

Check if the channel is currently connected.

Returns:

true if connected, false otherwise.

uint16_t getPSM() const

Get the Protocol/Service Multiplexer number for this channel.

Returns:

The PSM value.

uint16_t getMTU() const

Get the negotiated Maximum Transmission Unit for this channel.

Returns:

The MTU in bytes; this is OUR receive MTU (the SDU size this side accepts). Writes are split by the PEER’s send MTU instead, so a full-MTU write may still be sent in several chunks.

uint16_t getConnHandle() const

Get the underlying BLE connection handle.

Returns:

The HCI connection handle.

class BLEL2CAPServer

L2CAP CoC server — listens for incoming channel connections on a PSM.

Create via BLE.createL2CAPServer(psm, mtu). When a remote device opens an L2CAP CoC channel to this PSM, the onAccept callback fires with a BLEL2CAPChannel handle.

Public Types

using AcceptHandler = std::function<void(BLEL2CAPChannel &channel)>

Callback invoked when a new L2CAP channel is accepted.

Param channel:

The newly accepted channel handle.

using DataHandler = std::function<void(BLEL2CAPChannel &channel, const uint8_t *data, size_t len)>

Callback invoked when data arrives on any channel owned by this server.

Param channel:

The channel that received data.

Param data:

Pointer to the received bytes.

Param len:

Number of bytes received.

using DisconnectHandler = std::function<void(BLEL2CAPChannel &channel)>

Callback invoked when a channel owned by this server disconnects.

Param channel:

The channel that was disconnected.

Public Functions

explicit operator bool() const

Test whether this handle refers to a valid server.

Returns:

true if the server is initialized, false otherwise.

BTStatus onAccept(AcceptHandler handler)

Register a handler for incoming channel connections.

Parameters:

handler – Callback to invoke when a remote device opens a channel to this PSM.

Returns:

BTStatus::OK on success.

BTStatus onData(DataHandler handler)

Register a default data handler for all channels accepted by this server.

Note

Per-channel handlers registered via BLEL2CAPChannel::onData() take precedence.

Parameters:

handler – Callback to invoke when data is received.

Returns:

BTStatus::OK on success.

BTStatus onDisconnect(DisconnectHandler handler)

Register a default disconnect handler for all channels accepted by this server.

Parameters:

handler – Callback to invoke on channel disconnect.

Returns:

BTStatus::OK on success.

BTStatus resetCallbacks()

Remove all registered callbacks from this server.

Returns:

BTStatus::OK on success.

uint16_t getPSM() const

Get the Protocol/Service Multiplexer number this server listens on.

Returns:

The PSM value.

uint16_t getMTU() const

Get the MTU configured for this server.

Returns:

The MTU in bytes.

BLERemoteCharacteristic.h

class BLERemoteCharacteristic

Remote GATT characteristic discovered on a peer device.

Shared handle. Obtained via BLERemoteService::getCharacteristic().

Public Types

using NotifyCallback = std::function<void(BLERemoteCharacteristic &chr, const uint8_t*, size_t, BLESubscription)>

Callback type for characteristic notifications and indications.

Note

Runs on the BLE stack task. Do not call blocking GATT operations (readValue(), confirmed writeValue(), subscribe()) on chr here: they wait for a response that this same task delivers, so they stall until their timeout. A read also replaces the buffer data points into. Defer such work to another task.

Note

For the GATT Service Changed characteristic (0x2A05), the discovered remote tree is invalidated before this callback. Bluedroid does not expose the peer’s changed-handle range, so its callback payload is the conservative full range 01 00 FF FF; rediscover services before using any prior remote handle.

Param chr:

The characteristic that received the value.

Param data:

Pointer to the payload.

Param length:

Length of the payload in bytes.

Param kind:

BLESubscription::Notify or BLESubscription::Indicate for this ATT PDU. Never BLESubscription::None and never both bits.

Public Functions

BLERemoteCharacteristic()

Construct an empty (invalid) handle; obtain a live one via BLERemoteService::getCharacteristic().

explicit operator bool() const

Check whether this handle refers to a valid remote characteristic.

Returns:

True if the underlying characteristic data is present, false otherwise.

String readValue(uint32_t timeoutMs = 3000)

Read the characteristic value from the remote device.

Note

The call blocks the current task until the GATT read completes or timeoutMs elapses. If encryption is being negotiated, the implementation may wait for the security procedure before the read.

Parameters:

timeoutMs – Maximum time in milliseconds to wait for a response.

Returns:

The value as a String, or an empty String on failure/timeout.

uint8_t readUInt8(uint32_t timeoutMs = 3000)

Read the characteristic value and interpret the first byte as uint8_t.

Parameters:

timeoutMs – Maximum time in milliseconds to wait for a response.

Returns:

The first byte of the value, or 0 on failure.

uint16_t readUInt16(uint32_t timeoutMs = 3000)

Read the characteristic value and interpret the first two bytes as uint16_t.

Parameters:

timeoutMs – Maximum time in milliseconds to wait for a response.

Returns:

The little-endian 16-bit value, or 0 on failure.

uint32_t readUInt32(uint32_t timeoutMs = 3000)

Read the characteristic value and interpret the first four bytes as uint32_t.

Parameters:

timeoutMs – Maximum time in milliseconds to wait for a response.

Returns:

The little-endian 32-bit value, or 0 on failure.

float readFloat(uint32_t timeoutMs = 3000)

Read the characteristic value and interpret the first four bytes as a float.

Parameters:

timeoutMs – Maximum time in milliseconds to wait for a response.

Returns:

The float value, or 0.0f on failure.

size_t readValue(uint8_t *buf, size_t bufLen, uint32_t timeoutMs = 3000)

Read the characteristic value into a caller-supplied buffer.

Parameters:
  • buf – Destination buffer.

  • bufLen – Size of buf in bytes.

  • timeoutMs – Maximum time in milliseconds to wait for a response.

Returns:

Number of bytes copied into buf (may be less than the full value if bufLen is too small).

const uint8_t *readRawData(size_t *len = nullptr) const

Get a pointer to the most recently read raw value without issuing a new read.

Note

The pointer is invalidated by any subsequent read or write on this characteristic.

Parameters:

len – If non-null, receives the length of the data in bytes.

Returns:

Pointer to the internal buffer, or nullptr if no value has been read yet.

BTStatus writeValue(const uint8_t *data, size_t len, bool withResponse = true)

Write a value to the remote characteristic.

Note

For ATT payloads that exceed one connection event or require prepared writes, the stack selects long-write semantics; withResponse should be true. Blocking behavior matches readValue.

Parameters:
  • data – Pointer to the data to write.

  • len – Number of bytes to write.

  • withResponse – If true, use Write Request (ATT); if false, use Write Command (no ACK).

Returns:

BTStatus indicating success or failure.

bool canRead() const

Check if the characteristic supports reads.

Returns:

True if the Read property is set.

bool canWrite() const

Check if the characteristic supports writes with response.

Returns:

True if the Write property is set.

bool canWriteNoResponse() const

Check if the characteristic supports writes without response.

Returns:

True if the Write Without Response property is set.

bool canNotify() const

Check if the characteristic supports notifications.

Returns:

True if the Notify property is set.

bool canIndicate() const

Check if the characteristic supports indications.

Returns:

True if the Indicate property is set.

bool canBroadcast() const

Check if the characteristic supports broadcast.

Returns:

True if the Broadcast property is set.

BTStatus subscribe(BLESubscription mode, NotifyCallback callback = nullptr)

Subscribe to server-initiated deliveries from this characteristic.

Note

Writes the selected bits to the Client Characteristic Configuration Descriptor (CCCD); the bits replace any previous subscription.

Parameters:
  • mode – Deliveries to enable (BLESubscription::Notify, BLESubscription::Indicate, or both combined with |). Must not be BLESubscription::None; use unsubscribe() to disable deliveries.

  • callback – Optional callback invoked on each delivery.

Returns:

BTStatus indicating success or failure.

BTStatus unsubscribe()

Unsubscribe from notifications and indications.

Returns:

BTStatus indicating success or failure.

BLERemoteDescriptor getDescriptor(const BLEUUID &uuid) const

Discover and return a descriptor by UUID.

Note

Triggers GATT descriptor discovery on first call.

Parameters:

uuid – UUID of the descriptor to find.

Returns:

The matching descriptor, or an invalid handle if not found.

std::vector<BLERemoteDescriptor> getDescriptors() const

Return all discovered descriptors of this characteristic.

Note

Triggers GATT descriptor discovery on first call.

Returns:

Vector of descriptor handles (may be empty).

BLERemoteService getRemoteService() const

Get the parent service of this characteristic.

Returns:

The parent BLERemoteService handle.

BLEUUID getUUID() const

Get the UUID of this characteristic.

Returns:

The characteristic UUID.

uint16_t getHandle() const

Get the attribute handle of this characteristic.

Returns:

The GATT attribute handle.

String toString() const

Get a human-readable representation of this characteristic.

Returns:

A String describing the characteristic UUID, handle, and properties.

BLERemoteDescriptor.h

class BLERemoteDescriptor

Remote GATT descriptor discovered on a peer device.

Shared handle. Obtained via BLERemoteCharacteristic::getDescriptor().

Public Functions

BLERemoteDescriptor()

Construct an empty (invalid) handle; obtain a live one via BLERemoteCharacteristic::getDescriptor().

explicit operator bool() const

Check whether this handle refers to a valid remote descriptor.

Returns:

True if the underlying descriptor data is present, false otherwise.

String readValue(uint32_t timeoutMs = 3000)

Read the descriptor value from the remote device.

Parameters:

timeoutMs – Maximum time in milliseconds to wait for a response.

Returns:

The value as a String, or an empty String on failure/timeout.

uint8_t readUInt8(uint32_t timeoutMs = 3000)

Read the descriptor value and interpret the first byte as uint8_t.

Parameters:

timeoutMs – Maximum time in milliseconds to wait for a response.

Returns:

The first byte of the value, or 0 on failure.

uint16_t readUInt16(uint32_t timeoutMs = 3000)

Read the descriptor value and interpret the first two bytes as uint16_t.

Parameters:

timeoutMs – Maximum time in milliseconds to wait for a response.

Returns:

The little-endian 16-bit value, or 0 on failure.

uint32_t readUInt32(uint32_t timeoutMs = 3000)

Read the descriptor value and interpret the first four bytes as uint32_t.

Parameters:

timeoutMs – Maximum time in milliseconds to wait for a response.

Returns:

The little-endian 32-bit value, or 0 on failure.

const uint8_t *readRawData(size_t *len = nullptr) const

Get a pointer to the cached raw data from the last read.

Parameters:

len – If non-null, receives the data length in bytes.

Returns:

Pointer to the internal value buffer, or nullptr if empty.

bool isUserDescription() const

Check whether this descriptor is a User Description (UUID 0x2901).

Returns:

true if UUID matches 0x2901.

bool isCCCD() const

Check whether this descriptor is a CCCD (UUID 0x2902).

Returns:

true if UUID matches 0x2902.

bool isPresentationFormat() const

Check whether this descriptor is a Presentation Format (UUID 0x2904).

Returns:

true if UUID matches 0x2904.

uint8_t getFormat() const

Get the format field from the cached Presentation Format descriptor (0x2904) value.

Returns:

Format code, or 0 if not a valid 7-byte 0x2904 descriptor. Call readValue() first.

int8_t getExponent() const

Get the exponent field from the cached Presentation Format descriptor (0x2904) value.

Returns:

Signed exponent, or 0 if not a valid 7-byte 0x2904 descriptor. Call readValue() first.

uint16_t getUnit() const

Get the unit field from the cached Presentation Format descriptor (0x2904) value.

Returns:

Bluetooth Assigned Number for the unit, or 0 if not a valid 7-byte 0x2904 descriptor. Call readValue() first.

uint8_t getNamespace() const

Get the namespace field from the cached Presentation Format descriptor (0x2904) value.

Returns:

Bluetooth namespace code, or 0 if not a valid 7-byte 0x2904 descriptor. Call readValue() first.

uint16_t getFormatDescription() const

Get the description field from the cached Presentation Format descriptor (0x2904) value.

Returns:

Bluetooth SIG description value, or 0 if not a valid 7-byte 0x2904 descriptor. Call readValue() first.

BTStatus writeValue(const uint8_t *data, size_t len, bool withResponse = true)

Write a value to the remote descriptor.

Parameters:
  • data – Pointer to the data to write.

  • len – Number of bytes to write.

  • withResponse – If true, use Write Request (ATT); if false, use Write Command (no ACK).

Returns:

BTStatus indicating success or failure.

BLERemoteCharacteristic getRemoteCharacteristic() const

Get the parent characteristic of this descriptor.

Returns:

The parent BLERemoteCharacteristic handle.

BLEUUID getUUID() const

Get the UUID of this descriptor.

Returns:

The descriptor UUID.

uint16_t getHandle() const

Get the attribute handle of this descriptor.

Returns:

The GATT attribute handle.

String toString() const

Get a human-readable representation of this descriptor.

Returns:

A String describing the descriptor UUID and handle.

BLERemoteService.h

class BLERemoteService

Remote GATT service discovered on a peer device.

Shared handle. Obtained via BLEClient::getService() or BLEClient::getServices().

Public Functions

BLERemoteService()

Construct an empty (invalid) handle; obtain a live one via BLEClient::getService().

explicit operator bool() const

Check whether this handle refers to a valid remote service.

Returns:

True if the underlying service data is present, false otherwise.

BLERemoteCharacteristic getCharacteristic(const BLEUUID &uuid) const

Discover and return a characteristic by UUID.

Note

Triggers GATT characteristic discovery on first call.

Parameters:

uuid – UUID of the characteristic to find.

Returns:

The matching characteristic, or an invalid handle if not found.

std::vector<BLERemoteCharacteristic> getCharacteristics() const

Return all discovered characteristics of this service.

Note

Triggers GATT characteristic discovery on first call.

Returns:

Vector of characteristic handles (may be empty).

BLEClient getClient() const

Get the client that owns this service.

Returns:

The parent BLEClient handle.

BLEUUID getUUID() const

Get the UUID of this service.

Returns:

The service UUID.

uint16_t getHandle() const

Get the attribute handle of this service.

Returns:

The GATT attribute handle.

String getValue(const BLEUUID &charUUID)

Shorthand: read a characteristic value by UUID.

Note

Discovers the characteristic first; blocks until the GATT read completes.

Parameters:

charUUID – UUID of the characteristic to read.

Returns:

The characteristic value as a String, or an empty String on failure.

BTStatus setValue(const BLEUUID &charUUID, const String &value)

Shorthand: write a characteristic value by UUID.

Parameters:
  • charUUID – UUID of the characteristic to write.

  • value – The value to write.

Returns:

BTStatus::NotFound if the characteristic is not in this service, otherwise the status of the underlying write.

String toString() const

Get a human-readable representation of this service.

Returns:

A String describing the service UUID and handle.

BLEAdvertisedDevice.h

class BLEAdvertisedDevice

Represents a single advertised BLE device discovered during scanning.

Shared handle. Obtained via BLEScan callbacks or BLEScan::Results. Contains parsed advertisement data (name, UUIDs, manufacturer data, etc.).

Public Types

enum FrameType

Beacon/frame type detected in the advertisement payload.

Values:

enumerator Unknown
enumerator IBeacon
enumerator EddystoneUUID
enumerator EddystoneURL
enumerator EddystoneTLM

Public Functions

explicit operator bool() const

Check whether this handle refers to a valid advertised device.

Returns:

True if the underlying device data is present, false otherwise.

BTAddress getAddress() const

Get the advertiser’s BLE address.

Returns:

The device address.

BTAddress::Type getAddressType() const

Get the address type (public, random, etc.).

Returns:

The address type.

String getName() const

Get the advertised local name.

Returns:

The device name, or an empty String if not present.

int8_t getRSSI() const

Get the received signal strength.

Returns:

RSSI in dBm, or -128 if unavailable.

int8_t getTXPower() const

Get the advertised TX power level.

Returns:

TX power in dBm, or -128 if not present.

uint16_t getAppearance() const

Get the advertised appearance value.

Returns:

The GAP appearance code, or 0 if not present.

uint16_t getMinPreferred() const

Get the advertised minimum preferred connection interval (AD type 0x12).

Returns:

Minimum connection interval in units of 1.25 ms, or 0 if not present.

uint16_t getMaxPreferred() const

Get the advertised maximum preferred connection interval (AD type 0x12).

Returns:

Maximum connection interval in units of 1.25 ms, or 0 if not present.

BLEAdvType getAdvType() const

Get the advertisement PDU type.

Returns:

The advertisement type enum value.

const uint8_t *getManufacturerData(size_t *len) const

Get the raw manufacturer-specific data.

Parameters:

len – If non-null, receives the data length in bytes (including the company ID).

Returns:

Pointer to the manufacturer data, or nullptr if not present.

String getManufacturerDataString() const

Get the manufacturer-specific data as a hex-encoded String.

Returns:

Hex string of the manufacturer data, or an empty String if not present.

uint16_t getManufacturerCompanyId() const

Get the company identifier from the manufacturer-specific data.

Returns:

The 16-bit company ID, or 0 if manufacturer data is not present.

size_t getServiceUUIDCount() const

Get the number of service UUIDs in the advertisement.

Returns:

The service UUID count.

BLEUUID getServiceUUID(size_t index = 0) const

Get a service UUID by index.

Parameters:

index – Zero-based index into the advertised service UUID list.

Returns:

The service UUID, or an invalid UUID if index is out of range.

bool haveServiceUUID() const

Check if the advertisement contains any service UUIDs.

Returns:

True if at least one service UUID is present.

bool isAdvertisingService(const BLEUUID &uuid) const

Check if a specific service UUID is advertised.

Parameters:

uuid – The service UUID to search for.

Returns:

True if the UUID is in the advertisement.

size_t getServiceDataCount() const

Get the number of service data entries in the advertisement.

Returns:

The service data entry count.

const uint8_t *getServiceData(size_t index, size_t *len) const

Get raw service data by index.

Parameters:
  • index – Zero-based index into the service data list.

  • len – If non-null, receives the data length in bytes.

Returns:

Pointer to the service data, or nullptr if index is out of range.

String getServiceDataString(size_t index = 0) const

Get service data as a hex-encoded String.

Parameters:

index – Zero-based index into the service data list.

Returns:

Hex string, or an empty String if index is out of range.

BLEUUID getServiceDataUUID(size_t index = 0) const

Get the UUID associated with a service data entry.

Parameters:

index – Zero-based index into the service data list.

Returns:

The service data UUID, or an invalid UUID if index is out of range.

bool haveServiceData() const

Check if the advertisement contains any service data.

Returns:

True if at least one service data entry is present.

const uint8_t *getPayload() const

Get a pointer to the raw advertisement payload.

Returns:

Pointer to the AD structure bytes.

size_t getPayloadLength() const

Get the total length of the raw advertisement payload.

Returns:

Payload length in bytes.

bool haveName() const

Check if a local name was present in the advertisement.

Returns:

True if the name field is present.

bool haveRSSI() const

Check if an RSSI value is available.

Returns:

True if RSSI was recorded.

bool haveTXPower() const

Check if a TX power level was present in the advertisement.

Returns:

True if the TX power field is present.

bool haveAppearance() const

Check if an appearance value was present in the advertisement.

Returns:

True if the appearance field is present.

bool havePreferredParams() const

Check if preferred connection interval parameters (AD type 0x12) were present.

Returns:

True if the Slave Connection Interval Range AD structure is present.

bool haveManufacturerData() const

Check if manufacturer-specific data was present in the advertisement.

Returns:

True if manufacturer data is present.

bool isConnectable() const

Check if the advertiser accepts connections.

Returns:

True if the advertisement is connectable.

bool isScannable() const

Check if the advertiser accepts scan requests.

Returns:

True if the advertisement is scannable.

bool isDirected() const

Check if this is a directed advertisement.

Returns:

True if the advertisement is directed to a specific device.

bool isLegacyAdvertisement() const

Check if this is a legacy (non-extended) advertisement.

Returns:

True for legacy ADV_IND / ADV_SCAN_IND / ADV_NONCONN_IND PDUs.

BLEPhy getPrimaryPhy() const

Get the primary advertising PHY (extended advertising only).

Returns:

The primary PHY.

BLEPhy getSecondaryPhy() const

Get the secondary advertising PHY (extended advertising only).

Returns:

The secondary PHY.

uint8_t getAdvSID() const

Get the advertising set ID (SID) for extended advertising.

Returns:

The SID value (0-15), or 0xFF if not available.

uint16_t getPeriodicInterval() const

Get the periodic advertising interval.

Returns:

Interval in units of 1.25 ms, or 0 if not a periodic advertisement.

FrameType getFrameType() const

Detect the beacon frame type of this advertisement.

Returns:

The detected FrameType, or Unknown if no known beacon format matches.

bool getBeacon(BLEBeacon &beacon) const

Parse this advertisement as an Apple iBeacon.

Parameters:

beacon – Output parameter populated when the advertisement is an iBeacon.

Returns:

True if this advertisement is a valid iBeacon and beacon was populated.

BLEBeacon getBeacon() const

Return this advertisement parsed as an Apple iBeacon.

Returns:

Populated BLEBeacon if valid, or a default-constructed BLEBeacon otherwise.

bool getEddystoneURL(BLEEddystoneURL &url) const

Parse this advertisement as an Eddystone-URL frame.

Parameters:

url – Output parameter populated when the advertisement contains an Eddystone-URL frame.

Returns:

True if an Eddystone-URL frame was found and url was populated.

BLEEddystoneURL getEddystoneURL() const

Return this advertisement parsed as an Eddystone-URL frame.

Returns:

Populated BLEEddystoneURL if valid, or a default-constructed BLEEddystoneURL otherwise.

bool getEddystoneTLM(BLEEddystoneTLM &tlm) const

Parse this advertisement as an Eddystone-TLM frame.

Parameters:

tlm – Output parameter populated when the advertisement contains an Eddystone-TLM frame.

Returns:

True if an Eddystone-TLM frame was found and tlm was populated.

BLEEddystoneTLM getEddystoneTLM() const

Return this advertisement parsed as an Eddystone-TLM frame.

Returns:

Populated BLEEddystoneTLM if valid, or a default-constructed BLEEddystoneTLM otherwise.

String toString() const

Get a human-readable representation of this advertised device.

Returns:

A String describing the device address, name, RSSI, and services.

BLEScan.h

class BLEScan

BLE scanner &#8212; legacy and BLE5 extended/periodic scanning.

Singleton shared handle. Access via BLE.getScan().

Public Types

using ResultHandler = std::function<void(const BLEAdvertisedDevice&)>

Callback invoked for each advertisement received during a scan.

Param device:

The advertised device that was discovered.

using CompleteHandler = std::function<void(Results&)>

Callback invoked when a scan completes (duration expires or manually stopped).

Param results:

Reference to the accumulated scan results.

using PeriodicSyncHandler = std::function<void(uint16_t syncHandle, uint8_t sid, const BTAddress &addr, BLEPhy phy, uint16_t interval)>

Callback invoked when periodic sync is established.

Param syncHandle:

Stack-assigned sync handle.

Param sid:

Advertising SID.

Param addr:

Advertiser address.

Param phy:

PHY used for the periodic train.

Param interval:

Periodic advertising interval.

using PeriodicReportHandler = std::function<void(uint16_t syncHandle, int8_t rssi, int8_t txPower, const uint8_t *data, size_t len)>

Callback invoked for each periodic advertising report.

Param syncHandle:

Sync handle identifying the periodic train.

Param rssi:

Received signal strength indicator.

Param txPower:

Transmit power level reported by the advertiser.

Param data:

Pointer to the periodic advertising payload.

Param len:

Length of the payload in bytes.

using PeriodicLostHandler = std::function<void(uint16_t syncHandle)>

Callback invoked when a periodic sync is lost (supervision timeout).

Param syncHandle:

Sync handle that was lost.

Public Functions

explicit operator bool() const

Check whether this handle references a valid scanner instance.

Returns:

true if the handle is backed by an initialized implementation, false otherwise.

void setInterval(uint16_t intervalMs)

Set the scan interval.

Parameters:

intervalMs – Interval between scan windows, in milliseconds.

void setWindow(uint16_t windowMs)

Set the scan window duration.

Parameters:

windowMs – Duration of each scan window, in milliseconds. Must be <= interval.

void setActiveScan(bool active)

Enable or disable active scanning.

Parameters:

active – If true, the scanner sends scan-request PDUs to obtain scan-response data.

void setFilterDuplicates(bool filter)

Enable or disable duplicate filtering.

Parameters:

filter – If true, suppress byte-identical reports from the same address and advertising SID while still delivering changed payloads.

void clearDuplicateCache()

Clear the host duplicate history.

The next report for each advertiser is delivered even when its bytes match the most recently cached result. The public scan results are not erased.

BTStatus start(uint32_t durationMs, bool appendToExistingResults = false)

Start scanning asynchronously.

Parameters:
  • durationMs – How long to scan, in milliseconds. 0 = scan indefinitely.

  • appendToExistingResults – If true, append to the existing result set rather than clearing it.

Returns:

BTStatus indicating success or error.

Results startBlocking(uint32_t durationMs)

Start scanning and block until the duration expires.

Parameters:

durationMs – How long to scan, in milliseconds.

Returns:

Snapshot of all discovered devices.

BTStatus stop()

Stop an in-progress scan.

Returns:

BTStatus indicating success or error.

bool isScanning() const

Check whether a scan is currently running.

Returns:

true if scanning is active, false otherwise.

void onResult(ResultHandler callback)

Register a handler called for every advertisement received.

Parameters:

callback – The handler to invoke, or nullptr to clear.

void onComplete(CompleteHandler callback)

Register a handler called when the scan completes.

Parameters:

callback – The handler to invoke, or nullptr to clear.

void resetCallbacks()

Remove all registered scan callbacks.

Results getResults() const

Retrieve a snapshot of the current scan results.

Returns:

Copy of the accumulated scan results.

void clearResults()

Discard all accumulated scan results.

void erase(const BTAddress &address)

Remove a specific device from the result set.

Parameters:

address – BLE address of the device to erase.

BTStatus startExtended(uint32_t durationMs, const ExtScanConfig *codedConfig = nullptr, const ExtScanConfig *uncodedConfig = nullptr)

Start a BLE5 extended scan.

Note

Requires BLE5_SUPPORTED.

Parameters:
  • durationMs – Scan duration in milliseconds. 0 = indefinite.

  • codedConfig – Optional scan parameters for the Coded PHY. nullptr to skip.

  • uncodedConfig – Optional scan parameters for the 1M / 2M PHY. nullptr to skip.

Returns:

BTStatus indicating success or error.

BTStatus stopExtended()

Stop a running BLE5 extended scan.

Returns:

BTStatus indicating success or error.

BTStatus createPeriodicSync(const BTAddress &addr, uint8_t sid, uint16_t skipCount = 0, uint16_t timeoutMs = 10000)

Create a synchronization with a periodic advertiser.

Parameters:
  • addr – Address of the periodic advertiser.

  • sid – Advertising SID to synchronize with.

  • skipCount – Max number of periodic events the receiver may skip. 0 = none.

  • timeoutMs – Synchronization supervision timeout in milliseconds.

Returns:

BTStatus indicating success or error.

BTStatus receivePeriodicSync(uint16_t connHandle, uint16_t skipCount = 0, uint16_t timeoutMs = 10000)

Enable Periodic Advertising Sync Transfer (PAST) receive on a connection.

A connected Broadcast Assistant (BASS) typically pushes PA sync via PAST rather than asking the delegator to scan. connHandle is the connection that will deliver HCI LE Periodic Advertising Sync Transfer Received. Pass the same handle to stopPeriodicSyncReceive to disarm.

Both backends accept the handle reported by BLEClient::getHandle() or BLEConnInfo::getHandle(); Bluedroid resolves its GATT connection id to the peer address internally. Returns NotConnected when no live link matches the handle.

Parameters:
  • connHandle – Connection handle of the assistant.

  • skipCount – Max number of periodic events the receiver may skip. 0 = none.

  • timeoutMs – Synchronization supervision timeout in milliseconds.

Returns:

BTStatus indicating success or error.

BTStatus receivePeriodicSync(const BLEConnInfo &peer, uint16_t skipCount = 0, uint16_t timeoutMs = 10000)

Enable PAST receive using a specific connection descriptor.

Role-aware variant for simultaneous GATT client+server links: it uses the descriptor’s address directly on Bluedroid, so a numeric handle collision between the two roles cannot pick the wrong link.

Parameters:
  • peer – Connection descriptor from a client/server callback or BLE.getConnections().

  • skipCount – Max number of periodic events the receiver may skip.

  • timeoutMs – Synchronization supervision timeout in milliseconds.

Returns:

BTStatus indicating success or error.

BTStatus stopPeriodicSyncReceive(uint16_t connHandle)

Disable PAST receive previously enabled by receivePeriodicSync.

Bluedroid has no dedicated disable command, so this restores the default receive parameters (the same no-sync mode NimBLE uses for cancellation).

Parameters:

connHandle – Connection handle of the assistant.

Returns:

BTStatus indicating success or error.

BTStatus stopPeriodicSyncReceive(const BLEConnInfo &peer)

Disable PAST receive using a specific connection descriptor.

Parameters:

peer – Connection descriptor from a client/server callback or BLE.getConnections().

Returns:

BTStatus indicating success or error.

BTStatus cancelPeriodicSyncCreate()

Cancel a pending periodic sync creation.

Returns:

BTStatus indicating success or error.

BTStatus terminatePeriodicSync(uint16_t syncHandle)

Terminate an established periodic sync.

Parameters:

syncHandle – Handle returned by the stack when sync was established.

Returns:

BTStatus indicating success or error.

void onPeriodicSync(PeriodicSyncHandler handler)

Register a handler for periodic sync establishment events.

Parameters:

handler – The handler to invoke, or nullptr to clear.

void onPeriodicReport(PeriodicReportHandler handler)

Register a handler for periodic advertising report events.

Parameters:

handler – The handler to invoke, or nullptr to clear.

void onPeriodicLost(PeriodicLostHandler handler)

Register a handler for periodic sync lost events.

Parameters:

handler – The handler to invoke, or nullptr to clear.

class Results

Container for a snapshot of BLE scan results.

Supports range-based for loops. Obtained from startBlocking / getResults or passed to the CompleteHandler callback.

Public Functions

inline size_t size() const

Get the number of devices in the results.

Returns:

The device count.

inline BLEAdvertisedDevice getDevice(size_t index) const

Get a device by index.

Parameters:

index – Zero-based index into the results.

Returns:

The advertised device at the given index, or an invalid handle if out of range.

inline explicit operator bool() const

Check whether the results contain any devices.

Returns:

true if at least one device was found.

void dump() const

Print all scan results to the log output.

BLEAdvertisedDevice appendOrReplace(const BLEAdvertisedDevice &device)

Insert a device or replace an existing entry with the same (address, SID).

Note

If the existing entry already has a name (merged from a prior scan response) and the incoming device has none, the existing entry is kept to avoid losing the scan-response data.

Parameters:

device – The advertised device to add or update.

inline const BLEAdvertisedDevice *begin() const

Iterator begin for range-based for loops.

Returns:

Pointer to the first device.

inline const BLEAdvertisedDevice *end() const

Iterator end for range-based for loops.

Returns:

Pointer past the last device.

struct ExtScanConfig

Scan timing and PHY choice for startExtended.

Public Members

BLEPhy phy = BLEPhy::PHY_1M

PHY to scan on.

uint16_t interval = 0

Scan interval in milliseconds (0 = use the value from setInterval()).

uint16_t window = 0

Scan window in milliseconds (0 = use the value from setWindow()).

BLESecurity.h

class BLESecurity

BLE Security configuration and bond management.

Lightweight shared handle. Access via BLE.getSecurity(). Configures IO capability, authentication mode, passkey behavior, and provides event handlers for the pairing flow.

Public Types

enum class KeyDist : uint8_t

Bitmask of SMP key types to distribute during pairing.

Values:

enumerator EncKey

Long Term Key (LTK) / encryption key.

enumerator IdKey

Identity Resolving Key (IRK).

enumerator SignKey

Connection Signature Resolving Key (CSRK).

enumerator LinkKey

BR/EDR Link Key derived from LE pairing.

using PassKeyRequestHandler = std::function<uint32_t(const BLEConnInfo &conn)>

Callback requesting the application to supply a passkey for keyboard-entry pairing.

Param conn:

Connection info for the peer requesting pairing.

Return:

The passkey (0–999999) to use for this pairing.

using PassKeyDisplayHandler = std::function<void(const BLEConnInfo &conn, uint32_t passKey)>

Callback requesting the application to display a passkey to the user.

Param conn:

Connection info for the peer requesting pairing.

Param passKey:

The passkey value to display.

using ConfirmPassKeyHandler = std::function<bool(const BLEConnInfo &conn, uint32_t passKey)>

Callback requesting the user to confirm a numeric comparison value.

Param conn:

Connection info for the peer requesting pairing.

Param passKey:

The numeric comparison value shown on both devices.

Return:

true if the user confirms the values match, false to reject.

using SecurityRequestHandler = std::function<bool(const BLEConnInfo &conn)>

Callback invoked when a peer initiates a security request.

Param conn:

Connection info for the requesting peer.

Return:

true to accept and begin pairing, false to reject.

using AuthorizationHandler = std::function<bool(const BLEConnInfo &conn, uint16_t attrHandle, bool isRead)>

Callback for runtime ATT-level authorization of reads/writes on protected attributes.

Param conn:

Connection info for the requesting peer.

Param attrHandle:

The attribute handle being accessed.

Param isRead:

true for a read operation, false for a write.

Return:

true to allow the access, false to reject with an ATT error.

using AuthCompleteHandler = std::function<void(const BLEConnInfo &conn, bool success)>

Callback invoked when authentication (pairing) completes.

Param conn:

Connection info for the peer.

Param success:

true if pairing succeeded, false on failure.

using BondStoreOverflowHandler = std::function<void(const BTAddress &oldestBond)>

Callback invoked when the bond store is full and a new bond must be saved.

Param oldestBond:

Address of the oldest bonded device that would be evicted.

Public Functions

explicit operator bool() const

Check whether this handle references a valid security instance.

Returns:

true if the handle is backed by an initialized implementation, false otherwise.

void setIOCapability(BLEIOCapability cap)

Set the I/O capability this device reports during pairing negotiation.

Parameters:

cap – What the device can display to and accept from the user, see BLEIOCapability.

bool isConfigured() const

Whether the sketch configured the association model itself.

False until setIOCapability or setAuthenticationMode is called. The LE Audio engine uses this to apply its Just Works defaults without overriding a deliberate application choice.

void setAuthenticationMode(bool bonding, bool mitm, bool secureConnection)

Set the authentication requirements for pairing.

Parameters:
  • bonding – If true, enable bonding (persist keys across connections).

  • mitm – If true, require MITM protection (passkey or numeric comparison).

  • secureConnection – If true, require LE Secure Connections (LESC).

void setPassKey(bool isStatic, uint32_t passkey = 0)

Configure static or random passkey mode.

Parameters:
  • isStatic – If true, use a fixed passkey; if false, generate a random one each pairing.

  • passkey – The fixed passkey value (0–999999). Ignored when isStatic is false.

void setStaticPassKey(uint32_t passkey)

Set a fixed static passkey for all future pairings.

Parameters:

passkey – The passkey value (0–999999).

void setRandomPassKey()

Switch to random passkey generation mode.

uint32_t getPassKey() const

Get the currently configured passkey.

Returns:

The passkey value.

void regenPassKeyOnConnect(bool enable)

Enable or disable automatic passkey regeneration on each new connection.

Note

Only effective when random passkey mode is active.

Parameters:

enable – If true, a new random passkey is generated before every pairing.

void onPassKeyRequest(PassKeyRequestHandler handler)

Register a handler invoked when the stack needs a passkey from the application.

Parameters:

handler – The handler to invoke, or nullptr to clear.

void onPassKeyDisplay(PassKeyDisplayHandler handler)

Register a handler invoked when the stack needs the application to display a passkey.

Parameters:

handler – The handler to invoke, or nullptr to clear.

void onConfirmPassKey(ConfirmPassKeyHandler handler)

Register a handler for numeric comparison confirmation.

Parameters:

handler – The handler to invoke, or nullptr to clear.

void onSecurityRequest(SecurityRequestHandler handler)

Register a handler for incoming security requests from a peer.

Parameters:

handler – The handler to invoke, or nullptr to clear.

void onAuthorization(AuthorizationHandler handler)

Register a handler for runtime ATT authorization decisions.

Parameters:

handler – The handler to invoke, or nullptr to clear.

void onAuthenticationComplete(AuthCompleteHandler handler)

Register a handler called when authentication completes.

Parameters:

handler – The handler to invoke, or nullptr to clear.

void resetCallbacks()

Remove all registered security callbacks.

void setInitiatorKeys(KeyDist keys)

Set which key types the initiator distributes during pairing.

Parameters:

keys – Bitmask of KeyDist values combined with operator|.

void setResponderKeys(KeyDist keys)

Set which key types the responder distributes during pairing.

Parameters:

keys – Bitmask of KeyDist values combined with operator|.

void setKeySize(uint8_t size)

Set the maximum encryption key size.

Parameters:

size – Key size in bytes (7–16).

void setForceAuthentication(bool force)

Require authenticated pairing for all GATT access on encrypted characteristics.

Note

When this path is used together with an active GATT client, the relative ordering of “authentication complete” and “first secure

read/write” is stack-dependent; when in doubt, wait for

onAuthenticationComplete or waitForAuthenticationComplete before relying on protected attributes.

Parameters:

force – If true, unauthenticated encrypted links are rejected.

bool getForceAuthentication() const

Get whether forced authentication is enabled.

Returns:

true if forced authentication is active, false otherwise.

std::vector<BTAddress> getBondedDevices() const

Retrieve the list of bonded device addresses.

Returns:

Vector of addresses for all currently bonded peers.

BTStatus deleteBond(const BTAddress &address)

Delete the bond for a specific device.

Note

Blocks until the bond store update completes. On success, getBondedDevices no longer includes address.

Parameters:

address – Address of the bonded device to remove.

Returns:

BTStatus indicating success or error.

BTStatus deleteAllBonds()

Delete all stored bonds.

Note

Blocks until every bond has been removed from the store. On success, getBondedDevices returns an empty list.

Returns:

BTStatus indicating success or error.

void onBondStoreOverflow(BondStoreOverflowHandler handler)

Register a handler for bond store overflow events.

Parameters:

handler – The handler to invoke, or nullptr to clear.

BTStatus startSecurity(uint16_t connHandle)

Initiate the security/pairing procedure on an existing connection.

Parameters:

connHandle – Connection handle to secure.

Returns:

BTStatus indicating success or error.

BTStatus startSecurity(const BLEConnInfo &peer)

Initiate the security/pairing procedure using a connection descriptor.

Role-aware variant for simultaneous client+server links: it uses the descriptor’s address directly on Bluedroid, avoiding numeric handle collisions between the two roles.

Parameters:

peer – Connection descriptor from a client/server callback or BLE.getConnections().

Returns:

BTStatus indicating success or error.

bool waitForAuthenticationComplete(uint32_t timeoutMs = 10000)

Block until authentication completes or the timeout elapses.

Parameters:

timeoutMs – Maximum time to wait in milliseconds.

Returns:

true if authentication completed (check the AuthCompleteHandler for success/failure), false if the timeout expired.

void resetSecurity()

Reset internal security state.

Public Static Functions

static uint32_t generateRandomPassKey()

Generate a cryptographically random 6-digit passkey.

Returns:

A random value in the range 0–999999.

BLEServer.h

class BLEServer

GATT Server handle.

Lightweight shared handle wrapping a BLEServer::Impl. Copying creates shared ownership (refcount increment). Moving transfers ownership.

Create via BLE.createServer(). Idempotent &#8212; always returns a handle to the same singleton server.

Callback threading: all server callbacks (onConnect, onDisconnect, onMtuChanged, etc.) execute on the BLE stack task — the NimBLE host task or the Bluedroid BTC task, depending on the backend. Callbacks are invoked outside the server mutex, so they may safely call other BLE APIs on the same server, but they must not block for extended periods or perform lengthy I/O.

Public Types

using ConnectHandler = std::function<void(BLEServer &server, const BLEConnInfo &conn)>

Callback invoked when a central connects.

Param server:

The server handle that accepted the connection.

Param conn:

Connection information for the new link.

using DisconnectHandler = std::function<void(BLEServer &server, const BLEConnInfo &conn, uint8_t reason)>

Callback invoked when a central disconnects.

Param server:

The server handle the central was connected to.

Param conn:

Connection information for the terminated link.

Param reason:

HCI disconnect reason code (e.g. 0x13 = Remote User Terminated).

using MtuChangedHandler = std::function<void(BLEServer &server, const BLEConnInfo &conn, uint16_t mtu)>

Callback invoked when the ATT MTU is negotiated or changed.

Param server:

The server handle.

Param conn:

Connection information.

Param mtu:

The newly agreed ATT MTU size in bytes.

using ConnParamsHandler = std::function<void(BLEServer &server, const BLEConnInfo &conn)>

Callback invoked when connection parameters are updated.

Param server:

The server handle.

Param conn:

Connection information reflecting the updated parameters.

using IdentityHandler = std::function<void(BLEServer &server, const BLEConnInfo &conn)>

Callback invoked when identity resolution completes for a peer.

Param server:

The server handle.

Param conn:

Connection information with resolved identity address.

Public Functions

BLEServer()

Construct an empty (invalid) handle; obtain a live one via BLE.createServer().

explicit operator bool() const

Check whether this handle references a valid server implementation.

Returns:

true if backed by a live Impl; false if default-constructed or moved-from.

BLEService createService(const BLEUUID &uuid, uint32_t numHandles = 15, uint8_t instId = 0)

Create a new GATT service and register it on this server.

Note

If a service with the same UUID and instId already exists, the existing handle is returned instead of creating a duplicate.

Parameters:
  • uuid – UUID of the service (16-bit, 32-bit, or 128-bit).

  • numHandles – Maximum number of attribute handles reserved for this service (includes the service declaration, characteristics, and descriptors).

  • instId – Instance ID to distinguish multiple services with the same UUID.

Returns:

A BLEService handle, or an invalid handle on failure.

BLEService getService(const BLEUUID &uuid) const

Look up an existing service by UUID.

Parameters:

uuid – UUID of the service to find.

Returns:

The matching BLEService handle, or an invalid handle if not found.

std::vector<BLEService> getServices() const

Get all services registered on this server.

Returns:

A vector of BLEService handles.

BTStatus removeService(const BLEService &service)

Remove a service from this server and from the stack.

Note

Bluedroid: deletes the GATT service via the controller.

Note

NimBLE: rebuilds the whole GATT table (no per-service delete); active connections may be affected — prefer calling when no central is connected.

Note

Returns Busy while the service is included by another service or has an outgoing value in flight. On success, retained handles to the service and its children become detached shells.

Parameters:

service – The service to remove.

Returns:

BTStatus indicating success or the error encountered.

BTStatus start()

Start the GATT server and register all added services with the stack.

Note

After BLE.end() the server is not started and has no services. Recreate the GATT tree, then call start() again.

Returns:

BTStatus indicating success or the error encountered.

bool isStarted() const

Check whether the server has been started.

Returns:

true if start() completed successfully; false otherwise.

void onConnect(ConnectHandler handler)

Register a handler called when a central connects.

Parameters:

handler – Callback to invoke on connection, or nullptr to clear.

void onDisconnect(DisconnectHandler handler)

Register a handler called when a central disconnects.

Parameters:

handler – Callback to invoke on disconnection, or nullptr to clear.

void onMtuChanged(MtuChangedHandler handler)

Register a handler called when the ATT MTU changes.

Parameters:

handler – Callback to invoke on MTU change, or nullptr to clear.

void onConnParamsUpdate(ConnParamsHandler handler)

Register a handler called when connection parameters are updated.

Parameters:

handler – Callback to invoke on parameter update, or nullptr to clear.

void onIdentity(IdentityHandler handler)

Register a handler called when peer identity is resolved.

Parameters:

handler – Callback to invoke on identity resolution, or nullptr to clear.

void resetCallbacks()

Clear all registered callback handlers.

void advertiseOnDisconnect(bool enable)

Enable or disable automatic advertising restart after a disconnection.

Parameters:

enable – true to restart advertising on disconnect; false to remain idle.

BLEAdvertising getAdvertising() const

Get the advertising handle associated with this server.

Returns:

A BLEAdvertising handle for configuring and controlling advertisements.

BTStatus startAdvertising()

Start advertising using the current advertising configuration.

Returns:

BTStatus indicating success or the error encountered.

BTStatus stopAdvertising()

Stop any active advertising.

Returns:

BTStatus indicating success or the error encountered.

size_t getConnectedCount() const

Get the number of currently connected centrals.

Returns:

The active connection count.

std::vector<BLEConnInfo> getConnections() const

Get connection information for every active link.

Returns:

A vector of BLEConnInfo for each connected peer.

BLEConnInfo getConnInfo(uint16_t connHandle) const

Get a fresh connection-info snapshot for a specific link.

Note

BLEConnInfo is a value snapshot. Re-call this to observe state that changed via a stack event (MTU exchange, connection-parameter update, encryption/bonding).

Parameters:

connHandle – Connection handle to look up.

Returns:

A valid BLEConnInfo for the link, or an invalid one (evaluates to false) if no connection with that handle exists.

BTStatus disconnect(uint16_t connHandle, uint8_t reason = 0x13)

Disconnect a connected peer.

Parameters:
  • connHandle – Connection handle of the peer to disconnect.

  • reason – HCI reason code (default 0x13 = Remote User Terminated Connection).

Returns:

BTStatus indicating success or the error encountered.

uint16_t getPeerMTU(uint16_t connHandle) const

Get the negotiated ATT MTU for a specific connection.

Parameters:

connHandle – Connection handle to query.

Returns:

The current ATT MTU size in bytes for that connection.

BTStatus updateConnParams(uint16_t connHandle, const BLEConnParams &params)

Request a connection parameter update for a specific link.

Parameters:
  • connHandle – Connection handle of the peer.

  • params – Desired connection parameters.

Returns:

BTStatus indicating success or the error encountered.

BTStatus setPhy(uint16_t connHandle, BLEPhy txPhy, BLEPhy rxPhy)

Set the preferred PHY for a connection (BLE 5.0+).

Parameters:
  • connHandle – Connection handle of the peer.

  • txPhy – Preferred transmit PHY.

  • rxPhy – Preferred receive PHY.

Returns:

BTStatus indicating success or the error encountered.

BTStatus getPhy(uint16_t connHandle, BLEPhy &txPhy, BLEPhy &rxPhy) const

Read the current PHY in use for a connection (BLE 5.0+).

Parameters:
  • connHandle – Connection handle of the peer.

  • txPhy – [out] Current transmit PHY.

  • rxPhy – [out] Current receive PHY.

Returns:

BTStatus indicating success or the error encountered.

BTStatus setDataLen(uint16_t connHandle, uint16_t txOctets, uint16_t txTime)

Set the Data Length Extension (DLE) parameters for a connection (BLE 4.2+).

Parameters:
  • connHandle – Connection handle of the peer.

  • txOctets – Preferred maximum number of payload octets per TX PDU.

  • txTime – Preferred maximum TX time in microseconds.

Returns:

BTStatus indicating success or the error encountered.

BLEStream.h

class BLEStream : public Stream

Arduino Stream interface over BLE using the Nordic UART Service (NUS).

BLEStream wraps BLE GATT operations behind the familiar Arduino Stream API. It uses the Nordic UART Service (NUS) UUID conventions for maximum interoperability with BLE serial apps (nRF Connect, Serial Bluetooth Terminal, etc.).

Multiple centrals can be connected at once in server mode: as a single Stream, writes are broadcast to every connected peer and incoming bytes from all peers are merged into one receive buffer (see peerCount). Client mode is a single peer.

Server mode — the ESP32 advertises a NUS service and accepts connections:

BLEStream bleStream;
bleStream.begin("MyDevice");          // starts advertising
if (bleStream.isConnected()) {
  bleStream.println("Hello World!");
  if (bleStream.available()) {
    String s = bleStream.readStringUntil('\n');
  }
}

Client mode — the ESP32 connects to a remote NUS server:

BLEStream bleStream;
bleStream.beginClient(remoteAddr);    // connects to the remote device
bleStream.println("Hello Server!");

Public Types

using ConnectHandler = std::function<void(const BLEConnInfo &connInfo)>

Notified when a peer connects (Nordic UART role established).

Param connInfo:

Connection metadata for the newly connected peer.

using DisconnectHandler = std::function<void(const BLEConnInfo &connInfo, uint8_t reason)>

Notified when the peer disconnects.

Param connInfo:

Connection metadata for the disconnected peer.

Param reason:

Disconnect reason code from the stack.

using PeerDataHandler = std::function<void(const BLEConnInfo &connInfo, const uint8_t *data, size_t len)>

Notified when data is received from a peer, with source attribution.

Param connInfo:

Connection metadata for the peer that sent the data.

Param data:

Received bytes.

Param len:

Length of data.

Public Functions

BLEStream(size_t rxBufferSize = 256)

Construct a BLEStream with the given receive buffer size.

Parameters:

rxBufferSize – Size (in bytes) of the internal receive ring buffer.

BTStatus begin(const String &deviceName = "BLE_Stream")

Start as a NUS server with advertising.

Note

NUS has a single owner at a time: idle BLEStream instances may coexist, but a second begin()/beginClient() while one owns NUS returns Busy. end() releases ownership.

Note

Initializes BLE if not already done, reconfigures advertising to include the NUS service UUID, and enables auto-advertise on disconnect. While active it owns NUS, legacy advertising, and server callback slots.

Note

Serialize begin(), beginClient(), end(), and destruction on the application task; concurrent lifecycle transitions are unsupported.

Parameters:

deviceName – BLE device name (used for BLE.begin and advertising)

Returns:

BTStatus::OK on success, BTStatus::InvalidState if already started, BTStatus::Busy if another owner already registered NUS, or a backend error status on failure.

BTStatus beginClient(const BTAddress &address, uint32_t timeoutMs = 5000)

Start as a NUS client and connect to a remote NUS server.

Note

Blocks until the connection completes or times out, then discovers the NUS service and subscribes to TX notifications.

Note

Serialize begin(), beginClient(), end(), and destruction on the application task; concurrent lifecycle transitions are unsupported.

Parameters:
  • address – BLE address of the remote NUS server

  • timeoutMs – Connection timeout in milliseconds

Returns:

BTStatus::OK on success, BTStatus::InvalidState if already started, BTStatus::Busy if another owner already registered NUS, BTStatus::NotFound if the NUS service or characteristics are missing, or a backend error status on connection failure.

void end()

Shut down the stream.

Note

Server mode stops legacy advertising, disconnects all server ACL peers, and removes only NUS. The BLE stack and unrelated services remain initialized.

Note

Serialize lifecycle calls on the application task. Calling end() reentrantly from this stream’s disconnect callback is safe.

bool isConnected() const

Check if at least one remote device is connected.

Note

In server mode multiple centrals may be connected simultaneously; this returns true while any of them remain connected. See peerCount.

Returns:

true if one or more peers are connected.

size_t peerCount() const

Number of currently connected peers.

Note

As a single Arduino Stream, writes are broadcast to all connected peers (GATT notifications) and received bytes from all peers are merged into the one receive buffer. Use the per-connection BLEServer callbacks if you need to distinguish individual peers.

Returns:

Peer count: 0 or 1 in client mode; 0..N in server mode.

std::vector<BLEConnInfo> peers() const

Snapshot of currently connected peers.

Returns:

In server mode, all connected centrals; in client mode, a single entry when connected, otherwise empty.

explicit operator bool() const

Check whether the stream has been started (begin or beginClient).

Returns:

true if the stream is in server or client mode.

int available() override

Return the number of bytes available to read.

Returns:

Number of bytes in the receive buffer.

int read() override

Read a single byte from the receive buffer.

Returns:

The next byte (0–255), or -1 if no data is available.

int peek() override

Peek at the next byte without removing it.

Returns:

The next byte (0–255), or -1 if no data is available.

size_t write(uint8_t c) override

Write a single byte to the remote device.

Parameters:

c – Byte to send.

Returns:

1 on success, 0 on failure or if not connected.

size_t write(const uint8_t *buffer, size_t size) override

Write a buffer of bytes to the remote device.

Note

Server mode sends via TX characteristic notifications; client mode writes to the remote RX characteristic. Each chunk is limited to (MTU - 3) bytes to fit the ATT header.

Parameters:
  • buffer – Pointer to the data to send.

  • size – Number of bytes to send.

Returns:

Number of bytes actually sent; stops on the first failed chunk.

size_t writeTo(const BLEConnInfo &peer, const uint8_t *buffer, size_t size)

Send data to a single connected peer (server mode only).

Parameters:
  • peer – Connection metadata for the target peer.

  • buffer – Data to send.

  • size – Number of bytes to send.

Returns:

Number of bytes sent, or 0 on failure, if not connected, or (server mode) if the peer has not enabled TX notifications.

void flush() override

Flush pending writes (currently a no-op for BLE).

void onConnect(ConnectHandler handler)

Register a callback for connection events.

Parameters:

handler – Function to call when a peer connects.

void onDisconnect(DisconnectHandler handler)

Register a callback for disconnection events.

Parameters:

handler – Function to call when the peer disconnects.

void onPeerData(PeerDataHandler handler)

Register a callback for attributed RX data (per peer).

Note

Fired in addition to the merged receive buffer; use this when you need to distinguish which peer sent each payload.

Parameters:

handler – Function to call when a peer writes to the RX characteristic.

void resetCallbacks()

Remove all registered callbacks.

Public Static Functions

static BLEUUID nusServiceUUID()

Get the Nordic UART Service UUID.

Returns:

The 128-bit NUS service UUID.

static BLEUUID nusRxCharUUID()

Get the NUS RX Characteristic UUID (peer writes here).

Returns:

The 128-bit NUS RX characteristic UUID.

static BLEUUID nusTxCharUUID()

Get the NUS TX Characteristic UUID (peer reads/subscribes here).

Returns:

The 128-bit NUS TX characteristic UUID.

BLEAdvTypes.h

struct BLEConnParams

Connection parameters &#8212; Bluetooth Core Spec Vol 6, Part B, 4.5.1.

All interval/timeout values are in the units specified by the Bluetooth spec.

Public Functions

bool isValid() const

Validates parameters against Bluetooth Core Spec Vol 6, Part B, Section 4.5.1.

Returns:

true if all fields are within their spec-mandated ranges (above) and the supervision timeout satisfies timeout > (1 + latency) × maxInterval × 2.

Public Members

uint16_t minInterval

6..3200 (7.5ms..4s in 1.25ms units)

uint16_t maxInterval

6..3200

uint16_t latency

0..499

uint16_t timeout

10..3200 (100ms..32s in 10ms units)

enum class BLEAdvType : uint8_t

Legacy and extended advertising PDU / event categories.

Values:

enumerator ConnectableScannable

Connectable and scannable undirected (legacy ADV_IND).

enumerator ConnectableDirected

Connectable directed, low duty cycle (legacy ADV_DIRECT_IND).

enumerator ScannableUndirected

Scannable undirected (legacy ADV_SCAN_IND).

enumerator NonConnectable

Non-connectable undirected (legacy ADV_NONCONN_IND).

enumerator DirectedHighDuty

Directed high-duty-cycle (< 3.75 ms interval, max 1.28 s).

enumerator DirectedLowDuty

Directed low-duty-cycle.

enum class BLEPhy : uint8_t

PHY values for connections and extended advertising (BLE 5).

Values:

enumerator PHY_1M

1 Mbps uncoded PHY (mandatory, BLE 4.x compatible)

enumerator PHY_2M

2 Mbps uncoded PHY (higher throughput, shorter range)

enumerator PHY_Coded

Coded PHY (125 kbps or 500 kbps, extended range).

BLEConnInfo.h

class BLEConnInfo

Stack-agnostic connection descriptor.

Replaces all backend-specific parameter types (esp_ble_gatts_cb_param_t, ble_gap_conn_desc, etc.) in callback signatures. This is a pure value type with no heap allocation &#8212; connection data is stored inline.

Backend code creates instances via the friend struct BLEConnInfoImpl.

Public Functions

BLEConnInfo()

Construct an empty (invalid) connection info object.

uint16_t getHandle() const

Connection handle assigned by the controller.

Returns:

The connection handle.

BTAddress getAddress() const

Over-the-air (OTA) peer address.

Returns:

The peer’s advertised address.

BTAddress getIdAddress() const

Identity address (after IRK resolution).

Returns:

The resolved identity address, or the OTA address if no IRK is available.

uint16_t getMTU() const

Negotiated ATT MTU for this connection.

Returns:

The current MTU in bytes.

bool isEncrypted() const

Check if the link is encrypted.

Returns:

True if the link is encrypted.

bool isAuthenticated() const

Check if authenticated pairing was used.

Returns:

True if the connection was authenticated.

bool isBonded() const

Check if a bond (LTK) exists for this peer.

Returns:

True if the peer is bonded.

uint8_t getSecurityKeySize() const

Encryption key size.

Returns:

Key size in bytes (7-16).

uint16_t getInterval() const

Connection interval in units of 1.25 ms.

Returns:

The connection interval.

uint16_t getLatency() const

Peripheral latency (number of connection events the peripheral may skip).

Returns:

The latency value.

uint16_t getSupervisionTimeout() const

Supervision timeout in units of 10 ms.

Returns:

The supervision timeout.

BLEPhy getTxPhy() const

TX PHY in use.

Note

Returns PHY_1M on non-BLE5 chips.

Returns:

The transmit PHY.

BLEPhy getRxPhy() const

RX PHY in use.

Note

Returns PHY_1M on non-BLE5 chips.

Returns:

The receive PHY.

bool isCentral() const

Check if this device is the central (initiator) of the connection.

Returns:

True if this device is the central.

bool isPeripheral() const

Check if this device is the peripheral (advertiser) of the connection.

Returns:

True if this device is the peripheral.

int8_t getRSSI() const

Last known RSSI for this connection.

Returns:

RSSI in dBm (-127 to +20), or 0 if unavailable.

explicit operator bool() const

Check if this object holds valid connection data.

Returns:

True if the connection info is valid, false otherwise.

struct Data

BLEIOCapability.h

enum class BLEIOCapability : uint8_t

Pairing input and output capability &#8212; Bluetooth Core Spec Vol 3, Part H, 2.3.2.

Describes what this device can show to a user and what it can accept from one. The two peers exchange this during pairing and the result decides which pairing method they end up using: Just Works, Passkey Entry, or Numeric Comparison.

This only describes the hardware. How strict the pairing has to be is a separate question, answered by BLESecurity::setAuthenticationMode. A board with a display and buttons can still choose to pair with Just Works, but a board that reports BLEIOCapability::NoInputNoOutput can never do better than Just Works no matter what else it asks for.

Values match the SMP I/O Capability field encoding, so they carry straight through to both host stacks.

Values:

enumerator DisplayOnly

Can show a passkey, cannot take input.

enumerator DisplayYesNo

Can show a passkey and accept a yes/no confirmation.

enumerator KeyboardOnly

Can take a typed passkey, cannot show one.

enumerator NoInputNoOutput

No usable I/O, so pairing falls back to Just Works.

enumerator KeyboardDisplay

Both a keypad and a display, so every pairing method is available.

BLEProperty.h

enum class BLEPermission : uint16_t

Attribute Access Permissions &#8212; Bluetooth Core Spec Vol 3, Part F, 3.2.5.

A permission says what a peer may do with an attribute and how well protected the link has to be before it may do it. Every name is a direction (Read, Write, or ReadWrite) followed by a security level, always in that order, so each permission has exactly one spelling.

The levels, from weakest to strongest:

  • Open: no protection at all, any peer may access it without pairing.

  • Encrypted: any pairing will do, including Just Works.

  • Authenticated: MITM-protected pairing, which also requires encryption.

  • Authorized: the application decides per access through BLESecurity::onAuthorization.

The level is always spelled out, including Open, so granting unprotected access is something you have to ask for by name rather than something you get by reaching for the shortest value.

Use | when the two directions need different levels:

// Anyone may read the value, only a bonded peer may change it.
svc.createCharacteristic(uuid, BLEProperty::Read | BLEProperty::Write, BLEPermission::ReadOpen | BLEPermission::WriteEncrypted);

The mapping to the native stacks is fail-closed: a characteristic advertises a read or write property only when the matching permission direction is declared. Notify-only and indicate-only characteristics therefore take BLEPermission::None, which grants no direct access.

Values:

enumerator None

No access permitted.

enumerator ReadOpen

Read with no security requirement at all.

enumerator ReadEncrypted

Read requires an encrypted link.

enumerator ReadAuthenticated

Read requires MITM-authenticated pairing, which implies encryption.

enumerator ReadAuthorized

Read gated by the application authorization callback.

enumerator WriteOpen

Write with no security requirement at all.

enumerator WriteEncrypted

Write requires an encrypted link.

enumerator WriteAuthenticated

Write requires MITM-authenticated pairing, which implies encryption.

enumerator WriteAuthorized

Write gated by the application authorization callback.

enumerator ReadWriteOpen

Read and write, neither with any security requirement.

enumerator ReadWriteEncrypted

Read and write both require an encrypted link.

enumerator ReadWriteAuthenticated

Read and write both require MITM-authenticated pairing.

enumerator ReadWriteAuthorized

Read and write both gated by the authorization callback.

enum class BLEProperty : uint8_t

Characteristic Properties &#8212; Bluetooth Core Spec Vol 3, Part G, 3.3.1.1.

The list of ATT operations a characteristic supports. These are independent flags rather than a hierarchy: none of them implies any other, so declare exactly the ones you want clients to be able to use.

BLEProperty::Write and BLEProperty::WriteNR in particular are two different ATT operations, not two spellings of the same one. Write is the acknowledged Write Request, where the client learns whether the write succeeded. WriteNR is the unacknowledged Write Command, which is cheaper and lower latency but reports nothing back. Declaring one does not enable the other, and declaring both is perfectly normal when you want the client to pick per write, which is what the Nordic UART RX characteristic and HID output reports do.

Combine with bitwise OR: BLEProperty::Read | BLEProperty::Notify.

Values:

enumerator Broadcast

Value can be included in advertising data.

enumerator Read

Value can be read.

enumerator WriteNR

Value can be written without response.

enumerator Write

Value can be written with response.

enumerator Notify

Value can be notified (server-initiated, no ACK).

enumerator Indicate

Value can be indicated (server-initiated, with ACK).

enumerator SignedWrite

Value supports authenticated signed writes.

enumerator ExtendedProps

Extended properties descriptor is present.

inline bool operator&(BLEPermission a, BLEPermission b)

Test whether a grants everything b asks for.

This is a containment test, not a plain bitwise AND, because the Authenticated values carry the encryption bit as well. Testing against BLEPermission::ReadAuthenticated is therefore true only for a permission that really is authenticated, and not for one that is merely encrypted, while testing a merely encrypted requirement against an authenticated permission still succeeds.

inline bool operator&(BLEProperty a, BLEProperty b)

Test whether a contains every bit of b.

inline BLEPermission operator|(BLEPermission a, BLEPermission b)

Combine permissions, typically to give each direction its own level.

inline BLEProperty operator|(BLEProperty a, BLEProperty b)
inline BLEPermission &operator|=(BLEPermission &a, BLEPermission b)
inline BLEProperty &operator|=(BLEProperty &a, BLEProperty b)

BLESubscription.h

enum class BLESubscription : uint8_t

Which server-initiated deliveries a GATT client subscribes to, and which ATT PDU arrived in a subscribe callback.

The two values are independent bits of the Client Characteristic Configuration Descriptor (0x2902; Bluetooth Core Spec Vol 3, Part G, §3.3.3.3): a characteristic that declares both the Notify and Indicate properties may be sent either way, and the server chooses per transmission. Combine with bitwise OR to receive both. A subscribe callback reports exactly one of Notify or Indicate:

chr.subscribe(BLESubscription::Notify | BLESubscription::Indicate, cb);

There is deliberately no “both” value: the combination is spelled as the OR of its parts, exactly like BLEProperty.

Values:

enumerator None

Subscribed to nothing (see unsubscribe()).

enumerator Notify

Notifications enabled (CCCD bit 0).

enumerator Indicate

Indications enabled (CCCD bit 1).

inline bool operator&(BLESubscription a, BLESubscription b)

Test whether a contains every bit of b.

inline BLESubscription operator|(BLESubscription a, BLESubscription b)
inline BLESubscription &operator|=(BLESubscription &a, BLESubscription b)

BLEUUID.h

class BLEUUID

Stack-agnostic BLE UUID type supporting 16-bit, 32-bit, and 128-bit UUIDs.

Stores internally as uint8_t[16] in big-endian (display) order. A bitSize of 0 indicates an invalid/unset UUID.

String parsing accepts:

  • ”180D” (16-bit)

  • ”0000180D” (32-bit)

  • ”0000180d-0000-1000-8000-00805f9b34fb” (128-bit with dashes)

  • ”0000180d00001000800000805f9b34fb” (128-bit without dashes)

Note

Backend conversion to NimBLE/Bluedroid native formats happens in Impl files.

Public Functions

constexpr BLEUUID() = default

Construct an invalid (empty) UUID.

BLEUUID(const char *uuid)

Construct from a string representation.

Parameters:

uuid – String in any of the accepted formats (case-insensitive); an optional “0x”/”0X” prefix is accepted. A null pointer leaves the UUID invalid.

BLEUUID(uint16_t uuid16)

Construct a 16-bit UUID.

Parameters:

uuid16 – The 16-bit UUID value.

BLEUUID(uint32_t uuid32)

Construct a 32-bit UUID.

Parameters:

uuid32 – The 32-bit UUID value.

BLEUUID(const uint8_t uuid128[16])

Construct a 128-bit UUID from raw bytes in big-endian order.

Parameters:

uuid128 – 16-byte array where uuid128[0] is the most significant byte.

BLEUUID(const uint8_t *data, size_t len, bool reverse)

Construct a 128-bit UUID from raw bytes with explicit byte order.

Parameters:
  • data – Pointer to 16 bytes of UUID data.

  • len – Must be 16 (validated at runtime).

  • reverse – If true, bytes are in little-endian order and will be reversed.

bool operator==(const BLEUUID &other) const

Test equality against another UUID.

Note

Two invalid UUIDs are never considered equal.

Parameters:

other – The UUID to compare with.

Returns:

True if both UUIDs represent the same value (compared at 128-bit width).

bool operator!=(const BLEUUID &other) const

Test inequality against another UUID.

Parameters:

other – The UUID to compare with.

Returns:

True if the UUIDs differ or either is invalid.

bool operator<(const BLEUUID &other) const

Lexicographic less-than comparison (for use in ordered containers).

Parameters:

other – The UUID to compare with.

Returns:

True if this UUID is lexicographically less than other; false if either is invalid.

String toString() const

Convert to human-readable string.

Format depends on bit size:

  • 16-bit: “180d”

  • 32-bit: “0000180d”

  • 128-bit: “0000180d-0000-1000-8000-00805f9b34fb”

Returns:

The UUID as a lowercase hex String, or “<invalid>” if the UUID is unset.

inline uint8_t bitSize() const

Get the native bit size (16, 32, or 128).

Returns:

The bit size, or 0 if the UUID is invalid/unset.

BLEUUID to128() const

Convert to full 128-bit form using the Bluetooth Base UUID.

Note

16/32-bit UUIDs already embed the Bluetooth Base UUID, so this only flips the bitSize field without changing the stored bytes.

Returns:

A new BLEUUID with bitSize() == 128, or *this unchanged if already 128-bit or invalid.

inline bool isValid() const

Check if the UUID has been set to a valid value.

Returns:

True if the UUID is valid (bitSize() != 0).

inline explicit constexpr operator bool() const

Equivalent to isValid().

Returns:

True if the UUID is valid.

inline const uint8_t *data() const

Access the internal 128-bit representation (big-endian).

Note

Only meaningful for 128-bit UUIDs or after calling to128().

Returns:

Pointer to the 16-byte internal array.

inline uint16_t toUint16() const

Get the 16-bit UUID value.

Note

Only valid when bitSize() == 16.

Returns:

The 16-bit value.

inline uint32_t toUint32() const

Get the 32-bit UUID value.

Note

Only valid when bitSize() == 32.

Returns:

The 32-bit value.

Public Static Functions

static inline BLEUUID from16(uint16_t uuid16)

Construct a 16-bit UUID at compile time.

static inline BLEUUID from128(uint8_t b0, uint8_t b1, uint8_t b2, uint8_t b3, uint8_t b4, uint8_t b5, uint8_t b6, uint8_t b7, uint8_t b8, uint8_t b9, uint8_t b10, uint8_t b11, uint8_t b12, uint8_t b13, uint8_t b14, uint8_t b15)

Construct a 128-bit UUID at compile time from 16 big-endian bytes.