High level Bluetooth Low Energy API and radio abstraction layer

Dependents:   BLE_ANCS_SDAPI BLE_temperature BLE_HeartRate BLE_ANCS_SDAPI_IRC ... more

Embed: (wiki syntax)

« Back to documentation index

BLE Class Reference

The base class used to abstract away BLE-capable radio transceivers or SOCs, so that the BLE API can work with any radio transparently. More...

#include <BLE.h>

Data Structures

struct  InitializationCompleteCallbackContext
 The context provided to init-completion-callbacks (see init() below). More...
struct  OnEventsToProcessCallbackContext
 Parameters provided to the callback registered by onEventsToProcess when there is events to process. More...

Public Types

typedef unsigned InstanceID_t
 The type returned by BLE::getInstanceID().
typedef
FunctionPointerWithContext
< OnEventsToProcessCallbackContext * > 
OnEventsToProcessCallback_t
 Callback type used by the onEventsToProcess function.
typedef void(* InitializationCompleteCallback_t )(InitializationCompleteCallbackContext *context)
 The signature for function-pointer like callbacks for initialization-completion.

Public Member Functions

ble_error_t init (InitializationCompleteCallback_t initCompleteCallback=NULL)
 Initialize the BLE controller.
template<typename T >
ble_error_t init (T *object, void(T::*initCompleteCallback)(InitializationCompleteCallbackContext *context))
 An alternate declaration for init().
bool hasInitialized (void) const
ble_error_t shutdown (void)
 Purge the BLE stack of GATT and GAP state.
const char * getVersion (void)
 This call allows the application to get the BLE stack version information.
Gap & gap ()
 Accessor to Gap.
const Gap & gap () const
 A const alternative to gap().
GattServer & gattServer ()
 Accessor to GattServer.
const GattServer & gattServer () const
 A const alternative to gattServer().
GattClient & gattClient ()
 Accessors to GattClient.
const GattClient & gattClient () const
 A const alternative to gattClient().
SecurityManager & securityManager ()
 Accessors to SecurityManager.
const SecurityManager & securityManager () const
 A const alternative to securityManager().
void waitForEvent (void)
 Yield control to the BLE stack or to other tasks waiting for events.
 BLE (InstanceID_t instanceID=DEFAULT_INSTANCE)
 Constructor for a handle to a BLE instance (the BLE stack).
InstanceID_t getInstanceID (void) const
 Fetch the ID of a BLE instance.
ble_error_t setAddress (BLEProtocol::AddressType_t type, const BLEProtocol::AddressBytes_t address)
 Set the BTLE MAC address and type.
ble_error_t getAddress (BLEProtocol::AddressType_t *typeP, BLEProtocol::AddressBytes_t address)
 Fetch the Bluetooth Low Energy MAC address and type.
void setAdvertisingType (GapAdvertisingParams::AdvertisingType advType)
 Set the GAP advertising mode to use for this device.
void setAdvertisingInterval (uint16_t interval)
uint16_t getMinAdvertisingInterval (void) const
uint16_t getMinNonConnectableAdvertisingInterval (void) const
uint16_t getMaxAdvertisingInterval (void) const
void setAdvertisingTimeout (uint16_t timeout)
void setAdvertisingParams (const GapAdvertisingParams &advParams)
 Set up a particular, user-constructed set of advertisement parameters for the underlying stack.
const GapAdvertisingParamsgetAdvertisingParams (void) const
ble_error_t accumulateAdvertisingPayload (uint8_t flags)
 Accumulate an AD structure in the advertising payload.
ble_error_t accumulateAdvertisingPayload (GapAdvertisingData::Appearance app)
 Accumulate an AD structure in the advertising payload.
ble_error_t accumulateAdvertisingPayloadTxPower (int8_t power)
 Accumulate an AD structure in the advertising payload.
ble_error_t accumulateAdvertisingPayload (GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len)
 Accumulate a variable length byte-stream as an AD structure in the advertising payload.
ble_error_t setAdvertisingData (const GapAdvertisingData &advData)
 Setup a particular, user-constructed advertisement payload for the underlying stack.
const GapAdvertisingDatagetAdvertisingData (void) const
void clearAdvertisingPayload (void)
 Reset any advertising payload prepared from prior calls to accumulateAdvertisingPayload().
ble_error_t setAdvertisingPayload (void)
 Dynamically reset the accumulated advertising payload and scanResponse.
ble_error_t accumulateScanResponse (GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len)
 Accumulate a variable length byte-stream as an AD structure in the scanResponse payload.
void clearScanResponse (void)
 Reset any scan response prepared from prior calls to accumulateScanResponse().
ble_error_t startAdvertising (void)
 Start advertising.
ble_error_t stopAdvertising (void)
 Stop advertising.
ble_error_t setScanParams (uint16_t interval=GapScanningParams::SCAN_INTERVAL_MAX, uint16_t window=GapScanningParams::SCAN_WINDOW_MAX, uint16_t timeout=0, bool activeScanning=false)
 Set up parameters for GAP scanning (observer mode).
ble_error_t setScanInterval (uint16_t interval)
 Set up the scanInterval parameter for GAP scanning (observer mode).
ble_error_t setScanWindow (uint16_t window)
 Set up the scanWindow parameter for GAP scanning (observer mode).
ble_error_t setScanTimeout (uint16_t timeout)
 Set up parameters for GAP scanning (observer mode).
void setActiveScan (bool activeScanning)
 Set up parameters for GAP scanning (observer mode).
ble_error_t startScan (void(*callback)(const Gap::AdvertisementCallbackParams_t *params))
 Start scanning (Observer Procedure) based on the parameters currently in effect.
template<typename T >
ble_error_t startScan (T *object, void(T::*memberCallback)(const Gap::AdvertisementCallbackParams_t *params))
 Same as above, but this takes an (object, method) pair for a callback.
ble_error_t stopScan (void)
 Stop scanning.
