BLE API

About

Warning

The BLE library was rewritten for Arduino Core 4.0 and the API might not be stable yet. While breaking changes will be avoided where possible, they may still happen in future releases. Pin your core version if you need a frozen API.

The BLE (Bluetooth Low Energy) library provides a unified, stack-agnostic API for Bluetooth Low Energy on ESP32 family chips. It supports both the NimBLE and Bluedroid host stacks transparently – the same application code compiles and runs on either backend without #ifdef guards.

Key Features:

  • Stack-agnostic API – same code compiles for NimBLE and Bluedroid

  • GATT Server and Client with shared-handle semantics (PIMPL pattern)

  • BLE 5.0 extended advertising, periodic advertising, PHY selection, Data Length Extension

  • Security: pairing, bonding, MITM protection, Secure Connections (LE SC)

  • HID-over-GATT (HOGP) device support via BLEHIDDevice

  • Beacon support: Apple iBeacon and Google Eddystone (URL + TLM)

  • Hosted BLE for ESP32-P4 via esp-hosted (runs NimBLE on a co-processor)

  • L2CAP CoC channels for high-throughput bulk data transfer (NimBLE, BLE_L2CAP_SUPPORTED)

  • BLEStream: Arduino Stream interface over BLE using the Nordic UART Service (NUS), including multi-central server mode

  • Modern C++17 API: std::function callbacks, RAII handles, BTStatus error handling

Supported SoCs

The BLE library is available on: ESP32, ESP32-S3, ESP32-S31, ESP32-C3, ESP32-C6, ESP32-C5, ESP32-H2, and ESP32-P4 (via hosted BLE).

BLE 5.0 features (extended advertising, periodic advertising, PHY selection, DLE) require a BLE 5.0-capable SoC (ESP32-S3, ESP32-S31, ESP32-C3, ESP32-C6, ESP32-C5, ESP32-H2, ESP32-P4) and are compile-time guarded by SOC_BLE_50_SUPPORTED.

Architecture and Design

PIMPL Pattern (Handle Types)

Public classes such as BLEServer, BLEClient, BLEService, BLECharacteristic, BLEDescriptor, BLEScan, BLEAdvertising, BLESecurity, BLEAdvertisedDevice, BLERemoteService, BLERemoteCharacteristic, and BLERemoteDescriptor are lightweight shared handles wrapping a std::shared_ptr<Impl>.

  • Copying a handle creates shared ownership (reference count increment).

  • Moving a handle transfers ownership (source becomes null).

  • A default-constructed handle is null – test with explicit operator bool():

BLEServer server;       // null handle
if (!server) {
    Serial.println("Handle is null");
}
server = BLE.createServer();  // now valid
BLEServer alias = server;     // shared ownership

Value Types vs Handle Types

Not every class uses the PIMPL pattern. The following are value types – they are copyable, have no shared_ptr, and behave like plain C++ structs/classes:

  • BTAddress – 6-byte Bluetooth address with type tag

  • BLEUUID – 16/32/128-bit UUID

  • BLEConnInfo – connection descriptor (inline storage)

  • BLEConnParams – connection parameters struct

  • BLEAdvertisementData – advertisement payload builder

  • BLEScan::Results – vector of BLEAdvertisedDevice

  • BTStatus – 1-byte error code with boolean conversion

Stack Selection

The BLE host stack is chosen at build time via sdkconfig:

  • CONFIG_NIMBLE_ENABLED selects NimBLE

  • CONFIG_BLUEDROID_ENABLED selects Bluedroid

The public API is identical regardless of the backend. Backend-specific code lives in per-component *.nimble.* and *.bluedroid.* source files (for example server/BLEServer.nimble.cpp), selected at compile time, and is never included by user code.

Thread Safety

  • User code typically runs on the Arduino task (loop()).

  • Stack callbacks run on the BT host task.

  • The library uses FreeRTOS task notifications (BLESync) for blocking operations (connect, discover, etc.).

  • User callbacks (onConnect, onWrite, etc.) are invoked from the BT host task – keep them fast and avoid blocking calls.

Warning

User callbacks execute on the BT host task, not the Arduino task. Long-running work inside a callback will stall the Bluetooth stack. Use flags or queues to defer heavy work to loop().

UUID Byte Order

BLEUUID stores 128-bit UUIDs in big-endian (network / display) order internally. Backend implementations convert to the stack-native byte order (little-endian for NimBLE) as needed. You never need to worry about byte order when using the public API.

Define UUIDs once at file scope and pass them to GATT/advertising APIs (all take const BLEUUID &):

static const BLEUUID SVC_UUID("4fafc201-1fb5-459e-8fcc-c5c9c331914b");
static const BLEUUID CHR_UUID("beb5483e-36e1-4688-b7f5-ea07361b26a8");

BLEService svc = server.createService(SVC_UUID);
BLECharacteristic chr = svc.createCharacteristic(CHR_UUID, ...);

String literals (for example "180A") are also accepted via the implicit BLEUUID(const char *) constructor, but named BLEUUID constants are preferred in examples and application code.

Error Handling

All operations that can fail return BTStatus. Check results with the boolean conversion:

BTStatus status = BLE.begin("MyDevice");
if (!status) {
    Serial.printf("BLE init failed: %s\n", status.toString());
}

if (status == BTStatus::Timeout) {
    Serial.println("Operation timed out");
}

BLE 5.0 Features

Extended advertising, periodic advertising, PHY selection, and Data Length Extension are available on SoCs with SOC_BLE_50_SUPPORTED (or via hosted BLE). These features are compile-time guarded by the BLE5_SUPPORTED macro defined in core/BLEGuards.h.

Getting Started

  1. Include <BLE.h> – this single header provides access to the global BLE object and all public BLE classes (BLEServer, BLEClient, BLEScan, BLECharacteristic, BLEBeacon, etc.).

  2. Call BLE.begin() to initialize the stack.

  3. Create a server, client, scanner, or advertiser as needed.

#include <BLE.h>

static const BLEUUID SVC_UUID("180A");   // Device Information Service
static const BLEUUID CHR_UUID("2A29");   // Manufacturer Name String

void setup() {
    Serial.begin(115200);

    if (!BLE.begin("MyDevice")) {
        Serial.println("BLE init failed!");
        return;
    }

    // Create a GATT server
    BLEServer server = BLE.createServer();
    BLEService svc = server.createService(SVC_UUID);
    BLECharacteristic chr = svc.createCharacteristic(
        CHR_UUID, BLEProperty::Read, BLEPermission::ReadOpen
    );
    chr.setValue("Espressif");
    server.start();

    BLE.startAdvertising();
    Serial.println("BLE server started");
}

void loop() {
    delay(1000);
}

Bluetooth Memory Reservation

The Bluetooth controller and host need dedicated RAM regions. Sketches that do not use Bluetooth should not pay for them, so initArduino() releases those regions back to the heap before setup() runs unless something in the link tells the core that Bluetooth is in use.

Linking this library is enough to make that decision: BLE.bluedroid.cpp and BLE.nimble.cpp include esp32-hal-alloc-ble-mem.h, whose constructor marks BLE as in use before app_main(). If you only ever call the BLE API, the regions stay reserved and there is nothing to configure.

Note

If your sketch calls ESP-IDF BLE APIs directly instead of going through this library – nimble_port_init(), esp_ble_mesh_init(), or similar – add the include yourself in at least one source file, or initialization will fail once the RAM has already been reclaimed:

#include "esp32-hal-alloc-ble-mem.h"

Warning

Do not use this library in a Matter sketch. When CHIPoBLE is compiled in, Matter owns the BLE host, so BLE.begin() will fail or crash after Matter.begin(). That holds even when Matter.setBLECommissioningEnabled(false) releases the BLE RAM, and after CHIPoBLE commissioning completes with the default Matter.setBLEMemoryReleaseEnabled(true). Turning CHIPoBLE off does not hand the radio over. Use Matter.onBLEMemoryReleased() if you need to allocate once that RAM is back on the heap. See Matter.

BLEClass (Global BLE Object)

The BLE global singleton is the entry point for all BLE operations. The class is BLEClass; users interact via the pre-instantiated BLE object.

Lifecycle

begin

Initialize the BLE stack with an optional device name.

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

Returns BTStatus::OK on success.

end

Deinitialize the BLE stack. Pass true to release controller memory (cannot re-initialize after). Local GATT services are dropped; createServer() still returns the same server object after a later begin(), so the sketch must recreate services before start(). User-held service and characteristic handles become detached shells: they remain non-null because the sketch still owns them, but no longer have a parent or native attribute handle. When called from a stack callback, shutdown is claimed immediately (a following begin() returns InvalidState) and the teardown body is deferred to a worker.

void end(bool releaseMemory = false);

isInitialized

bool isInitialized() const;

Returns true if begin() was called successfully and end() has not been called.

isEnding

bool isEnding() const;

Returns true once shutdown has claimed the current BLE session. Retained subsystem handles use it to reject native operations during callback-deferred teardown while end() completes on its worker.

operator bool

explicit operator bool() const;

Equivalent to isInitialized().

Identity

getAddress

BTAddress getAddress() const;

Returns the local Bluetooth address.

getDeviceName

String getDeviceName() const;

Returns the device name set during begin().

setOwnAddressType

BTStatus setOwnAddressType(BTAddress::Type type);

Set the address type used for advertising and connections (Public, Random, PublicID, RandomID).

getOwnAddressType

BTAddress::Type getOwnAddressType() const;

Returns the currently configured own-address type.

setOwnAddress