ble_error_t connect (const BLEProtocol::AddressBytes_t peerAddr, BLEProtocol::AddressType_t peerAddrType=BLEProtocol::AddressType::RANDOM_STATIC, const Gap::ConnectionParams_t *connectionParams=NULL, const GapScanningParams *scanParams=NULL)
 Create a connection (GAP Link Establishment).
ble_error_t disconnect (Gap::Handle_t connectionHandle, Gap::DisconnectionReason_t reason)
 This call initiates the disconnection procedure, and its completion is communicated to the application with an invocation of the onDisconnection callback.
ble_error_t disconnect (Gap::DisconnectionReason_t reason)
 This call initiates the disconnection procedure, and its completion is communicated to the application with an invocation of the onDisconnection callback.
Gap::GapState_t getGapState (void) const
 Returns the current Gap state of the device using a bitmask that describes whether the device is advertising or connected.
ble_error_t getPreferredConnectionParams (Gap::ConnectionParams_t *params)
 Get the GAP peripheral's preferred connection parameters.
ble_error_t setPreferredConnectionParams (const Gap::ConnectionParams_t *params)
 Set the GAP peripheral's preferred connection parameters.
ble_error_t updateConnectionParams (Gap::Handle_t handle, const Gap::ConnectionParams_t *params)
 Update connection parameters while in the peripheral role.
ble_error_t setDeviceName (const uint8_t *deviceName)
 Set the device name characteristic in the Gap service.
ble_error_t getDeviceName (uint8_t *deviceName, unsigned *lengthP)
 Get the value of the device name characteristic in the Gap service.
ble_error_t setAppearance (GapAdvertisingData::Appearance appearance)
 Set the appearance characteristic in the Gap service.
ble_error_t getAppearance (GapAdvertisingData::Appearance *appearanceP)
 Get the appearance characteristic in the Gap service.
ble_error_t setTxPower (int8_t txPower)
 Set the radio's transmit power.
void getPermittedTxPowerValues (const int8_t **valueArrayPP, size_t *countP)
 Query the underlying stack for permitted arguments for setTxPower().
ble_error_t addService (GattService &service)
 Add a service declaration to the local server ATT table.
ble_error_t readCharacteristicValue (GattAttribute::Handle_t attributeHandle, uint8_t *buffer, uint16_t *lengthP)
 Read the value of a characteristic from the local GattServer.
ble_error_t readCharacteristicValue (Gap::Handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, uint8_t *buffer, uint16_t *lengthP)
 Read the value of a characteristic from the local GattServer.
ble_error_t updateCharacteristicValue (GattAttribute::Handle_t attributeHandle, const uint8_t *value, uint16_t size, bool localOnly=false)
 Update the value of a characteristic on the local GattServer.
ble_error_t updateCharacteristicValue (Gap::Handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, const uint8_t *value, uint16_t size, bool localOnly=false)
 Update the value of a characteristic on the local GattServer.
ble_error_t initializeSecurity (bool enableBonding=true, bool requireMITM=true, SecurityManager::SecurityIOCapabilities_t iocaps=SecurityManager::IO_CAPS_NONE, const SecurityManager::Passkey_t passkey=NULL)
 Enable the BLE stack's Security Manager.
ble_error_t getLinkSecurity (Gap::Handle_t connectionHandle, SecurityManager::LinkSecurityStatus_t *securityStatusP)
 Get the security status of a connection.
ble_error_t purgeAllBondingState (void)
 Delete all peer device context and all related bonding information from the database within the security manager.
void onTimeout (Gap::TimeoutEventCallback_t timeoutCallback)
 Set up a callback for timeout events.
void onConnection (Gap::ConnectionEventCallback_t connectionCallback)
 Set up a callback for connection events.
void onDisconnection (Gap::DisconnectionEventCallback_t disconnectionCallback)
 Append to a chain of callbacks to be invoked upon GAP disconnection.
template<typename T >
void onDisconnection (T *tptr, void(T::*mptr)(const Gap::DisconnectionCallbackParams_t *))
 The same as onDisconnection(), but allows an object reference and member function to be added to the chain of callbacks.
void onRadioNotification (void(*callback)(bool))
 Radio Notification is a feature that enables ACTIVE and INACTIVE (nACTIVE) signals from the stack.
void onDataSent (void(*callback)(unsigned count))
 Add a callback for the GATT event DATA_SENT (which is triggered when updates are sent out by GATT in the form of notifications).
template<typename T >
void onDataSent (T *objPtr, void(T::*memberPtr)(unsigned count))
 The same as onDataSent(), but allows an object reference and member function to be added to the chain of callbacks.
void onDataWritten (void(*callback)(const GattWriteCallbackParams *eventDataP))
 Set up a callback for when an attribute has its value updated by or at the connected peer.
template<typename T >
void onDataWritten (T *objPtr, void(T::*memberPtr)(const GattWriteCallbackParams *context))
 The same as onDataWritten(), but allows an object reference and member function to be added to the chain of callbacks.
ble_error_t onDataRead (void(*callback)(const GattReadCallbackParams *eventDataP))
 Set up a callback to be invoked on the peripheral when an attribute is being read by a remote client.
template<typename T >
ble_error_t onDataRead (T *objPtr, void(T::*memberPtr)(const GattReadCallbackParams *context))
 The same as onDataRead(), but allows an object reference and member function to be added to the chain of callbacks.
void onUpdatesEnabled (GattServer::EventCallback_t callback)
 Set up a callback for when notifications or indications are enabled for a characteristic on the local GattServer.
void onUpdatesDisabled (GattServer::EventCallback_t callback)
 Set up a callback for when notifications or indications are disabled for a characteristic on the local GattServer.
void onConfirmationReceived (GattServer::EventCallback_t callback)
 Set up a callback for when the GATT server receives a response for an indication event sent previously.
void onSecuritySetupInitiated (SecurityManager::SecuritySetupInitiatedCallback_t callback)
 Set up a callback for when the security setup procedure (key generation and exchange) for a link has started.
void onSecuritySetupCompleted (SecurityManager::SecuritySetupCompletedCallback_t callback)
 Set up a callback for when the security setup procedure (key generation and exchange) for a link has completed.
void onLinkSecured (SecurityManager::LinkSecuredCallback_t callback)
 Set up a callback for when a link with the peer is secured.
void onSecurityContextStored (SecurityManager::HandleSpecificEvent_t callback)
 Set up a callback for successful bonding, meaning that link-specific security context is stored persistently for a peer device.
void onPasskeyDisplay (SecurityManager::PasskeyDisplayCallback_t callback)
 Set up a callback for when the passkey needs to be displayed on a peripheral with DISPLAY capability.
void processEvents ()
 Process ALL pending events living in the BLE stack .
void onEventsToProcess (const OnEventsToProcessCallback_t &callback)
 Register a hook which will be called every time the BLE stack has pending work.

Static Public Member Functions

static BLEInstance (InstanceID_t id=DEFAULT_INSTANCE)
 Get a reference to the BLE singleton corresponding to a given interface.

Static Public Attributes

static const InstanceID_t DEFAULT_INSTANCE = 0
 The value of the BLE::InstanceID_t for the default BLE instance.
static const InstanceID_t NUM_INSTANCES = 1
 The number of permitted BLE instances for the application.

Friends

class BLEInstanceBase

Detailed Description

The base class used to abstract away BLE-capable radio transceivers or SOCs, so that the BLE API can work with any radio transparently.

Definition at line 40 of file BLE.h.


Member Typedef Documentation

The signature for function-pointer like callbacks for initialization-completion.

Note:
There are two versions of init(). In addition to the simple function-pointer, init() can also take a <Object, member> tuple as its callback target. In case of the latter, the following declaration doesn't apply.

Definition at line 83 of file BLE.h.

typedef unsigned InstanceID_t

The type returned by BLE::getInstanceID().

Definition at line 43 of file BLE.h.

Callback type used by the onEventsToProcess function.

Definition at line 59 of file BLE.h.


Constructor & Destructor Documentation

BLE ( InstanceID_t  instanceID = DEFAULT_INSTANCE )

Constructor for a handle to a BLE instance (the BLE stack).

BLE handles are thin wrappers around a transport object (that is, ptr. to BLEInstanceBase).

It is better to create BLE objects as singletons accessed through the Instance() method. If multiple BLE handles are constructed for the same interface (using this constructor), they will share the same underlying transport object.

Definition at line 141 of file BLE.cpp.


Member Function Documentation

ble_error_t accumulateAdvertisingPayload ( uint8_t  flags )

Accumulate an AD structure in the advertising payload.

Please note that the payload is limited to 31 bytes. The SCAN_RESPONSE message may be used as an additional 31 bytes if the advertising payload is too small.

Parameters:
[in]flagsThe flags to add. Please refer to GapAdvertisingData::Flags for valid flags. Multiple flags may be specified in combination.

Definition at line 447 of file BLE.h.

ble_error_t accumulateAdvertisingPayload ( GapAdvertisingData::Appearance  app )

Accumulate an AD structure in the advertising payload.

Please note that the payload is limited to 31 bytes. The SCAN_RESPONSE message may be used as an additional 31 bytes if the advertising payload is too small.

Parameters:
[in]appThe appearance of the peripheral.

Definition at line 466 of file BLE.h.

ble_error_t accumulateAdvertisingPayload ( GapAdvertisingData::DataType  type,
const uint8_t *  data,
uint8_t  len 
)

Accumulate a variable length byte-stream as an AD structure in the advertising payload.

Please note that the payload is limited to 31 bytes. The SCAN_RESPONSE message may be used as an additional 31 bytes if the advertising payload is too small.

Parameters:
typeThe type that describes the variable length data.
dataData bytes.
lenData length.

Definition at line 504 of file BLE.h.

ble_error_t accumulateAdvertisingPayloadTxPower ( int8_t  power )

Accumulate an AD structure in the advertising payload.

Please note that the payload is limited to 31 bytes. The SCAN_RESPONSE message may be used as an additional 31 bytes if the advertising payload is too small.

Parameters:
[in]powerThe max transmit power to be used by the controller. This is only a hint.

Definition at line 485 of file BLE.h.

ble_error_t accumulateScanResponse ( GapAdvertisingData::DataType  type,
const uint8_t *  data,
uint8_t  len 
)

Accumulate a variable length byte-stream as an AD structure in the scanResponse payload.

Parameters:
[in]typeThe type that describes the variable length data.
[in]dataData bytes.
[in]lenData length.

Definition at line 580 of file BLE.h.

ble_error_t addService ( GattService &  service )

Add a service declaration to the local server ATT table.

Also add the characteristics contained within.

Definition at line 1030 of file BLE.h.

void clearAdvertisingPayload ( void   )

Reset any advertising payload prepared from prior calls to accumulateAdvertisingPayload().

This automatically propagates the re- initialized advertising payload to the underlying stack.

Definition at line 545 of file BLE.h.

void clearScanResponse ( void   )

Reset any scan response prepared from prior calls to accumulateScanResponse().

Definition at line 593 of file BLE.h.

ble_error_t connect ( const BLEProtocol::AddressBytes_t  peerAddr,
BLEProtocol::AddressType_t  peerAddrType = BLEProtocol::AddressType::RANDOM_STATIC,
const Gap::ConnectionParams_t connectionParams = NULL,
const GapScanningParams *  scanParams = NULL 
)

Create a connection (GAP Link Establishment).

Parameters:
peerAddr48-bit address, LSB format.
peerAddrTypeAddress type of the peer.
connectionParamsConnection parameters.
scanParamsParamters to use while scanning for the peer.
Returns:
BLE_ERROR_NONE if connection establishment procedure is started successfully. The onConnection callback (if set) is invoked upon a connection event.