BTStatus setOwnAddress(const BTAddress &addr);

Set a custom local address.

Connections

uint16_t getConnHandle(const BTAddress &peerAddress) const;
std::vector<uint16_t> getConnHandles(const BTAddress &peerAddress) const;
std::vector<BLEConnInfo> getConnections(const BTAddress &peerAddress) const;
BLEConnInfo getConnInfo(const BTAddress &peerAddress) const;

Look up live connections by peer address (OTA, or the identity address on NimBLE). getConnHandle() returns the handle used by BLEClient::getHandle() and the connection-scoped APIs, or 0xFFFF when the peer is not connected. The address lookup normalizes volatile fields (PHY/RSSI); an ambiguous raw handle matching links to different peers is refused with NotConnected — use the owning BLEClient/BLEServer handle for a specific GATT application.

Factory Methods

createServer

BLEServer createServer();

Returns a handle to the GATT server singleton. Idempotent – always returns the same server.

createClient

BLEClient createClient();

Creates a new GATT client instance. Each client manages one connection. Multiple clients can coexist.

getScan

BLEScan getScan();

Returns the scanner singleton handle.

getAdvertising

BLEAdvertising getAdvertising();

Returns the advertising controller singleton handle.

getSecurity

BLESecurity getSecurity();

Returns the security manager singleton handle.

getAudioController

BLEAudio getAudioController();

Returns the LE Audio controller handle (declared here so the core builds without the audio library; include <BLEAudio.h> before using it). The audio subsystem is documented separately in BLE Audio.

getIsoController

BLEIso getIsoController();

Returns the isochronous transport controller handle. See the BLEIso section under Specialty Features for the CIS/BIS roles. The method is declared only when BLE_ISO_SUPPORTED is set (see core/BLEGuards.h), so guard calls with the same macro.

Power

setPower

void setPower(int8_t txPowerDbm);

Set the transmit power in dBm.

getPower

int8_t getPower() const;

Get the current transmit power in dBm.

MTU

setMTU

BTStatus setMTU(uint16_t mtu);

Set the preferred ATT MTU size. The actual MTU is negotiated per connection.

getMTU

uint16_t getMTU() const;

Get the configured preferred MTU.

IRK (Identity Resolving Key)

Useful for integrations with Home Assistant, ESPresense, and other systems that track devices by IRK.

bool getLocalIRK(uint8_t irk[16]) const;
String getLocalIRKString() const;
String getLocalIRKBase64() const;
bool getPeerIRK(const BTAddress &peer, uint8_t irk[16]) const;
String getPeerIRKString(const BTAddress &peer) const;
String getPeerIRKBase64(const BTAddress &peer) const;
String getPeerIRKReverse(const BTAddress &peer) const;

BLE 5.0 Default PHY

setDefaultPhy

BTStatus setDefaultPhy(BLEPhy txPhy, BLEPhy rxPhy);

Set the default PHY preference for new connections.

getDefaultPhy

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

Read the current default PHY settings.

Whitelist

BTStatus whiteListAdd(const BTAddress &address);
BTStatus whiteListRemove(const BTAddress &address);
bool isOnWhiteList(const BTAddress &address) const;

whiteListAdd() and whiteListRemove() block until the controller whitelist update completes. On success, isOnWhiteList() reflects the new membership.

Advertising Shortcuts

BTStatus startAdvertising();
BTStatus stopAdvertising();

Convenience methods that forward to the advertising singleton.

Stack Info

enum class Stack { NimBLE, Bluedroid };
Stack getStack() const;
const char *getStackName() const;
bool isHostedBLE() const;

Hosted BLE (ESP32-P4)

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

Configure SDIO pins for esp-hosted BLE co-processor communication. Call before begin().

Raw Event Handlers (Advanced)

using RawEventHandler = std::function<int(void *event, void *arg)>;
BTStatus setCustomGapHandler(RawEventHandler handler);
BTStatus setCustomGattcHandler(RawEventHandler handler);
BTStatus setCustomGattsHandler(RawEventHandler handler);

Register custom handlers for raw GAP, GATT client, and GATT server events. These are advanced extension points for features not directly exposed by the library.

Warning

Raw event handler signatures and event structures are stack-specific. Your handler code will be tied to the selected backend (NimBLE or Bluedroid).

GATT Server

BLEServer

Created via BLE.createServer(). Represents the local GATT server.

BLEServer server = BLE.createServer();

Construction and Validity

BLEServer();                           // default: null handle
explicit operator bool() const;        // true if valid

Service Management

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

Create a GATT service. numHandles reserves attribute handles for included characteristics and descriptors (default 15 is sufficient for most services). instId differentiates multiple instances of the same UUID.

getService
BLEService getService(const BLEUUID &uuid) const;

Retrieve a service by UUID. Returns a null handle if not found.

getServices
std::vector<BLEService> getServices() const;

Returns all registered services.

removeService
BTStatus removeService(const BLEService &service);

Remove a previously created service. Returns Busy while the service is included by another service or has an outgoing value in flight. On NimBLE the whole GATT table is rebuilt, so prefer calling when no central is connected.

Server Lifecycle

start
BTStatus start();

Register all services with the stack and start the GATT server. Call after creating services and characteristics. Returns InvalidState after LE Audio has committed the shared GATT table (the audio freeze): restage classic services before audio.begin(), not after.

isStarted
bool isStarted() const;

Callbacks

All callback setters accept std::function handlers.

Warning

Mutable handle references passed to handlers (BLEServer &, BLECharacteristic &, BLEClient &, and similar) are borrowed for that callback invocation only. They let onRead/onNotify handlers call setValue() on the object being served, but the reference must not be retained, stored, or moved from: copy the handle (a cheap shared-handle copy) if it is needed after the handler returns.

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

Called when a remote device connects to this server.

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

Called when a remote device disconnects. reason is the HCI disconnect reason code (e.g. 0x13 = remote user terminated).

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

Called when the ATT MTU is renegotiated for a connection.

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

Called when connection parameters are updated.

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

Called when a peer’s identity address is resolved (e.g. after bonding with IRK exchange).

resetCallbacks
void resetCallbacks();

Clear all registered callbacks.

Advertising Control

advertiseOnDisconnect
void advertiseOnDisconnect(bool enable);

When enabled (default), the server automatically restarts advertising after a client disconnects.

getAdvertising
BLEAdvertising getAdvertising() const;

Get the advertising controller associated with this server.

startAdvertising / stopAdvertising
BTStatus startAdvertising();
BTStatus stopAdvertising();

Connection Management

getConnectedCount
size_t getConnectedCount() const;

Returns the number of currently connected clients.

getConnections
std::vector<BLEConnInfo> getConnections() const;
BLEConnInfo getConnInfo(uint16_t connHandle) const;

Returns connection information for all connected clients, or for a single client identified by its connection handle (a null/default BLEConnInfo when the handle is not connected).

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

Disconnect a specific client by connection handle.

getPeerMTU
uint16_t getPeerMTU(uint16_t connHandle) const;

Get the negotiated MTU for a specific connection.

updateConnParams
BTStatus updateConnParams(uint16_t connHandle, const BLEConnParams &params);

Request a connection parameter update for a specific connection.

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

Set or query the PHY for a specific connection (BLE 5.0).

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

Set the Data Length Extension parameters for a specific connection.

BLEService

Created via server.createService(uuid). Represents a GATT service.

Construction and Validity

BLEService();                          // default: null handle
explicit operator bool() const;        // true if valid

Included Services

addIncludedService
void addIncludedService(const BLEService &service);

Declare another service as an Included Service of this one (GATT §3.2). The included service must be created before the server is started. Used by BLEHIDDevice to include the Battery Service in the HID Service per HIDS 1.0 §3.

Characteristic Management

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

Create a characteristic with the given UUID, properties and permissions.

Permissions are required. 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::ReadWriteEncrypted; combine values with | when each direction needs its own security level. For notify- or indicate-only characteristics pass BLEPermission::None.

getCharacteristic
BLECharacteristic getCharacteristic(const BLEUUID &uuid) const;
getCharacteristics
std::vector<BLECharacteristic> getCharacteristics() const;
removeCharacteristic
void removeCharacteristic(const BLECharacteristic &chr);

Service Lifecycle

bool isStarted() const;

isStarted() returns true after the parent server’s start() has been called, registering the service in the GATT database.

Accessors

BLEUUID getUUID() const;
uint16_t getHandle() const;
BLEServer getServer() const;

BLECharacteristic

Created via service.createCharacteristic(uuid, properties, permissions). Represents a GATT characteristic.

Construction and Validity

BLECharacteristic();                   // default: null handle
explicit operator bool() const;        // true if valid

NotifyStatus Enum

Reported by the StatusHandler callback:

enum NotifyStatus {
    SUCCESS_INDICATE,
    SUCCESS_NOTIFY,
    ERROR_INDICATE_DISABLED,
    ERROR_NOTIFY_DISABLED,
    ERROR_GATT,
    ERROR_NO_CLIENT,
    ERROR_NO_SUBSCRIBER,
    ERROR_INDICATE_TIMEOUT,
    ERROR_INDICATE_FAILURE,
};

Callbacks

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

Called before a client reads the characteristic value. Use this to update the value dynamically: calling chr.setValue() inside the handler sets the value returned in that read. The handler runs once per read, including long reads of values larger than the MTU, which are served from the value set here. The library keeps a per-connection copy of that value until the long read completes, so a concurrent setValue() cannot mix two values in one read.

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

Called after a client writes to the characteristic. Retrieve the new value with getValue().

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