Definition at line 811 of file BLE.h.

ble_error_t disconnect ( Gap::Handle_t  connectionHandle,
Gap::DisconnectionReason_t  reason 
)

This call initiates the disconnection procedure, and its completion is communicated to the application with an invocation of the onDisconnection callback.

Parameters:
[in]connectionHandle
[in]reasonThe reason for disconnection; sent back to the peer.

Definition at line 827 of file BLE.h.

ble_error_t disconnect ( Gap::DisconnectionReason_t  reason )

This call initiates the disconnection procedure, and its completion is communicated to the application with an invocation of the onDisconnection callback.

Parameters:
reasonThe reason for disconnection; sent back to the peer.
Note:
This version of disconnect() doesn't take a connection handle. It works reliably only for stacks that are limited to a single connection.

Definition at line 848 of file BLE.h.

const Gap & gap (  ) const

A const alternative to gap().

Returns:
A const reference to a Gap object associated to this BLE instance.

Definition at line 183 of file BLE.cpp.

Gap & gap (  )

Accessor to Gap.

All Gap related functionality requires going through this accessor.

Returns:
A reference to a Gap object associated to this BLE instance.

Definition at line 192 of file BLE.cpp.

GattClient & gattClient (  )

Accessors to GattClient.

All GattClient related functionality requires going through this accessor.

Returns:
A reference to a GattClient object associated to this BLE instance.

Definition at line 228 of file BLE.cpp.

const GattClient & gattClient (  ) const

A const alternative to gattClient().

Returns:
A const reference to a GattClient object associated to this BLE instance.

Definition at line 219 of file BLE.cpp.

const GattServer & gattServer (  ) const

A const alternative to gattServer().

Returns:
A const reference to a GattServer object associated to this BLE instance.

Definition at line 201 of file BLE.cpp.

GattServer & gattServer (  )

Accessor to GattServer.

All GattServer related functionality requires going through this accessor.

Returns:
A reference to a GattServer object associated to this BLE instance.

Definition at line 210 of file BLE.cpp.

ble_error_t getAddress ( BLEProtocol::AddressType_t typeP,
BLEProtocol::AddressBytes_t  address 
)

Fetch the Bluetooth Low Energy MAC address and type.

Returns:
BLE_ERROR_NONE on success.

Definition at line 307 of file BLE.h.

const GapAdvertisingData& getAdvertisingData ( void   ) const
Returns:
Read back advertising data. Useful for storing and restoring payload.

Definition at line 531 of file BLE.h.

const GapAdvertisingParams& getAdvertisingParams ( void   ) const
Returns:
Read back advertising parameters. Useful for storing and restoring parameters rapidly.

Definition at line 427 of file BLE.h.

ble_error_t getAppearance ( GapAdvertisingData::Appearance appearanceP )

Get the appearance characteristic in the Gap service.

Parameters:
[out]appearancePThe new value for the device-appearance.

Definition at line 987 of file BLE.h.

ble_error_t getDeviceName ( uint8_t *  deviceName,
unsigned *  lengthP 
)

Get the value of the device name characteristic in the Gap service.

Parameters:
[out]deviceNamePointer to an empty buffer where the UTF-8 *non NULL- terminated* string will be placed. Set this value to NULL in order to obtain the deviceName-length from the 'length' parameter.
[in,out]lengthP(on input) Length of the buffer pointed to by deviceName; (on output) the complete device name length (without the null terminator).
Note:
If the device name is longer than the size of the supplied buffer, length will return the complete device name length, and not the number of bytes actually returned in deviceName. The application may use this information to retry with a suitable buffer size.

Definition at line 959 of file BLE.h.

Gap::GapState_t getGapState ( void   ) const

Returns the current Gap state of the device using a bitmask that describes whether the device is advertising or connected.

Definition at line 861 of file BLE.h.

InstanceID_t getInstanceID ( void   ) const

Fetch the ID of a BLE instance.

Typically there would only be the DEFAULT_INSTANCE.

Definition at line 273 of file BLE.h.

ble_error_t getLinkSecurity ( Gap::Handle_t  connectionHandle,
SecurityManager::LinkSecurityStatus_t *  securityStatusP 
)

Get the security status of a connection.

Parameters:
[in]connectionHandleHandle to identify the connection.
[out]securityStatusPSecurity status.
Returns:
BLE_SUCCESS or appropriate error code indicating the reason of failure.

Definition at line 1193 of file BLE.h.

uint16_t getMaxAdvertisingInterval ( void   ) const
Returns:
Maximum Advertising interval in milliseconds.

Definition at line 385 of file BLE.h.

uint16_t getMinAdvertisingInterval ( void   ) const
Returns:
Minimum Advertising interval in milliseconds.

Definition at line 361 of file BLE.h.

uint16_t getMinNonConnectableAdvertisingInterval ( void   ) const
Returns:
Minimum Advertising interval in milliseconds for non-connectible mode.

Definition at line 373 of file BLE.h.

void getPermittedTxPowerValues ( const int8_t **  valueArrayPP,
size_t *  countP 
)

Query the underlying stack for permitted arguments for setTxPower().

Parameters:
[out]valueArrayPPOut parameter to receive the immutable array of Tx values.
[out]countPOut parameter to receive the array's size.

Definition at line 1017 of file BLE.h.

ble_error_t getPreferredConnectionParams ( Gap::ConnectionParams_t params )

Get the GAP peripheral's preferred connection parameters.

These are the defaults that the peripheral would like to have in a connection. The choice of the connection parameters is eventually up to the central.

Parameters:
[out]paramsThe structure where the parameters will be stored. Memory for this is owned by the caller.
Returns:
BLE_ERROR_NONE if the parameters were successfully filled into the given structure pointed to by params.

Definition at line 882 of file BLE.h.

const char * getVersion ( void   )

This call allows the application to get the BLE stack version information.

Returns:
A pointer to a const string representing the version.
Note:
The string returned is owned by BLE API.

Definition at line 174 of file BLE.cpp.

bool hasInitialized ( void   ) const
Returns:
true if initialization has completed for the underlying BLE transport.

The application can set up a callback to signal completion of initialization when using init(). Otherwise, this method can be used to poll the state of initialization.

Definition at line 156 of file BLE.cpp.

ble_error_t init ( T *  object,
void(T::*)(InitializationCompleteCallbackContext *context)  initCompleteCallback 
)

An alternate declaration for init().

This one takes an <Object, member> tuple as its callback target.

Definition at line 126 of file BLE.h.

ble_error_t init ( InitializationCompleteCallback_t  initCompleteCallback = NULL )

Initialize the BLE controller.

This should be called before using anything else in the BLE API.

init() hands control to the underlying BLE module to accomplish initialization. This initialization may tacitly depend on other hardware setup (such as clocks or power-modes) that happens early on during system startup. It may not be safe to call init() from a global static context where ordering is compiler-specific and can't be guaranteed - it is safe to call BLE::init() from within main().

Parameters:
initCompleteCallbackA callback for when initialization completes for a BLE instance. This is an optional parameter; if no callback is set up the application can still determine the status of initialization using BLE::hasInitialized() (see below).
Returns:
BLE_ERROR_NONE if the initialization procedure was started successfully.
Note:
If init() returns BLE_ERROR_NONE, the underlying stack must invoke the initialization completion callback at some point.
Nearly all BLE APIs would return BLE_ERROR_INITIALIZATION_INCOMPLETE if used on an instance before the corresponding transport is initialized.
There are two versions of init(). In addition to the simple function-pointer, init() can also take an <Object, member> tuple as its callback target.

Definition at line 116 of file BLE.h.

ble_error_t initializeSecurity ( bool  enableBonding = true,
bool  requireMITM = true,
SecurityManager::SecurityIOCapabilities_t  iocaps = SecurityManager::IO_CAPS_NONE,
const SecurityManager::Passkey_t  passkey = NULL 
)

Enable the BLE stack's Security Manager.

The Security Manager implements the cryptographic algorithms and protocol exchanges that allow two devices to securely exchange data and privately detect each other. Calling this API is a prerequisite for encryption and pairing (bonding).

Parameters:
[in]enableBondingAllow for bonding.
[in]requireMITMRequire protection against man-in-the-middle attacks.
[in]iocapsTo specify the I/O capabilities of this peripheral, such as availability of a display or keyboard, to support out-of-band exchanges of security data.
[in]passkeyTo specify a static passkey.
Returns:
BLE_ERROR_NONE on success.

Definition at line 1173 of file BLE.h.

BLE & Instance ( InstanceID_t  id = DEFAULT_INSTANCE ) [static]

Get a reference to the BLE singleton corresponding to a given interface.

There is a static array of BLE singletons.

Note:
Calling Instance() is preferred over constructing a BLE object directly, as it returns references to singletons.
Parameters:
[in]idInstance-ID. This should be less than NUM_INSTANCES for the returned BLE singleton to be useful.
Returns:
A reference to a single object.

Definition at line 116 of file BLE.cpp.

void onConfirmationReceived ( GattServer::EventCallback_t  callback )

Set up a callback for when the GATT server receives a response for an indication event sent previously.

Definition at line 1436 of file BLE.h.

void onConnection ( Gap::ConnectionEventCallback_t  connectionCallback )

Set up a callback for connection events.

Refer to Gap::ConnectionEventCallback_t.

Definition at line 1235 of file BLE.h.

ble_error_t onDataRead ( void(*)(const GattReadCallbackParams *eventDataP)  callback )

Set up a callback to be invoked on the peripheral when an attribute is being read by a remote client.

Note:
This functionality may not be available on all underlying stacks. You could use GattCharacteristic::setReadAuthorizationCallback() as an alternative.
It is possible to chain together multiple onDataRead callbacks (potentially from different modules of an application) to receive updates to characteristics. Services may add their own onDataRead callbacks behind the scenes to trap interesting events.
It is also possible to set up a callback into a member function of some object.
Returns:
BLE_ERROR_NOT_IMPLEMENTED if this functionality isn't available; else BLE_ERROR_NONE.

Definition at line 1384 of file BLE.h.

ble_error_t onDataRead ( T *  objPtr,
void(T::*)(const GattReadCallbackParams *context)  memberPtr 
)

The same as onDataRead(), but allows an object reference and member function to be added to the chain of callbacks.

Definition at line 1397 of file BLE.h.

void onDataSent ( void(*)(unsigned count)  callback )

Add a callback for the GATT event DATA_SENT (which is triggered when updates are sent out by GATT in the form of notifications).

Note:
It is possible to chain together multiple onDataSent callbacks (potentially from different modules of an application) to receive updates to characteristics.
It is also possible to set up a callback into a member function of some object.

Definition at line 1306 of file BLE.h.

void onDataSent ( T *  objPtr,
void(T::*)(unsigned count)  memberPtr 
)

The same as onDataSent(), but allows an object reference and member function to be added to the chain of callbacks.

Definition at line 1319 of file BLE.h.

void onDataWritten ( void(*)(const GattWriteCallbackParams *eventDataP)  callback )

Set up a callback for when an attribute has its value updated by or at the connected peer.

For a peripheral, this callback is triggered when the local GATT server has an attribute updated by a write command from the peer. For a Central, this callback is triggered when a response is received for a write request.

Note:
It is possible to chain together multiple onDataWritten callbacks (potentially from different modules of an application) to receive updates to characteristics. Many services, such as DFU and UART, add their own onDataWritten callbacks behind the scenes to trap interesting events.
It is also possible to set up a callback into a member function of some object.

Definition at line 1343 of file BLE.h.

void onDataWritten ( T *  objPtr,
void(T::*)(const GattWriteCallbackParams *context)  memberPtr 
)