Called once per notify() / indicate() call, before the payload is built, when there is at least one recipient. When notify() or indicate() is called without a payload, a value set here with chr.setValue() is the one sent to every recipient.

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

Called when a client subscribes to or unsubscribes from notifications/indications. subValue indicates the subscription type (0 = unsubscribe, 1 = notifications, 2 = indications).

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

Called with the delivery status of each notification or indication:

  • SUCCESS_NOTIFY once a notification has been sent.

  • SUCCESS_INDICATE once the client has confirmed an indication.

  • ERROR_NO_CLIENT when no client is connected, the target connection handle is not connected, or the link drops before delivery.

  • ERROR_NO_SUBSCRIBER when notify() or indicate() (without a connection handle) finds clients connected but none subscribed.

  • ERROR_NOTIFY_DISABLED / ERROR_INDICATE_DISABLED when the client targeted by notify(connHandle) / indicate(connHandle) has not enabled notifications / indications.

  • ERROR_INDICATE_TIMEOUT when an indication is not confirmed within 30 seconds (the link is then closed), ERROR_INDICATE_FAILURE when it cannot be sent, is rejected, or the per-client queue is full, and ERROR_GATT for other failures. code carries the backend error code.

The handler may run on the task that called notify() (NimBLE reports notification results before notify() returns) or on the BLE stack task.

resetCallbacks
void resetCallbacks();

Clear all registered callbacks.

Value Access

setValue
void setValue(const uint8_t *data, size_t length);
void setValue(const String &value);
void setValue(uint16_t value);
void setValue(uint32_t value);
void setValue(int value);
void setValue(float value);
void setValue(double value);

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

Set the characteristic value. The template overload writes the raw bytes of any POD type.

getValue
const uint8_t *getValue(size_t *length = nullptr) const;
String getStringValue() const;

template<typename T>
T getValue() const;

Read the characteristic value. The pointer returned by getValue() is valid until the next setValue() call. The template overload reinterprets the raw bytes as type T.

Notifications and Indications

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

Send a notification to all subscribers or to a specific connection. If data is nullptr, the current characteristic value is sent. The broadcast overload returns BTStatus::OK even when there is no recipient (reported through onStatus). notify(connHandle) returns BTStatus::NotConnected if the handle is not connected and BTStatus::InvalidState if that client has not enabled notifications.

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

Send an indication to all subscribers or to a specific connection. Indications require acknowledgment from the client, and ATT allows only one unconfirmed indication per client. The call does not block: an indication sent while another is awaiting confirmation is queued (up to 8 per client) and sent in order, and onStatus reports SUCCESS_INDICATE as each one is confirmed. indicate(connHandle) returns BTStatus::NotConnected / BTStatus::InvalidState like notify(connHandle), and BTStatus::Busy when the queue for that client is full.

An indication the stack refuses because it is still waiting for the client to confirm one the stack sent itself (such as Service Changed) is retried until the 30 s ATT transaction timeout passes. Notifications sent while an indication is awaiting confirmation on the same characteristic are sent immediately on both backends.

Properties and Permissions

BLEProperty getProperties() const;
void setPermissions(BLEPermission permissions);
BLEPermission getPermissions() const;

Descriptor Management

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

Create a descriptor under this characteristic.

getDescriptor
BLEDescriptor getDescriptor(const BLEUUID &uuid) const;
getDescriptors
std::vector<BLEDescriptor> getDescriptors() const;
removeDescriptor
void removeDescriptor(const BLEDescriptor &desc);

Subscription State

size_t getSubscribedCount() const;
std::vector<uint16_t> getSubscribedConnections() const;
bool isSubscribed(uint16_t connHandle) const;

Accessors

BLEUUID getUUID() const;
uint16_t getHandle() const;
BLEService getService() const;
void setDescription(const String &desc);
String toString() const;

setDescription() is a convenience that creates or updates a User Description descriptor (0x2901).

BLEDescriptor

Created via characteristic.createDescriptor(uuid) or static factory methods.

Constructors

BLEDescriptor();                                         // null handle
BLEDescriptor(const BLEUUID &uuid, uint16_t maxLength = 100);  // standalone descriptor
explicit operator bool() const;

Callbacks

using ReadHandler = std::function<void(BLEDescriptor &desc, const BLEConnInfo &conn)>;
using WriteHandler = std::function<void(BLEDescriptor &desc, const BLEConnInfo &conn)>;
void onRead(ReadHandler handler);
void onWrite(WriteHandler handler);
resetCallbacks
void resetCallbacks();

Clear all registered callbacks.

Value Access

void setValue(const uint8_t *data, size_t length);
void setValue(const String &value);
const uint8_t *getValue(size_t *length = nullptr) const;
size_t getLength() const;

Permissions

void setPermissions(BLEPermission perms);

Accessors

BLEUUID getUUID() const;
uint16_t getHandle() const;
BLECharacteristic getCharacteristic() const;
String toString() const;

Static Factories

createUserDescription
static BLEDescriptor createUserDescription(const String &description);

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

createCCCD
static BLEDescriptor createCCCD();

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

Note

A CCCD is automatically created for characteristics with Notify or Indicate properties. You rarely need to create one manually.

createPresentationFormat
static BLEDescriptor createPresentationFormat();

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

User Description Convenience (0x2901)

void setUserDescription(const String &description);
String getUserDescription() const;

CCCD Convenience (0x2902)

bool getNotifications() const;
bool getIndications() const;
void setNotifications(bool enable);
void setIndications(bool enable);

Presentation Format Convenience (0x2904)

void setFormat(uint8_t format);
void setExponent(int8_t exponent);
void setUnit(uint16_t unit);
void setNamespace(uint8_t ns);
void setFormatDescription(uint16_t description);

uint8_t getFormat() const;
int8_t getExponent() const;
uint16_t getUnit() const;
uint8_t getNamespace() const;
uint16_t getFormatDescription() const;

FORMAT Constants

static constexpr uint8_t FORMAT_BOOLEAN = 1;
static constexpr uint8_t FORMAT_UINT8   = 4;
static constexpr uint8_t FORMAT_UINT16  = 6;
static constexpr uint8_t FORMAT_UINT32  = 8;
static constexpr uint8_t FORMAT_SINT8   = 12;
static constexpr uint8_t FORMAT_SINT16  = 14;
static constexpr uint8_t FORMAT_SINT32  = 16;
static constexpr uint8_t FORMAT_FLOAT32 = 20;
static constexpr uint8_t FORMAT_FLOAT64 = 21;
static constexpr uint8_t FORMAT_UTF8    = 25;
static constexpr uint8_t FORMAT_UTF16   = 26;

Type Queries

bool isUserDescription() const;    // UUID == 0x2901
bool isCCCD() const;               // UUID == 0x2902
bool isPresentationFormat() const;  // UUID == 0x2904

GATT Client

BLEClient

Created via BLE.createClient(). Each instance manages one connection to a remote peripheral. Multiple BLEClient instances can coexist for multi-connection scenarios.

BLEClient client = BLE.createClient();

Construction and Validity

BLEClient();                           // default: null handle
explicit operator bool() const;        // true if valid

Connecting

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

Synchronous connect. Blocks until the connection is established or the timeout expires. The PHY-aware overloads (BLE 5.0) specify the preferred PHY for the initial connection.

Note

onConnect is delivered before a blocking connect() returns. The ATT MTU exchange also completes before connect() returns (required on Bluedroid so a follow-up GATT/GAP call cannot race the pending exchange). onMtuChanged still fires after onConnect. Do not read the negotiated MTU inside onConnect – use onMtuChanged or getMTU() after connect() returns. connectAsync() does not auto-exchange MTU; call setMTU() after you observe onConnect.

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

Initiate a connection without blocking. Use the onConnect callback to know when the connection is established. Unlike blocking connect(), this path does not automatically exchange MTU.

cancelConnect
BTStatus cancelConnect();

Cancel a pending connection attempt.

disconnect
BTStatus disconnect();

Disconnect from the remote device.

isConnected
bool isConnected() const;
secureConnection
BTStatus secureConnection();

Initiate security/pairing on the existing connection.

Service Discovery

getService
BLERemoteService getService(const BLEUUID &uuid) const;

Discover and return a specific service by UUID. Triggers service discovery if not already cached.

getServices
std::vector<BLERemoteService> getServices() const;

Returns all discovered services.

discoverServices
BTStatus discoverServices();

Explicitly trigger GATT service discovery. Normally called automatically by getService().

Convenience Read/Write

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

Read or write a characteristic value by service and characteristic UUID in a single call.

Callbacks

using ConnectHandler = std::function<void(BLEClient &client, const BLEConnInfo &conn)>;
using DisconnectHandler = std::function<void(BLEClient &client, const BLEConnInfo &conn, uint8_t reason)>;
using ConnectFailHandler = std::function<void(BLEClient &client, int reason)>;
using MtuChangedHandler = std::function<void(BLEClient &client, const BLEConnInfo &conn, uint16_t mtu)>;
using ConnParamsReqHandler = std::function<bool(BLEClient &client, const BLEConnParams &params)>;
using IdentityHandler = std::function<void(BLEClient &client, const BLEConnInfo &conn)>;

void onConnect(ConnectHandler handler);
void onDisconnect(DisconnectHandler handler);
void onConnectFail(ConnectFailHandler handler);
void onMtuChanged(MtuChangedHandler handler);
void onConnParamsUpdateRequest(ConnParamsReqHandler handler);
void onIdentity(IdentityHandler handler);
resetCallbacks
void resetCallbacks();

Clear all registered callbacks.

Note

onConnParamsUpdateRequest returns bool – return true to accept the parameters, false to reject. This callback is NimBLE-only; Bluedroid has no pre-accept hook for connection-parameter updates, so the handler is never invoked on that backend.

MTU and Connection Info

void setMTU(uint16_t mtu);
uint16_t getMTU() const;
int8_t getRSSI() const;
BTAddress getPeerAddress() const;
uint16_t getHandle() const;
BLEConnInfo getConnInfo() const;

Connection Parameters and PHY

BTStatus updateConnParams(const BLEConnParams &params);
BTStatus setPhy(BLEPhy txPhy, BLEPhy rxPhy);
BTStatus getPhy(BLEPhy &txPhy, BLEPhy &rxPhy) const;
BTStatus setDataLen(uint16_t txOctets, uint16_t txTime);

toString

String toString() const;

BLERemoteService

Represents a GATT service discovered on a remote device. Obtained via BLEClient::getService() or BLEClient::getServices().

BLERemoteService();                    // default: null handle
explicit operator bool() const;

Characteristic Access

BLERemoteCharacteristic getCharacteristic(const BLEUUID &uuid) const;
std::vector<BLERemoteCharacteristic> getCharacteristics() const;

Convenience Read/Write

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

Accessors

BLEClient getClient() const;
BLEUUID getUUID() const;
uint16_t getHandle() const;
String toString() const;

BLERemoteCharacteristic

Represents a GATT characteristic on a remote device. Obtained via BLERemoteService::getCharacteristic().

BLERemoteCharacteristic();             // default: null handle
explicit operator bool() const;

Reading Values

String readValue(uint32_t timeoutMs = 3000);
uint8_t readUInt8(uint32_t timeoutMs = 3000);
uint16_t readUInt16(uint32_t timeoutMs = 3000);
uint32_t readUInt32(uint32_t timeoutMs = 3000);
float readFloat(uint32_t timeoutMs = 3000);
size_t readValue(uint8_t *buf, size_t bufLen, uint32_t timeoutMs = 3000);
const uint8_t *readRawData(size_t *len = nullptr) const;

The typed read methods (readUInt8, readFloat, etc.) perform a remote GATT read and interpret the result. readRawData() returns the cached raw bytes from the last read without triggering a new one.

Writing Values

BTStatus writeValue(const uint8_t *data, size_t len, bool withResponse = true);
BTStatus writeValue(const String &value, bool withResponse = true);
BTStatus writeValue(uint8_t value, bool withResponse = true);

Set withResponse to false for write-without-response (faster, no acknowledgment).

Capability Checks

bool canRead() const;
bool canWrite() const;
bool canWriteNoResponse() const;
bool canNotify() const;
bool canIndicate() const;
bool canBroadcast() const;

Subscribe / Unsubscribe

using NotifyCallback = std::function<void(BLERemoteCharacteristic &chr, const uint8_t *, size_t, BLESubscription)>;
BTStatus subscribe(BLESubscription mode, NotifyCallback callback = nullptr);
BTStatus unsubscribe();

Subscribe to notifications (BLESubscription::Notify), indications (BLESubscription::Indicate), or both simultaneously (BLESubscription::Notify | BLESubscription::Indicate, which writes 0x0003 to the CCCD). The selected bits replace any previous subscription; BLESubscription::None is rejected (use unsubscribe()). The callback receives the characteristic, data pointer, data length, and a BLESubscription value saying whether the value arrived as a notification or an indication (never None, never both bits for a single delivery).

Note

The callback runs on the BLE stack task. Do not call blocking GATT operations (readValue(), confirmed writeValue(), subscribe()) on the characteristic from inside it: they wait for a response that the same task delivers and stall until they time out. A read also replaces the buffer the data pointer refers to. Defer such work to another task.

Descriptor Access

BLERemoteDescriptor getDescriptor(const BLEUUID &uuid) const;
std::vector<BLERemoteDescriptor> getDescriptors() const;

Accessors

BLERemoteService getRemoteService() const;
BLEUUID getUUID() const;
uint16_t getHandle() const;
String toString() const;

BLERemoteDescriptor

Represents a GATT descriptor on a remote device. Obtained via BLERemoteCharacteristic::getDescriptor().

BLERemoteDescriptor();                 // default: null handle
explicit operator bool() const;

Reading Values

String readValue(uint32_t timeoutMs = 3000);
uint8_t readUInt8(uint32_t timeoutMs = 3000);
uint16_t readUInt16(uint32_t timeoutMs = 3000);
uint32_t readUInt32(uint32_t timeoutMs = 3000);
const uint8_t *readRawData(size_t *len = nullptr) const;

Presentation Format Convenience (0x2904)

uint8_t getFormat() const;
int8_t getExponent() const;
uint16_t getUnit() const;
uint8_t getNamespace() const;
uint16_t getFormatDescription() const;

bool isUserDescription() const;    // UUID == 0x2901
bool isCCCD() const;               // UUID == 0x2902
bool isPresentationFormat() const;  // UUID == 0x2904

The getFormat() / getExponent() / getUnit() / getNamespace() / getFormatDescription() getters parse the cached 7-byte Presentation Format payload populated by readValue().

Writing Values

BTStatus writeValue(const uint8_t *data, size_t len, bool withResponse = true);
BTStatus writeValue(const String &value, bool withResponse = true);
BTStatus writeValue(uint8_t value, bool withResponse = true);

Accessors

BLERemoteCharacteristic getRemoteCharacteristic() const;
BLEUUID getUUID() const;
uint16_t getHandle() const;
String toString() const;

Scanning

BLEScan

Obtained via BLE.getScan(). Supports legacy scanning and BLE 5.0 extended/periodic scanning.

BLEScan scan = BLE.getScan();

Construction and Validity

BLEScan();                             // default: null handle
explicit operator bool() const;

Configuration

setInterval
void setInterval(uint16_t intervalMs);

Set the scan interval in milliseconds.

setWindow
void setWindow(uint16_t windowMs);

Set the scan window in milliseconds. Must be <= interval.

setActiveScan
void setActiveScan(bool active);

Enable active scanning (sends scan requests to get scan response data).

setFilterDuplicates
void setFilterDuplicates(bool filter);

When enabled, duplicate advertisements from the same device are filtered out.

clearDuplicateCache
void clearDuplicateCache();

Clear the duplicate advertisement filter cache.

Starting and Stopping

start
BTStatus start(uint32_t durationMs, bool appendToExistingResults = false);

Start scanning for durationMs milliseconds (non-blocking); 0 scans indefinitely. Set appendToExistingResults to true to append to existing results instead of clearing them.

startBlocking
BLEScan::Results startBlocking(uint32_t durationMs);

Start scanning and block until complete. Returns the scan results directly.

stop
BTStatus stop();

Stop an active scan.

isScanning
bool isScanning() const;

Callbacks

onResult
void onResult(std::function<void(const BLEAdvertisedDevice &)> callback);

Called for each advertisement received during scanning.

onComplete
void onComplete(std::function<void(BLEScan::Results &)> callback);

Called when a scan completes (duration expired).

resetCallbacks
void resetCallbacks();

Clear all registered callbacks.

Results Management

BLEScan::Results getResults() const;
void clearResults();
void erase(const BTAddress &address);

Extended Scanning (BLE 5.0)

struct ExtScanConfig {
    BLEPhy phy = BLEPhy::PHY_1M;
    uint16_t interval = 0;
    uint16_t window = 0;
};

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

Extended scanning supports separate configuration for coded PHY and uncoded PHY.

Periodic Sync (BLE 5.0)

BTStatus createPeriodicSync(const BTAddress &addr, uint8_t sid,
                            uint16_t skipCount = 0, uint16_t timeoutMs = 10000);
BTStatus receivePeriodicSync(uint16_t connHandle,
                             uint16_t skipCount = 0, uint16_t timeoutMs = 10000);
BTStatus receivePeriodicSync(const BLEConnInfo &peer,
                             uint16_t skipCount = 0, uint16_t timeoutMs = 10000);
BTStatus stopPeriodicSyncReceive(uint16_t connHandle);
BTStatus stopPeriodicSyncReceive(const BLEConnInfo &peer);
BTStatus cancelPeriodicSyncCreate();
BTStatus terminatePeriodicSync(uint16_t syncHandle);

Synchronize to a periodic advertiser identified by address and advertising SID. cancelPeriodicSyncCreate() aborts a pending create, and terminatePeriodicSync() tears down an established sync.

receivePeriodicSync() enables Periodic Advertising Sync Transfer (PAST) receive on a connection: a connected Broadcast Assistant (BASS) typically pushes the PA sync via PAST instead of asking the Scan Delegator to scan. Both backends accept the handle reported by BLEClient::getHandle() or BLEConnInfo::getHandle() and return BTStatus::NotConnected when no live link matches. The BLEConnInfo overload is the role-aware variant for simultaneous GATT client and server links; on Bluedroid it uses the descriptor’s address directly so a numeric handle collision between roles cannot pick the wrong link. The stopPeriodicSyncReceive() overloads disable PAST receive again (Bluedroid has no dedicated disable command, so it restores the default no-sync receive parameters).

Periodic Sync Callbacks
using PeriodicSyncHandler = std::function<void(uint16_t syncHandle, uint8_t sid,
                                               const BTAddress &addr, BLEPhy phy,
                                               uint16_t interval)>;
using PeriodicReportHandler = std::function<void(uint16_t syncHandle, int8_t rssi,
                                                 int8_t txPower, const uint8_t *data,
                                                 size_t len)>;