The same as onDataWritten(), but allows an object reference and member function to be added to the chain of callbacks.

Definition at line 1356 of file BLE.h.

void onDisconnection ( T *  tptr,
void(T::*)(const Gap::DisconnectionCallbackParams_t *)  mptr 
)

The same as onDisconnection(), but allows an object reference and member function to be added to the chain of callbacks.

Definition at line 1261 of file BLE.h.

void onDisconnection ( Gap::DisconnectionEventCallback_t  disconnectionCallback )

Append to a chain of callbacks to be invoked upon GAP disconnection.

Definition at line 1247 of file BLE.h.

void onEventsToProcess ( const OnEventsToProcessCallback_t callback )

Register a hook which will be called every time the BLE stack has pending work.

By registering a callback, user code can know when event processing has to be scheduled. Callback format is void (*)(BLE& ble);

Definition at line 273 of file BLE.cpp.

void onLinkSecured ( SecurityManager::LinkSecuredCallback_t  callback )

Set up a callback for when a link with the peer is secured.

For bonded devices, subsequent reconnections with a bonded peer will result only in this callback when the link is secured, and setup procedures will not occur unless the bonding information is either lost or deleted on either or both sides. The callback is passed in a SecurityManager::SecurityMode_t according to the level of security in effect for the secured link.

Definition at line 1484 of file BLE.h.

void onPasskeyDisplay ( SecurityManager::PasskeyDisplayCallback_t  callback )

Set up a callback for when the passkey needs to be displayed on a peripheral with DISPLAY capability.

This happens when security is configured to prevent Man-In-The-Middle attacks, and the peers need to exchange a passkey (or PIN) to authenticate the connection attempt.

Definition at line 1513 of file BLE.h.

void onRadioNotification ( void(*)(bool)  callback )

Radio Notification is a feature that enables ACTIVE and INACTIVE (nACTIVE) signals from the stack.

These notify the application when the radio is in use. The signal is sent using software interrupt.

The ACTIVE signal is sent before the radio event starts. The nACTIVE signal is sent at the end of the radio event. These signals can be used by the application programmer to synchronize application logic with radio activity. For example, the ACTIVE signal can be used to shut off external devices to manage peak current drawn during periods when the radio is on, or to trigger sensor data collection for transmission in the radio event.

Parameters:
callbackThe application handler to be invoked in response to a radio ACTIVE/INACTIVE event.

Definition at line 1286 of file BLE.h.

void onSecurityContextStored ( SecurityManager::HandleSpecificEvent_t  callback )

Set up a callback for successful bonding, meaning that link-specific security context is stored persistently for a peer device.

Definition at line 1497 of file BLE.h.

void onSecuritySetupCompleted ( SecurityManager::SecuritySetupCompletedCallback_t  callback )

Set up a callback for when the security setup procedure (key generation and exchange) for a link has completed.

This will be skipped for bonded devices. The callback is passed in the success/failure status of the security setup procedure.

Definition at line 1467 of file BLE.h.

void onSecuritySetupInitiated ( SecurityManager::SecuritySetupInitiatedCallback_t  callback )

Set up a callback for when the security setup procedure (key generation and exchange) for a link has started.

This will be skipped for bonded devices. The callback is passed in parameters received from the peer's security request: bool allowBonding, bool requireMITM, and SecurityIOCapabilities_t.

Definition at line 1452 of file BLE.h.

void onTimeout ( Gap::TimeoutEventCallback_t  timeoutCallback )

Set up a callback for timeout events.

Refer to Gap::TimeoutSource_t for possible event types.

Definition at line 1223 of file BLE.h.

void onUpdatesDisabled ( GattServer::EventCallback_t  callback )

Set up a callback for when notifications or indications are disabled for a characteristic on the local GattServer.

Definition at line 1423 of file BLE.h.

void onUpdatesEnabled ( GattServer::EventCallback_t  callback )

Set up a callback for when notifications or indications are enabled for a characteristic on the local GattServer.

Definition at line 1410 of file BLE.h.

void processEvents (  )

Process ALL pending events living in the BLE stack .

Return once all events have been consumed. This function is called by user in their while loop (mbed Classic) or automatically by Minar (mbed OS) when BLE event processing is scheduled. Internally, this function will call BLEInstanceBase::processEvent.

Definition at line 264 of file BLE.cpp.

ble_error_t purgeAllBondingState ( void   )

Delete all peer device context and all related bonding information from the database within the security manager.

Return values:
BLE_ERROR_NONEOn success; else returns an error code indicating the reason for the failure.
BLE_ERROR_INVALID_STATEIf the API is called without module initialization or application registration.

Definition at line 1210 of file BLE.h.

ble_error_t readCharacteristicValue ( GattAttribute::Handle_t  attributeHandle,
uint8_t *  buffer,
uint16_t *  lengthP 
)

Read the value of a characteristic from the local GattServer.

Parameters:
[in]attributeHandleAttribute handle for the value attribute of the characteristic.
[out]bufferA buffer to hold the value being read.
[in,out]lengthPLength of the buffer being supplied. If the attribute value is longer than the size of the supplied buffer, this variable will return the total attribute value length (excluding offset). The application may use this information to allocate a suitable buffer size.
Returns:
BLE_ERROR_NONE if a value was read successfully into the buffer.

Definition at line 1054 of file BLE.h.

ble_error_t readCharacteristicValue ( Gap::Handle_t  connectionHandle,
GattAttribute::Handle_t  attributeHandle,
uint8_t *  buffer,
uint16_t *  lengthP 
)

Read the value of a characteristic from the local GattServer.

Parameters:
[in]connectionHandleConnection Handle.
[in]attributeHandleAttribute handle for the value attribute of the characteristic.
[out]bufferA buffer to hold the value being read.
[in,out]lengthPLength of the buffer being supplied. If the attribute value is longer than the size of the supplied buffer, this variable will return the total attribute value length (excluding offset). The application may use this information to allocate a suitable buffer size.
Returns:
BLE_ERROR_NONE if a value was read successfully into the buffer.
Note:
This API is a version of the above, with an additional connection handle parameter to allow fetches for connection-specific multivalued attributes (such as the CCCDs).