using PeriodicLostHandler = std::function<void(uint16_t syncHandle)>;

void onPeriodicSync(PeriodicSyncHandler handler);
void onPeriodicReport(PeriodicReportHandler handler);
void onPeriodicLost(PeriodicLostHandler handler);

BLEAdvertisedDevice

Represents a single BLE device discovered during scanning. Shared handle with parsed advertisement data.

Construction and Validity

BLEAdvertisedDevice();                 // default: null handle
explicit operator bool() const;

Basic Information

BTAddress getAddress() const;
BTAddress::Type getAddressType() const;
String getName() const;
int8_t getRSSI() const;
int8_t getTXPower() const;
uint16_t getAppearance() const;
BLEAdvType getAdvType() const;

Manufacturer Data

const uint8_t *getManufacturerData(size_t *len) const;
String getManufacturerDataString() const;
uint16_t getManufacturerCompanyId() const;

Service UUIDs

size_t getServiceUUIDCount() const;
BLEUUID getServiceUUID(size_t index = 0) const;
bool haveServiceUUID() const;
bool isAdvertisingService(const BLEUUID &uuid) const;

Service Data

size_t getServiceDataCount() const;
const uint8_t *getServiceData(size_t index, size_t *len) const;
String getServiceDataString(size_t index = 0) const;
BLEUUID getServiceDataUUID(size_t index = 0) const;
bool haveServiceData() const;

Raw Payload

const uint8_t *getPayload() const;
size_t getPayloadLength() const;

Presence Checks

bool haveName() const;
bool haveRSSI() const;
bool haveTXPower() const;
bool haveAppearance() const;
bool haveManufacturerData() const;
bool havePreferredParams() const;

Preferred Connection Parameters (AD 0x12)

uint16_t getMinPreferred() const;
uint16_t getMaxPreferred() const;

Returns the Slave Connection Interval Range (AD type 0x12) bounds in 1.25 ms units when havePreferredParams() is true, or 0 otherwise.

Connectable / Scannable / Directed

bool isConnectable() const;
bool isScannable() const;
bool isDirected() const;
bool isLegacyAdvertisement() const;

BLE 5.0 Extended Info

BLEPhy getPrimaryPhy() const;
BLEPhy getSecondaryPhy() const;
uint8_t getAdvSID() const;
uint16_t getPeriodicInterval() const;

Frame Type and Beacon / Eddystone Helpers

enum FrameType { Unknown, IBeacon, EddystoneUUID, EddystoneURL, EddystoneTLM };
FrameType getFrameType() const;

BLEBeacon getBeacon() const;
bool getBeacon(BLEBeacon &beacon) const;
BLEEddystoneURL getEddystoneURL() const;
bool getEddystoneURL(BLEEddystoneURL &url) const;
BLEEddystoneTLM getEddystoneTLM() const;
bool getEddystoneTLM(BLEEddystoneTLM &tlm) const;

toString

String toString() const;

BLEScan::Results

Container for BLE scan results, nested in BLEScan. Supports range-based for loops.

explicit operator bool() const;         // true if non-empty
size_t size() const;
BLEAdvertisedDevice getDevice(size_t index) const;
void dump() const;                      // log all results

const BLEAdvertisedDevice *begin() const;
const BLEAdvertisedDevice *end() const;

Example:

BLEScan::Results results = scan.startBlocking(5000);
for (const auto &device : results) {
    Serial.printf("Found: %s RSSI=%d\n",
                   device.getName().c_str(),
                   device.getRSSI());
}

Advertising

BLEAdvertising

Obtained via BLE.getAdvertising() or server.getAdvertising(). Supports legacy, extended, and periodic advertising.

Construction and Validity

BLEAdvertising();                      // default: null handle
explicit operator bool() const;

Legacy Advertising

Service UUIDs
void addServiceUUID(const BLEUUID &uuid);
void removeServiceUUID(const BLEUUID &uuid);
void clearServiceUUIDs();
Configuration
void setName(const String &name);
void setScanResponse(bool enable);
void setType(BLEAdvType type);
void setDirectedAddress(const BTAddress &address);
BTAddress getDirectedAddress() const;
void setInterval(uint16_t minMs, uint16_t maxMs);
void setMinPreferred(uint16_t minPreferred);
void setMaxPreferred(uint16_t maxPreferred);
void setTxPower(bool include);
void setAppearance(uint16_t appearance);
void setScanFilter(bool scanRequestWhitelistOnly, bool connectWhitelistOnly);
void reset();

Note

When scan response is enabled (default after reset()), the device name is placed in the scan response payload per CSS Part A §1.2, keeping the primary advertising data free for flags, service UUIDs, and appearance. When scan response is disabled via setScanResponse(false), the name is included in the primary advertising data instead. This behavior is consistent across both NimBLE and Bluedroid backends.

Note

setMinPreferred / setMaxPreferred emit the Slave Connection Interval Range AD structure (0x12) in the primary advertising payload when either bound is non-zero (a zero side copies the other). Connection parameters are still negotiated post-connect via L2CAP; the AD is only a hint to centrals.

Note

setDirectedAddress sets the peer address used as InitA in directed advertising PDUs (BLEAdvType::DirectedHighDuty, DirectedLowDuty, or ConnectableDirected). Such types require a non-zero address before start(); a zero address clears the stored peer. Use getDirectedAddress() to read the stored InitA (a zero address when none was set).

Custom Advertisement Data
void setAdvertisementData(const BLEAdvertisementData &data);
void setScanResponseData(const BLEAdvertisementData &data);
Start / Stop
BTStatus start(uint32_t durationMs = 0);
BTStatus stop();
bool isAdvertising() const;

Pass durationMs = 0 for indefinite advertising. Finite durations above the HCI 16-bit 10 ms unit field (about 655.35 s) return BTStatus::InvalidParam. High-duty directed advertising is limited to 1.28 s, and directed types started with a zero setDirectedAddress() also return InvalidParam.

isAdvertising() is 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.

Extended Advertising (BLE 5.0)

Extended advertising is configured per instance with individual setters (mirroring the legacy setter style) rather than a single config struct. Each advertising set is identified by an instance index (0, 1, 2, …), so several sets can run in parallel. Configure the instance, set its data, then start it.

Note

These APIs require a BLE 5.0-capable SoC (ESP32-C3, S3, C6, H2, …) with extended advertising enabled in the backend (CONFIG_BT_NIMBLE_EXT_ADV for NimBLE, CONFIG_BT_BLE_50_FEATURES_SUPPORTED for Bluedroid). On builds without BLE 5 support every method logs a warning and returns BTStatus::NotSupported; the void setters are no-ops. Always check the returned BTStatus.

Setters
void setExtType(uint8_t instance, BLEAdvType type);
void setExtPhy(uint8_t instance, BLEPhy primaryPhy, BLEPhy secondaryPhy);
void setExtTxPower(uint8_t instance, int8_t txPower);       // 127 = controller default
void setExtInterval(uint8_t instance, uint16_t minInterval, uint16_t maxInterval);
void setExtChannelMap(uint8_t instance, uint8_t channelMap);
void setExtSID(uint8_t instance, uint8_t sid);
void setExtAnonymous(uint8_t instance, bool anonymous);
void setExtIncludeTxPower(uint8_t instance, bool include);
void setExtScanReqNotify(uint8_t instance, bool enable);
Data and lifecycle
BTStatus setExtAdvertisementData(uint8_t instance, const BLEAdvertisementData &data);
BTStatus setExtScanResponseData(uint8_t instance, const BLEAdvertisementData &data);
BTStatus setExtInstanceAddress(uint8_t instance, const BTAddress &addr);
BTStatus startExtended(uint8_t instance, uint32_t durationMs = 0, uint8_t maxEvents = 0);
BTStatus stopExtended(uint8_t instance);
BTStatus removeExtended(uint8_t instance);
BTStatus clearExtended();

Periodic Advertising (BLE 5.0)

Periodic advertising attaches to an existing extended advertising instance. Configure the extended instance first, then set the periodic parameters and data and start it. As with extended advertising, these methods are per instance and return BTStatus::NotSupported on non-BLE-5 builds.

void setPeriodicAdvInterval(uint8_t instance, uint16_t minInterval, uint16_t maxInterval);
void setPeriodicAdvTxPower(uint8_t instance, bool include);
BTStatus setPeriodicAdvData(uint8_t instance, const BLEAdvertisementData &data);
BTStatus startPeriodicAdv(uint8_t instance);
BTStatus stopPeriodicAdv(uint8_t instance);

Event Handler

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

Called when an advertising duration expires or max events are reached.

resetCallbacks
void resetCallbacks();

Clear all registered callbacks.

BLEAdvertisementData

Builder for raw BLE advertisement data payloads. Constructs AD structures per Bluetooth Core Spec Vol 3, Part C, Section 11.

void setFlags(BLEAdvFlag flags);
void addServiceUUID(const BLEUUID &uuid);
void setPartialServices(const BLEUUID &uuid);
void setServiceData(const BLEUUID &uuid, const uint8_t *data, size_t len);
void setManufacturerData(uint16_t companyId, const uint8_t *data, size_t len);
void setName(const String &name, bool complete = true);
void setBroadcastName(const String &name);
void setAppearance(uint16_t appearance);
void setPreferredParams(uint16_t minInterval, uint16_t maxInterval);
void setTxPower(int8_t txPower);
void addField(uint8_t type, const uint8_t *data, size_t len);
void addRaw(const uint8_t *data, size_t len);
void clear();