Definition at line 1084 of file BLE.h.

SecurityManager & securityManager (  )

Accessors to SecurityManager.

All SecurityManager related functionality requires going through this accessor.

Returns:
A reference to a SecurityManager object associated to this BLE instance.

Definition at line 246 of file BLE.cpp.

const SecurityManager & securityManager (  ) const

A const alternative to securityManager().

Returns:
A const reference to a SecurityManager object associated to this BLE instance.

Definition at line 237 of file BLE.cpp.

void setActiveScan ( bool  activeScanning )

Set up parameters for GAP scanning (observer mode).

Parameters:
[in]activeScanningSet to True if active-scanning is required. This is used to fetch the scan response from a peer if possible.

Once the scanning parameters have been configured, scanning can be enabled by using startScan().

Definition at line 745 of file BLE.h.

ble_error_t setAddress ( BLEProtocol::AddressType_t  type,
const BLEProtocol::AddressBytes_t  address 
)

Set the BTLE MAC address and type.

Returns:
BLE_ERROR_NONE on success.

Definition at line 294 of file BLE.h.

ble_error_t setAdvertisingData ( const GapAdvertisingData advData )

Setup a particular, user-constructed advertisement payload for the underlying stack.

It would be uncommon for this API to be used directly; there are other APIs to build an advertisement payload (see above).

Definition at line 518 of file BLE.h.

void setAdvertisingInterval ( uint16_t  interval )
Parameters:
[in]intervalAdvertising interval in units of milliseconds. Advertising is disabled if interval is 0. If interval is smaller than the minimum supported value, then the minimum supported value is used instead. This minimum value can be discovered using getMinAdvertisingInterval().

This field must be set to 0 if connectionMode is equal to ADV_CONNECTABLE_DIRECTED.

Note:
Decreasing this value allows central devices to detect a peripheral faster, at the expense of more power being used by the radio due to the higher data transmit rate.
Note:
WARNING: This API previously used 0.625ms as the unit for its 'interval' argument. That required an explicit conversion from milliseconds using Gap::MSEC_TO_GAP_DURATION_UNITS(). This conversion is no longer required as the new units are milliseconds. Any application code depending on the old semantics needs to be updated accordingly.

Definition at line 349 of file BLE.h.

void setAdvertisingParams ( const GapAdvertisingParams advParams )

Set up a particular, user-constructed set of advertisement parameters for the underlying stack.

It would be uncommon for this API to be used directly; there are other APIs to tweak advertisement parameters individually (see above).

Definition at line 414 of file BLE.h.

ble_error_t setAdvertisingPayload ( void   )

Dynamically reset the accumulated advertising payload and scanResponse.

The application must clear and re- accumulates a new advertising payload (and scanResponse) before using this API.

Returns:
BLE_ERROR_NONE when the advertising payload is set successfully.
Note:
The new APIs in Gap update the underlying advertisement payload implicitly.

Definition at line 563 of file BLE.h.

void setAdvertisingTimeout ( uint16_t  timeout )
Parameters:
[in]timeoutAdvertising timeout (in seconds) between 0x1 and 0x3FFF (1 and 16383). Use 0 to disable the advertising timeout.

Definition at line 399 of file BLE.h.

void setAdvertisingType ( GapAdvertisingParams::AdvertisingType  advType )

Set the GAP advertising mode to use for this device.

Definition at line 319 of file BLE.h.

ble_error_t setAppearance ( GapAdvertisingData::Appearance  appearance )

Set the appearance characteristic in the Gap service.

Parameters:
[in]appearanceThe new value for the device-appearance.

Definition at line 973 of file BLE.h.

ble_error_t setDeviceName ( const uint8_t *  deviceName )

Set the device name characteristic in the Gap service.

Parameters:
[in]deviceNameThe new value for the device-name. This is a UTF-8 encoded, NULL-terminated string.

Definition at line 932 of file BLE.h.

ble_error_t setPreferredConnectionParams ( const Gap::ConnectionParams_t params )

Set the GAP peripheral's preferred connection parameters.

These are the defaults that the peripheral would like to have in a connection. The choice of the connection parameters is eventually up to the central.

Parameters:
[in]paramsThe structure containing the desired parameters.

Definition at line 899 of file BLE.h.

ble_error_t setScanInterval ( uint16_t  interval )

Set up the scanInterval parameter for GAP scanning (observer mode).

Parameters:
[in]intervalScan interval (in milliseconds) [valid values lie between 2.5ms and 10.24s].

The scanning window divided by the interval determines the duty cycle for scanning. For example, if the interval is 100ms and the window is 10ms, then the controller will scan for 10 percent of the time. It is possible to have the interval and window set to the same value. In this case, scanning is continuous, with a change of scanning frequency once every interval.

Once the scanning parameters have been configured, scanning can be enabled by using startScan().

Definition at line 677 of file BLE.h.

ble_error_t setScanParams ( uint16_t  interval = GapScanningParams::SCAN_INTERVAL_MAX,
uint16_t  window = GapScanningParams::SCAN_WINDOW_MAX,
uint16_t  timeout = 0,
bool  activeScanning = false 
)

Set up parameters for GAP scanning (observer mode).

Parameters:
[in]intervalScan interval (in milliseconds) [valid values lie between 2.5ms and 10.24s].
[in]windowScan Window (in milliseconds) [valid values lie between 2.5ms and 10.24s].
[in]timeoutScan timeout (in seconds) between 0x0001 and 0xFFFF; 0x0000 disables timeout.
[in]activeScanningSet to True if active-scanning is required. This is used to fetch the scan response from a peer if possible.