const uint8_t *data() const;
size_t length() const;

Tip

Use BLEAdvertisementData when you need full control over the advertisement payload. For simple cases, use the convenience methods on BLEAdvertising directly.

Security

BLESecurity

Obtained via BLE.getSecurity(). Configures security parameters, manages bonds, and provides event handlers for the pairing flow.

BLESecurity sec = BLE.getSecurity();

Construction and Validity

BLESecurity();                         // default: null handle
explicit operator bool() const;

IO Capability and Authentication

setIOCapability
void setIOCapability(BLEIOCapability cap);

Declare what this device can show to and accept from a user during pairing. See BLEIOCapability.

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

Configure the authentication requirements:

  • bonding – persist keys for future reconnection

  • mitm – require Man-In-The-Middle protection (passkey or numeric comparison)

  • secureConnection – require LE Secure Connections (ECDH-based pairing)

Passkey Management

void setPassKey(bool isStatic, uint32_t passkey = 0);
void setStaticPassKey(uint32_t passkey);
void setRandomPassKey();
uint32_t getPassKey() const;
static uint32_t generateRandomPassKey();
void regenPassKeyOnConnect(bool enable);

setStaticPassKey() sets a fixed 6-digit passkey. setRandomPassKey() generates a random one. regenPassKeyOnConnect(true) generates a new random passkey for each new pairing attempt.

Security Callbacks

onPassKeyRequest
using PassKeyRequestHandler = std::function<uint32_t(const BLEConnInfo &conn)>;
void onPassKeyRequest(PassKeyRequestHandler handler);

Called when the stack needs a passkey from the user (keyboard-only devices). Return the passkey entered.

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

Called when the stack wants to display a passkey for the user to enter on the peer device.

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

Called during numeric comparison pairing. Display the passkey and return true if the user confirms it matches.

onSecurityRequest
using SecurityRequestHandler = std::function<bool(const BLEConnInfo &conn)>;
void onSecurityRequest(SecurityRequestHandler handler);

Called when a peer initiates a security request. Return true to accept.

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

Called when an attribute access requires authorization. Return true to allow.

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

Called when the authentication/pairing process completes.

resetCallbacks
void resetCallbacks();

Clear all registered callbacks.

Key Distribution

KeyDist Enum
enum class KeyDist : uint8_t {
    EncKey  = 0x01,   // Encryption key (LTK)
    IdKey   = 0x02,   // Identity key (IRK)
    SignKey = 0x04,   // Signing key (CSRK)
    LinkKey = 0x08,   // Link key (BR/EDR)
};

Combine with bitwise OR: KeyDist::EncKey | KeyDist::IdKey.

void setInitiatorKeys(KeyDist keys);
void setResponderKeys(KeyDist keys);
void setKeySize(uint8_t size);

Force Authentication

void setForceAuthentication(bool force);
bool getForceAuthentication() const;

When enabled, all GATT attribute access requires an authenticated connection.

Bond Management

std::vector<BTAddress> getBondedDevices() const;
BTStatus deleteBond(const BTAddress &address);
BTStatus deleteAllBonds();

deleteBond() and deleteAllBonds() block until the bond store update completes. On success, getBondedDevices() no longer includes the removed peer(s).

Bond Store Overflow
using BondStoreOverflowHandler = std::function<void(const BTAddress &oldestBond)>;
void onBondStoreOverflow(BondStoreOverflowHandler handler);

Called when the bond store is full and a new bond needs to be stored.

Security Flow Methods

BTStatus startSecurity(uint16_t connHandle);
BTStatus startSecurity(const BLEConnInfo &peer);
bool waitForAuthenticationComplete(uint32_t timeoutMs = 10000);
void resetSecurity();

startSecurity() initiates pairing on a specific connection (by handle, or by peer via the BLEConnInfo overload, which refuses ambiguous raw handles to the wrong link). waitForAuthenticationComplete() blocks until pairing completes or times out.

Shared Types

BTAddress

Unified Bluetooth address type for both BLE and BT Classic.

Internally stores 6 bytes in LSB-first (Bluetooth standard) order. Displayed as "AA:BB:CC:DD:EE:FF" (MSB-first, human-readable).

Type Enum

enum Type : uint8_t {
    Public   = 0,
    Random   = 1,
    PublicID = 2,
    RandomID = 3,
};

Constructors

BTAddress();                                        // zero address
BTAddress(const uint8_t addr[6], Type type = Public);  // from raw bytes (LSB-first)
BTAddress(const char *str);                         // from "AA:BB:CC:DD:EE:FF" or "AABBCCDDEEFF"
BTAddress(const String &str);

Methods

bool operator==(const BTAddress &other) const;
bool operator!=(const BTAddress &other) const;
bool operator<(const BTAddress &other) const;
explicit operator bool() const;         // true if non-zero
const uint8_t *data() const;            // internal 6-byte array (LSB-first)
Type type() const;
String toString(bool uppercase = false) const;
bool isZero() const;

BTStatus

Unified error/status type. 1 byte. explicit operator bool() returns true on success.

Status Codes

enum Code : int8_t {
    OK               =  0,
    Fail             = -1,
    NotInitialized   = -2,
    InvalidParam     = -3,
    InvalidState     = -4,
    NoMemory         = -5,
    Timeout          = -6,
    NotConnected     = -7,
    AlreadyConnected = -8,
    NotFound         = -9,
    AuthFailed       = -10,
    PermissionDenied = -11,
    Busy             = -12,
    NotSupported     = -13,
};

Methods

BTStatus();                     // defaults to OK
BTStatus(Code c);
explicit operator bool() const; // true when OK
bool operator!() const;
bool operator==(const BTStatus &o) const;
bool operator!=(const BTStatus &o) const;
Code code() const;
const char *toString() const;

Usage:

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

BLEUUID

Stack-agnostic 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 invalid/unset.

Constructors

BLEUUID();                                          // invalid UUID
BLEUUID(const char *uuid);                          // "180D", "0000180D", or full 128-bit
BLEUUID(uint16_t uuid16);
BLEUUID(uint32_t uuid32);
BLEUUID(const uint8_t uuid128[16]);                 // big-endian
BLEUUID(const uint8_t *data, size_t len, bool reverse);  // explicit byte order

String parsing accepts:

  • "180D" – 16-bit

  • "0000180D" – 32-bit

  • "0000180d-0000-1000-8000-00805f9b34fb" – 128-bit with dashes

  • "0000180d00001000800000805f9b34fb" – 128-bit without dashes

Methods

bool operator==(const BLEUUID &other) const;
bool operator!=(const BLEUUID &other) const;
bool operator<(const BLEUUID &other) const;
String toString() const;
uint8_t bitSize() const;         // 16, 32, 128, or 0 (invalid)
BLEUUID to128() const;           // expand to 128-bit using Bluetooth Base UUID
bool isValid() const;
explicit operator bool() const;  // equivalent to isValid()
const uint8_t *data() const;     // internal 128-bit representation
uint16_t toUint16() const;       // valid only when bitSize() == 16
uint32_t toUint32() const;       // valid only when bitSize() == 32

BLEProperty

Characteristic properties – Bluetooth Core Spec Vol 3, Part G, 3.3.1.1. Combine with bitwise OR.

This is the list of ATT operations a characteristic supports. The flags are independent and none of them implies any other, so declare exactly the ones clients should be able to use.

enum class BLEProperty : uint8_t {
    Broadcast     = 0x01,
    Read          = 0x02,
    WriteNR       = 0x04,  // Write Without Response
    Write         = 0x08,
    Notify        = 0x10,
    Indicate      = 0x20,
    SignedWrite   = 0x40,
    ExtendedProps = 0x80,
};

Write and WriteNR are two different ATT operations rather than two spellings of one:

Property

ATT operation

Acknowledged

Client API

Write

Write Request

Yes, the client learns if it failed

writeValue(data, len, true)

WriteNR

Write Command

No, fire and forget

writeValue(data, len, false)

Declaring one does not enable the other. Declaring both is normal when you want the client to choose per write, which is what the Nordic UART RX characteristic and HID output reports do. A client can check each independently with canWrite() and canWriteNoResponse().

Example:

BLEProperty props = BLEProperty::Read | BLEProperty::Write | BLEProperty::Notify;

BLEPermission

Attribute access permissions – Bluetooth Core Spec Vol 3, Part F, 3.2.5.

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.

Security level

Read only

Write only

Both directions

Open, no pairing

ReadOpen

WriteOpen

ReadWriteOpen

Encrypted link

ReadEncrypted

WriteEncrypted

ReadWriteEncrypted

MITM-authenticated pairing

ReadAuthenticated

WriteAuthenticated

ReadWriteAuthenticated

Authorization callback

ReadAuthorized

WriteAuthorized

ReadWriteAuthorized

BLEPermission::None means no access at all, which is what notify-only and indicate-only characteristics use.

enum class BLEPermission : uint16_t {
    None                   = 0x0000,

    ReadOpen               = 0x0001,
    ReadEncrypted          = 0x0002,
    ReadAuthenticated      = 0x0004 | ReadEncrypted,
    ReadAuthorized         = 0x0008,

    WriteOpen              = 0x0010,
    WriteEncrypted         = 0x0020,
    WriteAuthenticated     = 0x0040 | WriteEncrypted,
    WriteAuthorized        = 0x0080,

    ReadWriteOpen          = ReadOpen | WriteOpen,
    ReadWriteEncrypted     = ReadEncrypted | WriteEncrypted,
    ReadWriteAuthenticated = ReadAuthenticated | WriteAuthenticated,
    ReadWriteAuthorized    = ReadAuthorized | WriteAuthorized,
};