The scanning window divided by the interval determines the duty cycle for scanning. For example, if the interval is 100ms and the window is 10ms, then the controller will scan for 10 percent of the time. It is possible to have the interval and window set to the same value. In this case, scanning is continuous, with a change of scanning frequency once every interval.

Once the scanning parameters have been configured, scanning can be enabled by using startScan().

Note:
The scan interval and window are recommendations to the BLE stack.

Definition at line 650 of file BLE.h.

ble_error_t setScanTimeout ( uint16_t  timeout )

Set up parameters for GAP scanning (observer mode).

Parameters:
[in]timeoutScan timeout (in seconds) between 0x0001 and 0xFFFF; 0x0000 disables timeout.

The scanning window divided by the interval determines the duty cycle for scanning. For example, if the interval is 100ms and the window is 10ms, then the controller will scan for 10 percent of the time. It is possible to have the interval and window set to the same value. In this case, scanning is continuous, with a change of scanning frequency once every interval.

Once the scanning parameters have been configured, scanning can be enabled by using startScan().

Note:
The scan interval and window are recommendations to the BLE stack.

Definition at line 727 of file BLE.h.

ble_error_t setScanWindow ( uint16_t  window )

Set up the scanWindow parameter for GAP scanning (observer mode).

Parameters:
[in]windowScan Window (in milliseconds) [valid values lie between 2.5ms and 10.24s].

The scanning window divided by the interval determines the duty cycle for scanning. For example, if the interval is 100ms and the window is 10ms, then the controller will scan for 10 percent of the time. It is possible to have the interval and window set to the same value. In this case, scanning is continuous, with a change of scanning frequency once every interval.

Once the scanning parameters have been configured, scanning can be enabled by using startScan().

Definition at line 701 of file BLE.h.

ble_error_t setTxPower ( int8_t  txPower )

Set the radio's transmit power.

Parameters:
[in]txPowerRadio transmit power in dBm.

Definition at line 1000 of file BLE.h.

ble_error_t shutdown ( void   )

Purge the BLE stack of GATT and GAP state.

init() must be called afterwards to re-instate services and GAP state. This API offers a way to repopulate the GATT database with new services and characteristics.

Definition at line 165 of file BLE.cpp.

ble_error_t startAdvertising ( void   )

Start advertising.

Definition at line 605 of file BLE.h.

ble_error_t startScan ( T *  object,
void(T::*)(const Gap::AdvertisementCallbackParams_t *params)  memberCallback 
)

Same as above, but this takes an (object, method) pair for a callback.

ble_error_t startScan ( void(*)(const Gap::AdvertisementCallbackParams_t *params)  callback )

Start scanning (Observer Procedure) based on the parameters currently in effect.

Parameters:
[in]callbackThe application-specific callback to be invoked upon receiving every advertisement report. This can be passed in as NULL, in which case scanning may not be enabled at all.

Definition at line 763 of file BLE.h.

ble_error_t stopAdvertising ( void   )

Stop advertising.

Definition at line 617 of file BLE.h.

ble_error_t stopScan ( void   )

Stop scanning.

The current scanning parameters remain in effect.

Return values:
BLE_ERROR_NONEif successfully stopped scanning procedure.

Definition at line 788 of file BLE.h.

ble_error_t updateCharacteristicValue ( Gap::Handle_t  connectionHandle,
GattAttribute::Handle_t  attributeHandle,
const uint8_t *  value,
uint16_t  size,
bool  localOnly = false 
)

Update the value of a characteristic on the local GattServer.

A version of the above, with a connection handle parameter to allow updates for connection-specific multivalued attributes (such as the CCCDs).

Parameters:
[in]connectionHandleConnection Handle.
[in]attributeHandleHandle for the value attribute of the Characteristic.
[in]valueA pointer to a buffer holding the new value.
[in]sizeSize of the new value (in bytes).
[in]localOnlyShould this update be kept on the local GattServer regardless of the state of the notify/indicate flag in the CCCD for this Characteristic? If set to true, no notification or indication is generated.
Returns:
BLE_ERROR_NONE if we have successfully set the value of the attribute.

Definition at line 1145 of file BLE.h.

ble_error_t updateCharacteristicValue ( GattAttribute::Handle_t  attributeHandle,
const uint8_t *  value,
uint16_t  size,
bool  localOnly = false 
)

Update the value of a characteristic on the local GattServer.

Parameters:
[in]attributeHandleHandle for the value attribute of the characteristic.
[in]valueA pointer to a buffer holding the new value.
[in]sizeSize of the new value (in bytes).
[in]localOnlyShould this update be kept on the local GattServer regardless of the state of the notify/indicate flag in the CCCD for this characteristic? If set to true, no notification or indication is generated.
Returns:
BLE_ERROR_NONE if we have successfully set the value of the attribute.

Definition at line 1111 of file BLE.h.

ble_error_t updateConnectionParams ( Gap::Handle_t  handle,
const Gap::ConnectionParams_t params 
)

Update connection parameters while in the peripheral role.

In the peripheral role, this will send the corresponding L2CAP request to the connected peer and wait for the central to perform the procedure.

Parameters:
[in]handleConnection Handle
[in]paramsPointer to desired connection parameters. If NULL is provided on a peripheral role, the parameters in the PPCP characteristic of the GAP service will be used instead.

Definition at line 918 of file BLE.h.

void waitForEvent ( void   )

Yield control to the BLE stack or to other tasks waiting for events.

This is a sleep function that will return when there is an application-specific interrupt, but the MCU might wake up several times before returning (to service the stack). This is not always interchangeable with WFE().

Definition at line 255 of file BLE.cpp.


Field Documentation

const InstanceID_t DEFAULT_INSTANCE = 0 [static]

The value of the BLE::InstanceID_t for the default BLE instance.

Definition at line 230 of file BLE.h.

static const InstanceID_t NUM_INSTANCES = 1 [static]

The number of permitted BLE instances for the application.

Definition at line 235 of file BLE.h.