The Authenticated values carry the encryption requirement with them, matching the ATT security hierarchy, so there is no way to ask for MITM protection and accidentally leave the link unencrypted.

The security level is always spelled out, Open included. Granting unprotected access is therefore something you name explicitly rather than something you get by reaching for the shortest value in the enum.

Combine values with bitwise OR when the two directions need different levels:

// Anyone may read the value, only a paired peer may change it
BLEPermission perms = BLEPermission::ReadOpen | BLEPermission::WriteEncrypted;

BLEIOCapability

Pairing input/output capability – Bluetooth Core Spec Vol 3, Part H, 2.3.2. Describes what the device can show to a user and what it can accept from one, which is what the Security Manager uses to pick a pairing method.

enum class BLEIOCapability : uint8_t {
    DisplayOnly     = 0,  // Can show a passkey, cannot take input
    DisplayYesNo    = 1,  // Can show a passkey and accept a yes/no confirmation
    KeyboardOnly    = 2,  // Can take a typed passkey, cannot show one
    NoInputNoOutput = 3,  // No usable I/O, so pairing falls back to Just Works
    KeyboardDisplay = 4,  // Both a keypad and a display, every pairing method available
};

This describes the hardware only. How strict the pairing has to be is a separate setting, setAuthenticationMode(). A board with a display and buttons may still choose Just Works, but a board reporting NoInputNoOutput can never do better than Just Works no matter what else it asks for.

BLESecurity sec = BLE.getSecurity();
sec.setIOCapability(BLEIOCapability::DisplayOnly);
sec.setAuthenticationMode(true, true, true);  // bonding, MITM, LE Secure Connections

BLEConnInfo

Stack-agnostic connection descriptor. Pure value type with inline storage (no heap allocation).

BLEConnInfo();
explicit operator bool() const;         // true if valid

uint16_t getHandle() const;             // connection handle
BTAddress getAddress() const;           // OTA peer address
BTAddress getIdAddress() const;         // identity address when available, else OTA
uint16_t getMTU() const;                // negotiated ATT MTU
bool isEncrypted() const;
bool isAuthenticated() const;
bool isBonded() const;
uint8_t getSecurityKeySize() const;     // 7-16 bytes
uint16_t getInterval() const;           // in 1.25 ms units
uint16_t getLatency() const;            // peripheral latency
uint16_t getSupervisionTimeout() const; // in 10 ms units
BLEPhy getTxPhy() const;
BLEPhy getRxPhy() const;
bool isCentral() const;
bool isPeripheral() const;
int8_t getRSSI() const;                 // -127 to +20 dBm

Note

On NimBLE, getIdAddress() returns the resolved identity address when the stack provides one (peer_id_addr); otherwise the OTA address. Bluedroid has no resolved-identity field on the connect event, so getIdAddress() always returns the OTA address (never empty). Peer address type comes from GATTS/GATTC connect and AUTH_CMPL on Bluedroid; real PHY may still report as PHY_1M until BLE 5.0 silicon surfaces those fields.

BLEConnParams

Connection parameter structure.

struct BLEConnParams {
    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)

    bool isValid() const;  // validates against Bluetooth Core Spec
};

BLEAdvType

enum class BLEAdvType : uint8_t {
    ConnectableScannable,
    ConnectableDirected,
    ScannableUndirected,
    NonConnectable,
    DirectedHighDuty,
    DirectedLowDuty,
};

BLEPhy

enum class BLEPhy : uint8_t {
    PHY_1M    = 1,
    PHY_2M    = 2,
    PHY_Coded = 3,
};

Specialty Features

BLEIso (Isochronous Transport)

Time-bounded, sequence-numbered SDU delivery over LE isochronous channels, without any audio profile on top: connected isochronous streams (CIS, point to point over an ACL link) and broadcast isochronous streams (BIS, one to many over periodic advertising). Payloads are transparent – the application defines what an SDU carries. For LC3 audio with BAP/CAP interoperability use BLEAudio instead (see BLE Audio); both can run in one sketch.

#include <BLE.h>   // BLEIso is part of the BLE library

BLEIso iso = BLE.getIsoController();
iso.begin();
BLEIso::CisParams qos;
BLEIso::Channel ch = iso.connectCis(client.getHandle(), qos);
ch.onConnected([](BLEIso::Channel &c) { /* CIS up */ });
ch.onDisconnected([](BLEIso::Channel &c, uint8_t reason) { /* CIS down */ });

Roles, each guarded by its own BLE_ISO_*_SUPPORTED flag (the factory logs and returns an empty handle when its role is not compiled in):

  • CIS Central (connectCis) – creates the CIG and connects a CIS on an existing ACL link.

  • CIS Peripheral (listenCis) – registers the ISO server; the CIS is accepted when the central establishes it.

  • BIS Broadcaster (createBig) – creates a BIG on a running extended + periodic advertising set.

  • BIS Receiver (syncBig) – arms a BIG sync when the BIGInfo report arrives on the synced periodic train.

A CIS carries data central-to-peripheral (CisParams::sduSize) and optionally back (CisParams::returnSduSize); a BIS carries data broadcaster-to-receivers. Limits: one Central CIS, one BIG and one BIG sync at a time (one BIS each); a peripheral may listen on several channels, one per incoming CIS. Every channel comes from a fixed pool. Channels are shared handles returned by value: copies share the channel, and a handle outliving its channel (after disconnect(), end(), or slot reuse) becomes a detached shell whose operations fail safe.

BLEIso iso = BLE.getIsoController();
BTStatus begin();   // idempotent; call after BLE.begin()
BTStatus end();     // refused with Busy from a stack callback; defer to loop()
bool isActive();
Channel connectCis(uint16_t connHandle, const CisParams &params);
Channel connectCis(uint16_t connHandle);   // default QoS
Channel listenCis(const CisParams &params);
Channel listenCis();                        // default QoS

Stale handles (0xFFFF, dead or recycled links) are refused before any CIG is created. listenCis() keeps listening after its CIS disconnects; a second call reserves an additional concurrent channel. Never-started listening is stopped with disconnect().

BTStatus send(const uint8_t *sdu, uint16_t len);
BTStatus send(const uint8_t *sdu, uint16_t len, uint16_t seqNum);
BTStatus disconnect();   // onDisconnected follows once the controller confirms

The controller consumes one SDU per SDU interval; onSent fires per consumed SDU and pacing against it keeps the stream in step with the controller.

BLEBeacon (iBeacon)

Apple iBeacon advertisement builder/parser.

#include <BLE.h>

BLEBeacon beacon;
beacon.setProximityUUID(BLEUUID("FDA50693-A4E2-4FB1-AFCF-C6EB07647825"));
beacon.setMajor(1);
beacon.setMinor(1);
beacon.setSignalPower(-59);
BLEAdvertisementData advData = beacon.getAdvertisementData();

Methods

BLEBeacon();

BLEUUID getProximityUUID() const;
void setProximityUUID(const BLEUUID &uuid);

uint16_t getMajor() const;
void setMajor(uint16_t major);

uint16_t getMinor() const;
void setMinor(uint16_t minor);

uint16_t getManufacturerId() const;
void setManufacturerId(uint16_t id);

int8_t getSignalPower() const;
void setSignalPower(int8_t power);

BLEAdvertisementData getAdvertisementData() const;
void setFromPayload(const uint8_t *payload, size_t len);

BLEEddystone (URL + TLM)

Google Eddystone frame builders/parsers.

BLEEddystoneURL

#include <BLE.h>

BLEEddystoneURL url;
url.setURL("https://espressif.com");
url.setTxPower(-20);
BLEAdvertisementData advData = url.getAdvertisementData();

Methods:

BLEEddystoneURL();
void setURL(const String &url);
String getURL() const;
void setTxPower(int8_t txPower);
int8_t getTxPower() const;
BLEAdvertisementData getAdvertisementData() const;
void setFromServiceData(const uint8_t *data, size_t len);
static BLEUUID serviceUUID();

BLEEddystoneTLM

BLEEddystoneTLM tlm;
tlm.setBatteryVoltage(3300);
tlm.setTemperature(25.5f);
tlm.setAdvertisingCount(100);
tlm.setUptime(36000);
BLEAdvertisementData advData = tlm.getAdvertisementData();

Methods:

BLEEddystoneTLM();
void setBatteryVoltage(uint16_t millivolts);
uint16_t getBatteryVoltage() const;
void setTemperature(float celsius);
float getTemperature() const;
void setAdvertisingCount(uint32_t count);
uint32_t getAdvertisingCount() const;
void setUptime(uint32_t deciseconds);
uint32_t getUptime() const;
BLEAdvertisementData getAdvertisementData() const;
void setFromServiceData(const uint8_t *data, size_t len);
String toString() const;
static BLEUUID serviceUUID();

BLEHIDDevice (HID-over-GATT)

Helper for creating HID-over-GATT (HOGP) devices. Manages the standard GATT services:

  • Device Information Service (0x180A)

  • HID Service (0x1812)

  • Battery Service (0x180F) — automatically declared as an Included Service of the HID Service (HIDS 1.0 §3)

The constructor also:

  • Adds an External Report Reference descriptor (0x2907) on the Report Map characteristic, referencing the Battery Level UUID (0x2A19), as required by HIDS 1.0 §3.6.

  • Adds the HID Service UUID (0x1812) to the advertising data automatically, so user code does not need to call adv.addServiceUUID() for HID discovery.

#include <BLE.h>

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

BLEAdvertising adv = BLE.getAdvertising();
adv.setAppearance(BLE_APPEARANCE_HID_KEYBOARD);
adv.start();

Methods

explicit BLEHIDDevice(BLEServer server);

void reportMap(const uint8_t *map, uint16_t size);

BLEService deviceInfoService();
BLEService hidService();
BLEService batteryService();

BLECharacteristic manufacturer();
void manufacturer(const String &name);

void pnp(uint8_t sig, uint16_t vendorId, uint16_t productId, uint16_t version);
void hidInfo(uint8_t country, uint8_t flags);

void setBatteryLevel(uint8_t level);

BLECharacteristic hidControl();
BLECharacteristic protocolMode();

BLECharacteristic inputReport(uint8_t reportId);
BLECharacteristic outputReport(uint8_t reportId);
BLECharacteristic featureReport(uint8_t reportId);

BLECharacteristic bootInput();
BLECharacteristic bootOutput();

inputReport(), outputReport(), and featureReport() each create a new Report characteristic (UUID 0x2A4D) with a Report Reference descriptor. Multiple reports with the same report ID but different types (input vs output) are supported.

bootInput() and bootOutput() use lazy creation — calling them multiple times returns the same cached characteristic.

HID Appearance Constants

Defined in advertising/BLEAppearance.h (pulled in transitively by <BLE.h>) for use with adv.setAppearance():

#define BLE_APPEARANCE_HID_GENERIC             0x03C0
#define BLE_APPEARANCE_HID_KEYBOARD            0x03C1
#define BLE_APPEARANCE_HID_MOUSE               0x03C2
#define BLE_APPEARANCE_HID_JOYSTICK            0x03C3
#define BLE_APPEARANCE_HID_GAMEPAD             0x03C4
#define BLE_APPEARANCE_HID_DIGITIZER_TABLET    0x03C5
#define BLE_APPEARANCE_HID_CARD_READER         0x03C6
#define BLE_APPEARANCE_HID_DIGITAL_PEN         0x03C7
#define BLE_APPEARANCE_HID_BARCODE_SCANNER     0x03C8
#define BLE_APPEARANCE_HID_TOUCHPAD            0x03C9
#define BLE_APPEARANCE_HID_PRESENTATION_REMOTE 0x03CA

L2CAP CoC (Connection-Oriented Channels)

L2CAP CoC channels provide a higher-throughput alternative to GATT for bulk data transfer, bypassing the GATT attribute protocol overhead. Requires NimBLE with BLE_L2CAP_SUPPORTED (set CONFIG_BT_NIMBLE_L2CAP_COC_MAX_NUM > 0 in sdkconfig).

Factory Methods (BLEClass)

BLEL2CAPServer createL2CAPServer(uint16_t psm, uint16_t mtu = 512);
BLEL2CAPChannel connectL2CAP(uint16_t connHandle, uint16_t psm, uint16_t mtu = 512);

createL2CAPServer() starts listening for incoming L2CAP CoC connections on the given PSM. connectL2CAP() opens an outgoing channel to an already-connected peer.

BLEL2CAPChannel

Represents a single bidirectional L2CAP CoC channel.

Construction and Validity
BLEL2CAPChannel();
explicit operator bool() const;
Data Transfer
BTStatus write(const uint8_t *data, size_t len);
BTStatus disconnect();
bool isConnected() const;
uint16_t getPSM() const;
uint16_t getMTU() const;
uint16_t getConnHandle() const;

write() splits payloads larger than the peer CoC MTU into MTU-sized SDUs and may block briefly between chunks while waiting for peer credits. getMTU() returns the local (receive) CoC MTU negotiated for the channel.

Callbacks
using DataHandler = std::function<void(BLEL2CAPChannel &channel, const uint8_t *data, size_t len)>;
using DisconnectHandler = std::function<void(BLEL2CAPChannel &channel)>;
BTStatus onData(DataHandler handler);
BTStatus onDisconnect(DisconnectHandler handler);
BTStatus resetCallbacks();

Note

L2CAP callback registration methods return BTStatus, unlike most other BLE classes where they return void.

BLEL2CAPServer

Listens for incoming L2CAP CoC connections on a PSM.

Construction and Validity
BLEL2CAPServer();
explicit operator bool() const;
Callbacks
using AcceptHandler = std::function<void(BLEL2CAPChannel &channel)>;
using DataHandler = std::function<void(BLEL2CAPChannel &channel, const uint8_t *data, size_t len)>;
using DisconnectHandler = std::function<void(BLEL2CAPChannel &channel)>;
BTStatus onAccept(AcceptHandler handler);
BTStatus onData(DataHandler handler);
BTStatus onDisconnect(DisconnectHandler handler);
BTStatus resetCallbacks();

Per-channel handlers registered via BLEL2CAPChannel::onData() take precedence over the server-level default.

Accessors
uint16_t getPSM() const;
uint16_t getMTU() const;

BLEStream (Nordic UART Service)

BLEStream wraps BLE GATT operations behind the familiar Arduino Stream API using the Nordic UART Service (NUS) UUID conventions. It is interoperable with standard BLE serial apps (nRF Connect, Serial Bluetooth Terminal, etc.).

BLEStream is non-copyable and owns its server/client resources internally.

In server mode, multiple centrals may connect at once. As a single Arduino Stream, write() / print() broadcast to every subscribed peer and read() / available() drain one merged RX buffer. Use the additive per-peer APIs when you need to attribute traffic. Client mode remains one ESP32 central to one remote NUS server.

See the MultiClientUART example for a multi-central server sketch.

Server Mode

BLEStream bleStream;
bleStream.begin("MyDevice");
if (bleStream.isConnected()) {
    bleStream.println("Hello World!");  // broadcast to all peers
    if (bleStream.available()) {
        String s = bleStream.readStringUntil('\n');  // merged RX
    }
}

Client Mode

BLEStream bleStream;
bleStream.beginClient(remoteAddr);
bleStream.println("Hello Server!");

Lifecycle

BLEStream(size_t rxBufferSize = 256);
BTStatus begin(const String &deviceName = "BLE_Stream");
BTStatus beginClient(const BTAddress &address, uint32_t timeoutMs = 5000);
void end();
bool isConnected() const;                // true while any peer is connected
explicit operator bool() const;         // true after begin / beginClient

Multi-peer (server mode)

size_t peerCount() const;
std::vector<BLEConnInfo> peers() const;
size_t writeTo(const BLEConnInfo &peer, const uint8_t *buffer, size_t size);
  • peerCount() – number of connected centrals (0 or 1 in client mode).

  • peers() – snapshot of connected peers (BLEConnInfo values).

  • writeTo() – notify only the given peer’s TX subscription (server mode). Returns 0 if that peer has not enabled TX notifications.

bleStream.onPeerData([](const BLEConnInfo &peer, const uint8_t *data, size_t len) {
    bleStream.writeTo(peer, data, len);  // echo to that peer only
});
Serial.printf("peers=%u\n", (unsigned)bleStream.peerCount());

Arduino Stream Interface

BLEStream implements the standard Arduino Stream methods:

int available() override;
int read() override;
int peek() override;
size_t write(uint8_t c) override;                          // broadcast (server) / write (client)
size_t write(const uint8_t *buffer, size_t size) override; // same
void flush() override;                                     // no-op for BLE

Each write() chunk is limited to (MTU - 3) bytes to fit the ATT header.

Callbacks

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

void onConnect(ConnectHandler handler);
void onDisconnect(DisconnectHandler handler);
void onPeerData(PeerDataHandler handler);  // attributed RX; also fills the merged buffer
void resetCallbacks();

NUS UUIDs

static BLEUUID nusServiceUUID();
static BLEUUID nusRxCharUUID();
static BLEUUID nusTxCharUUID();

Troubleshooting

Pairing Keeps Failing With the Same Peer

Bonds live in NVS, not in the sketch. Uploading new firmware, rebuilding the GATT database, or switching between the Bluedroid and NimBLE stacks all leave the stored bond keys untouched, so a bond created by an earlier sketch can outlive everything that produced it.

When those stored keys stop matching what the peer expects, pairing fails at the cryptographic step that first notices the mismatch. The reported reason describes that step and not the bond store, which makes a stale bond easy to misread as a stack or configuration bug. Typical symptoms:

  • DHKey check failed or confirm value mismatch during Secure Connections pairing.

  • controller failed to start encryption when reconnecting to an already bonded peer.

  • Numeric comparison displaying the same six digits on both devices, and pairing failing anyway.

  • A peer that paired reliably for a long time now failing every attempt, with no code change.

The library logs a warning pointing at this section the first time a pairing fails in a session.

Clearing the Bond Store

From a sketch:

BLESecurity sec = BLE.getSecurity();
sec.deleteAllBonds();             // drop every bond
sec.deleteBond(peerAddress);      // or just one peer

Or erase NVS from the host, which also discards Wi-Fi credentials and anything else kept in Preferences:

esptool -p <port> erase-flash

Note

A bond has two sides. Clearing it on the ESP32 while a phone, computer, or second ESP32 still holds its half produces exactly the same failures, because that peer keeps presenting keys this device no longer recognizes. Remove the pairing on the peer too, which on most phones is “Forget This Device”.

Automated test setups are especially exposed to this, because bond state survives between runs and can turn an otherwise deterministic suite into an intermittent one. Wiping bonds at startup, or erasing flash before a run, keeps results reproducible.

Migration from v3.x

See the Migration Guide for a comprehensive old-vs-new API mapping, before/after code examples, and ArduinoBLE porting guide.