STM32WBA_BLE_UM

STM32WBA Bluetooth® LE Stack User Manual

 

Revision history

Rev 1.0 (27 January 2023): First release.

Rev 1.1 (March 2023): Update maximum number of supported Links and a new condition to call the BleStack_Process.

Rev 1.2 (2 June 2023): Update Bluetooth® LE library folder structure picture (add ble_legacy.h file); Fix some spell errors; Define bitmap of “options” argument of “BleStack_init_t”; Replace BLE with Bluetooth® LE.

Rev 1.3 (6 October 2023): Update the section 2.1.2 library variants: Add “figure 2: Bluetooth® LE stack variants”; Update the paragraph detailing the 4 variants to be clearer; Update the certified features.

Rev 1.4 (10 November 2023): Update timer ID parameter of BLEPLAT_Timer functions.

Rev 1.5 (20 December 2023): Update table of supported features variants. Update libraries compilation information.

Rev 1.6 (11 January 2024): Minor update of the table of supported features variants. Add unaligned memory access note.

Rev 1.7 (22 January 2024): Update table of supported features variants.

Rev 1.8 (10 April 2024): Update BLE Stack variants. Add BLE Stack wrapper section. Figures updated.

Rev 1.9 (13 May 2024): Update BLE Stack and Link Layer Footprint; Update BLE Stack user interface section.

 

Contents

List of tables. 1

List of figures. 1

1                            About this document 1

1.1                        Purpose  1

1.2                        Scope  1

1.3                        Acronyms definitions  1

1.4                        References  1

2                            Bluetooth® LE stack overview.. 1

2.1                        Release contents  1

2.1.1                    Folder structure. 1

2.1.2                    Library variants. 1

2.2                        Real-Time environment 1

2.3                        Library dependencies  1

2.4                        Library compilation options  1

2.5                        Application compilation options  1

3                            Bluetooth® LE stack user interface. 1

3.1                        Bluetooth® LE stack initialization  1

3.2                        Bluetooth® LE stack process  1

3.3                        Bluetooth® LE stack ACI/HCI interface  1

3.3.1                    Transparent Mode. 1

3.3.2                    Direct Mode. 1

3.3.2.1                    Bluetooth® LE stack wrapper 1

3.3.2.2                    Commands and data sending. 1

3.3.2.3                    Asynchronous events and data reception. 1

4                            Bluetooth® LE stack porting. 1

4.1                        Bluetooth® LE platform initialization  1

4.2                        Bluetooth® LE platform functions  1

4.2.1                    NVM functions. 1

4.2.2                    Timer functions. 1

4.2.3                    AES functions. 1

4.2.4                    PKA functions. 1

4.2.5                    RNG functions. 1

 

 

List of tables

Table 1: Acronyms definitions  1

Table 2: Supported features of each Bluetooth® LE stack variant 1

Table 3: BleStack_Init function  1

Table 4: BleStack_Init function's parameters  1

Table 5: BleStack_Process function  1

Table 6: BleStack_Request function  1

Table 7: BLECB_Indication function  1

Table 8: BLEPLAT_Init function  1

Table 9: BLEPLAT functions' returns  1

Table 10: BLEPLAT NVM functions  1

Table 11: BLEPLAT Timer functions  1

Table 12: BLEPLAT AES functions  1

Table 13: BLEPLAT PKA functions  1

Table 14: BLEPLAT RNG function  1

List of figures

Figure 1: Bluetooth® LE library folder structure. 1

Figure 2: Bluetooth® LE stack variants. 1

 


1                            About this document

1.1                        Purpose

This document describes to an application developer how to integrate the STM32WBAxx Bluetooth® LE stack library.

1.2                        Scope

This document covers only the Bluetooth® LE stack library integration, and it does not include the Link Layer integration aspects.

1.3                        Acronyms definitions

Acronym

Definition

HCI

Host Controller interface

ACI

Application Controller Interface

N/A

Not Applicable

Table 1: Acronyms definitions

1.4                        References

-       STM32WBA_BLE_Wireless_Interface.html

-       STM32WBAxx reference manual

2                            Bluetooth® LE stack overview

2.1                        Release contents

2.1.1                    Folder structure

The Bluetooth® LE stack delivery contains 3 folders as following:

Figure 1: Bluetooth® LE library folder structure

 

- “doc” folder contains the current document and “STM32WBA_BLE_Wireless_Interface.html” which describes the Bluetooth® LE Application Commands Interface (ACI) and the Host Commands Interface (HCI).

- “include” folder contains the header files of the Bluetooth® LE stack library interface. These files contain some definitions of constants and types and the declarations of ACI and HCI functions. It also contains the declarations of some external modules’ functions used by the Bluetooth® LE stack (for more details see section 4.2)

- “lib” folder contains the 6 Bluetooth® LE stack library variants described in the following section.

2.1.2                    Library variants

The Bluetooth® LE stack library is delivered in 6 variants as following:

·         4 variants containing the Bluetooth® LE host stack:

o   Full stack (stm32wba_ble_stack_full.a)

o   Basic Plus stack (stm32wba_ble_stack_basic_plus.a)

o   Basic stack (stm32wba_ble_stack_basic.a)

o   Peripheral Only stack (stm32wba_ble_stack_po.a)

 

·         2 variants without the Bluetooth® LE host stack (they contain the LE Controller only):

o   Link Layer Only stack (stm32wba_ble_stack_llo.a)

o   Link Layer Only Basic stack (stm32wba_ble_stack_llobasic.a)


Figure 2: Bluetooth® LE stack variants

Here are the 6 Bluetooth® LE stack variants details:

-       Full stack (stm32wba_ble_stack_full.a) includes the LE Controller and the Host Stack, both with all the supported features.
It contains all the legacy stack supported features plus the advertising extensions, GATT caching, Enhanced ATT,  ACI HCI flow control, isochronous support for audio, L2CAP connection oriented channels.

Note: This Bluetooth® LE stack variant can be configured to run in controller only mode (host stack is bypassed).
See the parameter “options” of the initialization structure BleStack_init_t parameters in section 3.1 to enable/disable the controller only mode.

-       Basic Plus stack (stm32wba_ble_stack_basic_plus.a) includes the LE Controller and the Host Stack, both with the basic features along with additional features as Extended Advertising/Scanning, LE Power Control and Connection Subrating, Enhanced ATT, L2CAP connection oriented channels and GATT caching features.

-       Basic stack (stm32wba_ble_stack_basic.a) includes the LE Controller and the Host Stack, both with the basic features.
It contains only Bluetooth® LE legacy features without extended advertising, neither GATT caching, nor ACI HCI flow control, nor isochronous support, nor L2CAP connection oriented channels. The Host Stack is included, and it supports all the basic GATT, GAP and L2CAP features.

-       Peripheral Only stack (stm32wba_ble_stack_po.a) includes the LE Controller and the Host Stack, both with the basic features but only for peripheral role.
The Host Stack is included, and it supports all the basic GATT, GAP and L2CAP features.

-       Link Layer Only stack (stm32wba_ble_stack_llo.a) includes only the LE Controller with all the supported features.
It contains all the features supported by the full stack but doesn’t include the Host Stack.

-       Link Layer Only Basic stack (stm32wba_ble_stack_llobasic.a) includes only the LE Controller with the basic features.
It contains all the features supported by the basic stack but doesn’t include the Host Stack.

 

For more information, please refer to “STM32WBA_BLE_Wireless_Interface.html” to know which ACI and HCI command/event is supported by each stack configuration.

The table below details the supported features for each Bluetooth® LE stack variants:

 

Configuration

FULL

 Host Stack + LE Controller
(stm32wba_ble_stack_full)

BASIC_PLUS

Host Stack + LE Controller
(stm32wba_ble_stack_basic_plus)

BASIC

Host Stack + LE Controller
(stm32wba_ble_stack_basic)

PERIPHERAL_ONLY

Host Stack + LE Controller
(stm32wba_ble_stack_po)

LL_ONLY

LE Controller Only
(stm32wba_ble_stack_llo)

LL_ONLY_BASIC

LE Controller Only
(stm32wba_ble_stack_llobasic)

Link Layer library dependency

LinkLayer_BLE_Full_lib

LinkLayer_BLE_Basic_Plus_lib

LinkLayer_BLE_Basic_lib

LinkLayer_BLE_Peripheral_Only_lib

LinkLayer_BLE_Full_lib

LinkLayer_BLE_Basic_lib

Stack Library Flash Footprint (1)

81.1 kB

66.9 kB

54.6 kB

41.8 kB

23.3 kB

8.8 kB

 

Link Layer Library Flash Footprint (1)

254.3 kB

139.7 kB

99.2 kB

78.3 kB

254.3 kB

99.2 kB

 

Advertising

Certified

Certified

Certified

Certified

Certified

Certified

Scanning

Certified

Certified

Certified

Not Supported

Certified

Certified

Connection Slave

Certified

Certified

Certified

Certified

Certified

Certified

Connection Master

Certified

Certified

Certified

Not Supported

Certified

Certified

 

Data length extension

Certified

Certified

Certified

Certified

Certified

Certified

Privacy

Certified

Certified

Certified

Certified

Certified

Certified

LE Encryption

Certified

Certified

Certified

Certified

Certified

Certified

Legacy Pairing, LE secure connections

Certified

Certified

Certified

Certified

Certified

Certified

LE 2Mbit PHY

Certified

Certified

Certified

Certified

Certified

Certified

LE Coded PHY

Certified

Certified

Certified

Certified

Certified

Certified

Channel Selection Algorithm #2

Certified

Certified

Certified

Certified

Certified

Certified

Direct Test Mode

Certified

Certified

Certified

Certified

Certified

Certified

Extended Advertising

Certified

Certified

Not Supported

Not Supported

Certified

Not Supported

Periodic Advertising

Certified

Not Supported

Not Supported

Not Supported

Certified

Not Supported

Sleep Clock Accuracy Update

Certified

Not Supported

Not Supported

Not Supported

Certified

Not Supported

 

AOA/AOD

Certified

Not Supported

Not Supported

Not Supported

Certified

Not Supported

Periodic Sync Transfer

Certified

Not Supported

Not Supported

Not Supported

Certified

Not Supported

Connected Isochronous

Certified

Not Supported

Not Supported

Not Supported

Certified

Not Supported

Isochronous Broadcaster

Certified

Not Supported

Not Supported

Not Supported

Certified

Not Supported

Isochronous Synchronized

Certified

Not Supported

Not Supported

Not Supported

Certified

Not Supported

LE Power Control

Certified

Certified

Not Supported

Not Supported

Certified

Not Supported

 

Connection Subrating

Certified

Certified

Not Supported

Not Supported

Certified

Not Supported

 

Channel Classification enhancement

Certified

Not Supported

Not Supported

Not Supported

Certified

Not Supported

Periodic Advertising Enhancement

Certified

Not Supported

Not Supported

Not Supported

Certified

Not Supported

GATT Client

Certified

Certified

Certified

Not Supported

N/A

N/A

Config HCI only

Certified

Not Supported

Not Supported

Not Supported

N/A

N/A

Enhanced ATT

Certified

Certified

Not Supported

Not Supported

N/A

N/A

LE L2CAP Connection Oriented channel

Certified

Certified

Not Supported

Not Supported

N/A

N/A

GATT Caching

Certified

Certified

Not Supported

Not Supported

N/A

N/A

 

Encrypted Advertising Data

Enabled

Not Supported

Not Supported

Not Supported

N/A

N/A

Number of Links

Up to 20 (2)

Up to 20 (2)

Up to 20 (2)

Up to 20 (2)

Up to 20 (2)

Up to 20 (2)

Table 2: Supported features of each Bluetooth® LE stack variant

(1): These values were computed with STM32CubeWBA Firmware Package v1.4.0 using Keil® environment with optimization size option.

(2): It might be limited to 8 or 20 links depending on the Link Layer library used.

2.2                        Real-Time environment

The Bluetooth® LE stack library is independent from the real-time software environment as well as any real-time resources.

The functions of this library used during run time are:

- The Bluetooth® LE stack commands (HCI, ACI...),

- The Bluetooth® LE stack process,

- The Bluetooth® LE stack callback functions called by the link layer or the platform software (PKA, Timer...).

All these functions must be called from the same level of execution, i.e., from the same task when using a real-time operating system or from the main loop in a bare metal environment.

2.3                        Library dependencies

The Bluetooth® LE stack library depends on (i.e. it must be linked with the following libraries):

-       STM32WBAxx Link Layer libraries (c.f. Table 2 Bluetooth® LE stack variants for Link Layer library configuration dependency).

-       Standard C library:

o   Only basic memory functions are used (memcpy, memset, memmove, memcmp)

2.4                        Library compilation options

The Bluetooth® LE stack library was compiled with the following options in Keil® environment:

-       General options:

o    Byte order: Little-endian

o    FPU: VFPv5 single precision

-       C/C++ Compilation options

o    Compilation options

--library_interface=aeabi_clib : Used to generate AEABI-compliant object code

--mno-unaligned-access : Used to enforce aligned memory access

o    Plain 'char' is unsigned.

 

As mentioned above, the Bluetooth® LE stack library is AEABI compliant; The advantage of adhering to AEABI is that the Bluetooth® LE stack library can be linked with any other AEABI-compliant module, even modules produced by tools provided by other vendors than Keil®.

For the enum type, the Keil® C/C++ compiler uses the smallest type required to hold enum constants (-fshort-enums), preferring signed rather than unsigned.

2.5                        Application compilation options

These compilation options are compulsory:

o    Plain 'char' is unsigned

o    Short enum:

·         For IAR® compiler, this option is set by default

·         Keil µvision® environment with ARM® CC compiler, the following option shall be added:   -fshort-enums

 

In CubeIDE environment with GCC compiler, there is no need to add specific compiler options or linker options.

3                            Bluetooth® LE stack user interface

To use the main functions of the Bluetooth® LE stack library, the user application code needs to include “blestack.h”.

In addition, to be able to directly call Bluetooth® LE commands (see section 3.3.2), the application needs to also include “blecore.h”.

3.1                        Bluetooth® LE stack initialization

 

Functions

Parameters

Return Value

BleStack_Init

BleStack_init_t* init_params_p

tBleStatus

Table 3: BleStack_Init function

BleStack_Init: The Bluetooth® LE Stack initialization routine. This function is used to define the memory and configure the Bluetooth® LE Stack.
All BleStack_init_t parameters are described below:

 

BleStack_init_t parameters

Definition

Value

uint16_t numAttrRecord

Maximum number of attribute records related to all the required characteristics (excluding the services) that can be stored in the GATT database, for the specific Bluetooth® LE user application.

Value = <number of user attributes> + 9                          

 

Min value = 9

 

Max value: depending on the GATT database defined by the user application.

 

uint16_t numAttrServ

Defines the maximum number of services that can be stored in the GATT database. Note that the GAP and GATT services are automatically added at initialization so this parameter must be the number of user services increased by two.

Value = <number of user services> + 2.

 

Min value = 2

 

Max value: depending on the GATT database defined by the user application.

 

uint16_t attrValueArrSize

Size of the storage area for the attribute values

By default, two services are present and must be included, with dedicated characteristics:

• Generic access service: service UUID 0x1800, with its three mandatory characteristics:

o   Device name UUID 0x2A00.

o   Appearance UUID 0x2A01.

o   Peripheral preferred connection parameters. UUID 0x2A04.

• Generic attribute service. UUID 0x1801, with one optional characteristic:

o   Service changed UUID 0x2A05.

Each characteristic contributes to the attrValueArrSize value as follows:

• Characteristic value length plus:

o   5 bytes if characteristic UUID is 16 bits

o   19 bytes if characteristic UUID is 128 bits

o   2 bytes if characteristic has a server configuration descriptor

o   2 bytes * NUM_OF_LINKs if the characteristic has a client configuration descriptor

o   2 bytes if the characteristic has extended properties

Depends on the number of attributes used by the application.

uint8_t numOfLinks

Maximum number of simultaneous connections that the device supports.

Min value: 1

Max value: 20

uint8_t prWriteListSize

Maximum number of supported “prepare ATT write request”.

Value defined by the macro:

DIVC (max_char_size, default_att_mtu - 5) * 2

 

max_char_size: Maximum characteristic’s value size

BLE_DEFAULT_ATT_MTU = 23

 

uint8_t mblockCount

Number of allocated memory blocks for the Bluetooth® LE stack.

Value defined by the macro:

BLE_MBLOCKS_CALC (PREP_WRITE_LIST_SIZE, MAX_ATT_MTU, NUM_LINKS) + MBLOCK_COUNT_MARGIN)

 

With:
- PREP_WRITE_LIST_SIZE defined by the parameter prWriteListSize.
- MAX_ATT_MTU defined by the attMtu parameter

- NUM_LINKS defined by the numOfLinks parameter
- MBLOCK_COUNT_MARGIN the memory margin to take.

uint16_t attMtu

Maximum ATT MTU size supported.

 

 

Min value: 23

Max value: 512

uint16_t max_coc_mps

Used in APIs in l2cap_coc.c to process with a L2CAP connection, send/receive data…

Maximum value of the connection-oriented channel Maximum Payload Size.

Min value: 23

Max value: 248

 

uint8_t max_coc_nbr

Used in APIs in l2cap_coc.c to process with a L2CAP connection, send/receive data…

Maximum number of connection-oriented channels.

Min value: 0

Max value: 64

 

uint8_t max_coc_initiator_nbr

Used in APIs in l2cap_coc.c to process with a L2CAP connection, send/receive data…

Maximum number of connection-oriented channels in initiator mode.

Min value:0

Max value: max_coc_nbr

 

uint8_t* bleStartRamAddress

Start address of the RAM buffer allocated for Bluetooth® LE stack library. It must be a 32bit aligned RAM area.

 

(uint32_t) total_buffer_size

Size of the RAM buffer allocated for Bluetooth® LE stack library.

Value defined by the macro:
BLE_TOTAL_BUFFER_SIZE (NUM_LINKS, MBLOCK_COUNT)

 

With

- NUM_LINKS: the maximum number of links defined by the parameter numOfLinks.
- MBLOCK_COUNT: the number of allocated memory blocks, defined by the parameter mblockCount.

uint8_t* bleStartRamAddress_GATT

Start address of the RAM buffer allocated for GATT database. It must be a 32bit aligned RAM area.

 

uint32_t total_buffer_size_GATT

Size of the RAM buffer allocated for GATT database.

Value defined by the macro:
BLE_TOTAL_BUFFER_SIZE_GATT (NUM_ATTR_RECORD, NUM_ATTR_SERV, ATTR_VALUE_ARR_SIZE)

 

With

- NUM_ATTR_RECORD: defined by the parameter numAttrRecord.
- NUM_ATTR_SERV: defined by the parameter numAttrServ.

- ATTR_VALUE_ARR_SIZE: defined by the parameter attrValueArrSize.

 

uint16_t options

Options flags. Bitmap of the “BLE_OPTIONS_...” definitions:

bit number

bit value = 1

bit value = 0

0

LL only

LL + host

1

Remove the Service Changed characteristic

Add the Service Changed characteristic

2

Device name Read-Only

Device name R/W

3

Extended adv supported

Extended adv not supported

5

Reduced GATT database in NVM

Full GATT database in NVM

6

GATT caching is used

GATT caching is not used

7

LE Power Class 1

LE Power Class 2-3

8

Appearance Writable

Appearance Read-Only

9

Enhanced ATT supported

Enhanced ATT not supported

others

Reserved

BLE_OPTIONS_LL_ONLY = 0x0001U,

BLE_OPTIONS_NO_SVC_CHANGE_DESC = 0x0002U,

BLE_OPTIONS_DEV_NAME_READ_ONLY = 0x0004U,

BLE_OPTIONS_EXTENDED_ADV = 0x0008U,

BLE_OPTIONS_REDUCED_DB_IN_NVM = 0x0020U,

BLE_OPTIONS_GATT_CACHING = 0x0040U,

BLE_OPTIONS_POWER_CLASS_1 = 0x0080U,

BLE_OPTIONS_APPEARANCE_WRITABLE = 0x0100U

BLE_OPTIONS_ENHANCED_ATT = 0x0200U

uint32_t debug

Debug flags

BLE_DEBUG_RAND_ADDR_INIT = 0x00000010UL

Table 4: BleStack_Init function's parameters

Example:

BleStack_init_t pInitParams;

 

pInitParams.numAttrRecord           = CFG_BLE_NUM_GATT_ATTRIBUTES;

pInitParams.numAttrServ             = CFG_BLE_NUM_GATT_SERVICES;

pInitParams.attrValueArrSize        = CFG_BLE_ATT_VALUE_ARRAY_SIZE;

pInitParams.prWriteListSize         = CFG_BLE_ATTR_PREPARE_WRITE_VALUE_SIZE;

pInitParams.attMtu                  = CFG_BLE_MAX_ATT_MTU;

pInitParams.max_coc_nbr             = CFG_BLE_MAX_COC_NUMBER;

pInitParams.max_coc_mps             = CFG_BLE_MAX_COC_MPS;

pInitParams.max_coc_initiator_nbr   = CFG_BLE_MAX_COC_INITIATOR_NBR;

pInitParams.numOfLinks              = CFG_BLE_NUM_LINK;

pInitParams.mblockCount             = CFG_BLE_MBLOCK_COUNT;

pInitParams.bleStartRamAddress      = (uint8_t*)buffer;

pInitParams.total_buffer_size       = BLE_DYN_ALLOC_SIZE;

pInitParams.bleStartRamAddress_GATT = (uint8_t*)gatt_buffer;

pInitParams.total_buffer_size_GATT  = BLE_GATT_BUF_SIZE;

pInitParams.debug                   = 0x10; // static random address generation

pInitParams.options                 = 0x0000;

return_status = BleStack_Init(&pInitParams);

 

 

3.2                        Bluetooth® LE stack process

The BleStack_Process function runs all Host stack layers’ dedicated processes.

Functions

Parameters

Return Value

BleStack_Process

None

BLE_SLEEPMODE_RUNNING (0):
-> Bluetooth® LE Stack Process must be executed.

BLE_SLEEPMODE_CPU_HALT (1):
 -> Bluetooth® LE Stack Process does not have to be executed.

Table 5: BleStack_Process function

The BleStack_Process function shall be called in the following conditions:

-       This function shall be called regularly to handle all stack callbacks when needed. If it returns BLE_SLEEPMODE_RUNNING, it shall be re-called. If it returns BLE_SLEEPMODE_CPU_HALT, there is no need to call this function again and the MCU could go to sleep mode.

-       The Link Layer has been scheduled.

-       An ACI/HCI command, ACL data or ISO data has been sent to the Bluetooth® LE stack (either by calling BleStack_Request or by direct call to a specific command).

-    By the platform software at the timer expiry or the end of PKA activity.

 

Example:

return_status = BleStack_Process();

if (return_status == BLE_SLEEPMODE_RUNNING)

  // BleStack_Process shall be re-called again

else

  // The MCU can go to sleep mode

 

 

3.3                        Bluetooth® LE stack ACI/HCI interface

We have two ways to send commands and receive events in ST’s Bluetooth® LE Stack: Transparent Mode or Direct Mode.

3.3.1                    Transparent Mode

To use Bluetooth® LE stack in Transparent Mode, a buffer that contains the ACI/HCI command or ACL data packet shall be passed as parameter to the function BleStack_Request.

The ACI/HCI command is executed. The response event (command complete/ command status) is returned in the same buffer, and the size (in bytes) of the response event is given by the function’s return value.

Functions

Parameters

Return Value

BleStack_Request

uint8_t* buffer [IN/OUT]:
Buffer of bytes in the Bluetooth® LE standard format HCI/ACI command packet or ACL data packet. The response packet is returned in the same buffer and the size (in bytes) of the response is given by the function’s return value.

The size (uint16_t) of the response packet returned in the buffer parameter.

Table 6: BleStack_Request function

Example:

// It is recommended to initiate the buffer at maximum length that Bluetooth® LE Stack supports.

uint8_t reset_cmd[255] = {0x01, 0x03, 0x0C, 0x00};

/* BLE Stack executes Reset command, the Command Complete Event is returned in reset_cmd array,

the total length of event is returned in event_length. */

uint16_t event_length = BleStack_Request(reset_cmd);

// The response packet is in Bluetooth® LE standard format.

uint8_t cmd_status = reset_cmd[6];

 

The ACI/HCI asynchronous events must be handled in the BLECB_Indication callback.

This function is called by the Bluetooth® LE Stack with the following parameters:

Functions

Parameters

Return Value

BLECB_Indication

- const uint8_t* data: The data buffer

- uint16_t length: The length of the data buffer

- const uint8_t* ext_data: The extended data buffer. This buffer is used only for ISO data and ACL data events

- uint16_t ext_length: The length of the extended data buffer

uint8_t: Up to the user to define the return values

Table 7: BLECB_Indication function

Example:

uint8_t BLECB_Indication(const uint8_t* data, uint16_t length,

                         const uint8_t* ext_data, uint16_t ext_length)

{

  if (data[0] == HCI_LE_META_EVT_CODE)

  {

    // Check the subevent_code and the parameter length

    if ((data[2] == HCI_LE_CONNECTION_COMPLETE_SUBEVT_CODE) && (data[1] == 0x13))

    {

        hci_le_connection_complete_event_rp0 *p_conn_complete;

        p_conn_complete = (hci_le_connection_complete_event_rp0 *) (data + 3);

 

        printf("Connection DONE - Connection handle: 0x%04X\n", p_conn_complete->Connection_Handle);

        printf("Connection established with @:%02x:%02x:%02x:%02x:%02x:%02x\n",

                p_conn_complete->Peer_Address[5],

                p_conn_complete->Peer_Address[4],

                p_conn_complete->Peer_Address[3],

                p_conn_complete->Peer_Address[2],

                p_conn_complete->Peer_Address[1],

                p_conn_complete->Peer_Address[0]

                );

        printf("Connection parameters:\n- Connection Interval: %.2f ms\n- Connection latency: %d\n- Supervision Timeout: %d ms\n",

                p_conn_complete->Conn_Interval * 1.25,

                p_conn_complete->Conn_Latency,

                p_conn_complete->Supervision_Timeout * 10

                );

    }

  }

  return 0;

}

 

 3.3.2                    Direct Mode


The Direct Mode provides a dedicated API for each ACI/HCI command and event.

Instead of using BleStack_Request / BLECB_Indication like in transparent mode, the ACI/HCI commands/events can be used through the dedicated functions. Those functions are listed and detailed in the document STM32WBA_BLE_Wireless_Interface.html.

To use the direct mode, the BLE wrapper shall be compiled, that means “ble_wrap.c” needs to be included (see section 3.3.2.1).

 

 3.3.2.1                    Bluetooth® LE stack wrapper

The Bluetooth® LE stack includes a wrapper to execute pre and post processing for each BLE command.

The wrapper is implemented in the include/auto/ble_wrap.c file and defines each pre-processing and post-processing macro.

Each wrapper macro can be defined at application level to execute dedicated code. By default all specific macros are defined to the generic macros : “BLE_WRAP_PREPROC” and “BLE_WRAP_POSTPROC”.

The “BLE_WRAP_PREPROC” and “BLE_WRAP_POSTPROC” are empty macros; it is up to the user to redefine those macros to execute pre and post processing respectively for every command.

Wrapper implementation:

/* Generic BLE command pre-processing macro */

#ifndef BLE_WRAP_PREPROC

#define BLE_WRAP_PREPROC( )

#endif

 

/* Generic BLE command post-processing macro */

#ifndef BLE_WRAP_POSTPROC

#define BLE_WRAP_POSTPROC( )

#endif

 

/* HCI_DISCONNECT pre-processing macro */

#ifndef BLE_WRAP_HCI_DISCONNECT_PREPROC

#define BLE_WRAP_HCI_DISCONNECT_PREPROC BLE_WRAP_PREPROC

#endif

 

/* HCI_DISCONNECT post-processing macro */

#ifndef BLE_WRAP_HCI_DISCONNECT_POSTPROC

#define BLE_WRAP_HCI_DISCONNECT_POSTPROC BLE_WRAP_POSTPROC

#endif

 

 …

 

/* HCI_DISCONNECT wrapper function */

tBleStatus hci_disconnect( uint16_t Connection_Handle,

                           uint8_t Reason )

{

 BLE_WRAP_HCI_DISCONNECT_PREPROC( );

 tBleStatus status = HCI_DISCONNECT( Connection_Handle,

                                     Reason );

 BLE_WRAP_HCI_DISCONNECT_POSTPROC( );

 return status;

}

 

Application example:

/* User can define the specific macros to call their own functions */

/* HCI_DISCONNECT pre-processing macro */

#define BLE_WRAP_HCI_DISCONNECT_PREPROC user_disconnect_preproc()

 

/* HCI_DISCONNECT post-processing macro */

#define BLE_WRAP_HCI_DISCONNECT_POSTPROC user_disconnect_postproc()

 

[OR]

 

/* User can define the generic macros to call their own functions */

#define BLE_WRAP_PREPROC user_preproc()

#define BLE_WRAP_POSTPROC user_postproc()

 

3.3.2.2                    Commands and data sending

Each ACI/HCI command has its own interface, e.g. the HCI Reset command can be called through the “hci_reset” interface.

The HCI commands functions can be found in include/auto/ble_hci_le.h file.

The ACI commands for GAP functions can be found in include /auto/ble_gap_le.h file.

The ACI commands for GATT functions can be found in include /auto/ble_gatt_le.h file.

The ACI commands for HAL functions can be found in include /auto/ble_hal_aci.h file.

The ACI commands for L2CAP functions can be found in include /auto/ble_l2cap_le.h file.

 

Also, it exists a way to use the ACI/HCI commands without using the BLE Wrapper. Those interfaces have the same name as the one listed before, but in uppercase: e.g. HCI Reset command is “HCI_RESET” instead of “hci_reset”.

Those functions can be found in include /auto/ble_raw_api.h file.

 

Example:

// Send HCI Reset command

tBleStatus reset_status = hci_reset();

// Send HCI Reset command without using the BLE Wrapper

tBleStatus reset_status = HCI_RESET();

 

// Send ACI GATT delete include service command

uint16_t Serv_Handle = 0x2456;

uint16_t Include_Handle = 0x8795;

tBleStatus gatt_status =  aci_gatt_del_include_service(Serv_Handle, Include_Handle);

 

3.3.2.3                    Asynchronous events and data reception

To handle ACI/HCI events in its application, the user can choose between two different methods:

1-    “FIFO event handling”

Handle the ACI/HCI events through the BLE Wrapper callback functions (listed in include/auto/ble_events.h file).
In the “BLECB_Indication” function, it is required to push the event data into a FIFO. Then, it is possible to call the “BLE_EventProcess” function each time an event is popped from the FIFO.
The “BLE_EventProcess” function calls the dedicated event callback. To handle the event, its dedicated callback needs to be redefined (e.g. “hci_disconnection_complete_event” callback)

2-    “Raw event handling”

Handle the ACI/HCI event directly when the BLE Stack raises it without using the BLE Wrapper. It requires to redefine the dedicated event callbacks (e.g. “HCI_DISCONNECTION_COMPLETE_EVENT” callback).
If an event is handled in its dedicated callback, the event cannot be handled in the BLECB_Indication callback anymore.

Based on its own application scenario, the user should identify the required Bluetooth® LE events to be detected and handled and the application ‘s specific actions as a response to such events.

When implementing a Bluetooth® LE application, the most common and widely used Bluetooth® LE events are the ones related to the discovery, connection, terminate procedures, services and characteristics discovery procedures, attribute modified events on a GATT server and attribute notification/ indication events on a GATT client.3.3.3.                         

There is one callback per event. All callback functions can be found in include/auto/ble_events.h (for method 1) and include /auto/ble_raw_api.h (for method 2).

Example:

tBleStatus hci_disconnection_complete_event(uint8_t Status,

                                            uint16_t Connection_Handle,

                                            uint8_t Reason)

{

  /* USER CODE BEGIN */

  // What to do when the device is disconnected.

  /* USER CODE END */

}

 

Known limitation :  In “LL only” mode or when using Direct Mode for the event callback, the RAM containing the reported data doesn’t support unaligned access. In these cases, it is advised to use the ble_memcpy/ble_memset/ble_memcmp functions (declared in "mem_intf.h" from link layer libraries) instead of memcpy/memset/memcmp functions when accessing those data.

4                            Bluetooth® LE stack porting

The Bluetooth® LE stack uses some generic HW features but lets the application define them by using HW drivers or emulating some of them by SW code.

All the required porting interfaces by the Bluetooth® LE stack are defined in the bleplat.h

The following features are used and need to be implemented on the application side:

-       NVM: Non-Volatile Memory used by the security database of the Bluetooth® LE stack.

-       Timer: used by several components of the Bluetooth® LE stack.

-       AES: Advanced Encryption Standard used by the security manager layer of the Bluetooth® LE stack.

-       PKA: Public Key Accelerator used by the controller in the Bluetooth® LE stack.

-       RNG: Random Number Generation used by the controller in the Bluetooth® LE stack.

4.1                        Bluetooth® LE platform initialization

 

Functions

Parameters

Return Value

BLEPLAT_Init

None

None

Table 8: BLEPLAT_Init function

This function is called by the Bluetooth® LE stack when it is initialized or reset (via hci_reset). The user shall call here the functions to reset the Timer, AES, PKA, NVM and RNG needed for the Bluetooth® LE stack.

The user must implement the functions mentioned below that are called by the Bluetooth® LE stack at runtime.

4.2                        Bluetooth® LE platform functions

All the BLEPLAT functions are called from the Bluetooth® LE stack process or commands. Those functions shall return one of the following status values:

Status

Value

Description

BLEPLAT_OK

  0

The function did the job and returns an OK status

BLEPLAT_FULL

 -1

The function exits because the HW resource is full

BLEPLAT_BUSY

 -2

The function is busy and is not available for the requested operation

BLEPLAT_EOF

 -3

The function exits and notifies the HW resource (memory for example) reached the end.

BLEPLAT_WARN

 -4

The function runs the asked operation and notifies that the HW resource is near to be full

BLEPLAT_ERROR

 -5

The function exits due to some issue (memory corruption or buffer overflow for example)

Table 9: BLEPLAT functions' returns

4.2.1                    NVM functions

The NVM functions are used to store security database information (security and GATT records) in the NVM, read from the NVM, compare data with the stored data in the NVM and clear the security database or some of it.

 

Functions

Parameters

Return Value

BLEPLAT_NvmAdd:

Store data in the NVM

-   uint8_t type: The type of data to be stored either security data (BLEPLAT_NVM_TYPE_SEC) or GATT data (BLEPLAT_NVM_TYPE_GATT)

-   const uint8_t* data: The data buffer to be stored

-   uint16_t size: The size of data to be stored

-   const uint8_t* extra_data: If there is extra data to be stored too. If not, this parameter shall be passed with “NULL” value

-   uint16_t extra_size: The size of extra data

int: One of the return values described in the section 4.2

BLEPLAT_NvmGet:

Read data from the NVM

-   uint8_t mode: The mode of NVM reading:

o   BLEPLAT_NVM_FIRST
used to read the first record of NVM

o   BLEPLAT_NVM_NEXT
used to read the next record (after a previous call to BLEPLAT_NvmGet)

o   BLEPLAT_NVM_CURRENT
used to read the same record again (after a previous call to BLEPLAT_NvmGet)

-   uint8_t type: The type of data to be read, either security data (BLEPLAT_NVM_TYPE_SEC) or GATT data (BLEPLAT_NVM_TYPE_GATT)

-   uint16_t offset: The offset from which the NVM starts the read an operation.

-   uint8_t* data: The pointer to data read by the function

-   uint16_t size: The size of data to be read

int: One of the return values described in the section 4.2

BLEPLAT_NvmCompare:

Compare passed data as parameter with data stored in the NVM

-   uint16_t offset: The offset from which the NVM starts the comparison

-   const uint8_t* data: The data to be compared with stored data in the NVM

-   uint16_t size: The size of data to be compared

int: One of the return values described in the section 4.2

BLEPLAT_NvmDiscard:

Clear a block from the NVM or the whole NVM, storing the security database (security and GATT records)

-   uint8_t mode: Mode of deleting data from the NVM, either clear all the security database (BLEPLAT_NVM_ALL) or the current read NVM block (BLEPLAT_NVM_CURRENT)

None

Table 10: BLEPLAT NVM functions

4.2.2                    Timer functions

The timer functions are used by the Bluetooth® LE stack to handle all procedures which are time dependent.

The timer should have an accuracy of 1 ms and it is recommended to be able to count up to 24 hours.

Function

Parameters

Return Value

BLEPLAT_TimerStart:

Start the Timer

uint16_t id: The timer ID to be started.

uint32_t timeout: The timeout needed to stop the timer (in ms)

int: One of the return values described in the section 4.2

BLEPLAT_TimerStop:

Stop the Timer

uint16_t id: The timer ID to be stopped

None

BLEPLATCB_TimerExpiry:

The timer callback function called when the timeout of a given timer has elapsed

uint16_t id: The timer ID

None

Table 11: BLEPLAT Timer functions

4.2.3                    AES functions

The AES functions are used by the Bluetooth® LE stack to encrypt a 128-bit single block or to compute CMAC which is needed by Bluetooth® LE security manager.

Function

Parameters

Return Value

BLEPLAT_AesEcbEncrypt:

Encrypt a single 128-bit block with a 128-bit key

const uint8_t* key: table of 16 bytes that contains the key to use (Little Endian format)

const uint8_t* input: table of 16 bytes that contains the block to encrypt

uint8_t* output: table of 16 bytes that is filled by the function with the encrypted block

None

BLEPLAT_AesCmacSetKey:

Set the 128-bit key to be used for CMAC computation

const uint8_t* key: table of 16 bytes that contains the key to use (Little Endian format)

None

BLEPLAT_AesCmacCompute:

CMAC computation: the function can be called several times with output_tag set to 0 to append data to the computation. It must be called once at the end with output_tag not set at 0 to complete the CMAC computation.

const uint8_t* input: table of “input_length” bytes that contains the data to append for the CMAC computation

uint32_t input_length: number of bytes in “input”.

uint8_t* output_tag: must be set to 0 for append. Otherwise: table of 16 bytes that is filled by the function with the computed CMAC tag.

None

Table 12: BLEPLAT AES functions

4.2.4                    PKA functions

The PKA functions are used by the Bluetooth® LE stack to compute the P-256 public key and the DH key used for Bluetooth® LE secure connections.

Function

Parameters

Return Value

BLEPLAT_PkaStartP256Key:

Start P-256 public key generation

const uint32_t* local_private_key: table of 8 x 32-bit words that contains the P-256 private key (Little Endian format)

int: One of the return values described in the section 4.2

BLEPLAT_PkaReadP256Key:

Get result of P-256 public key generation

uint32_t* local_public_key: table of 32 x 32-bit words that is filled by the function with the generated P-256 public key (Little Endian format)

int: One of the return values described in the section 4.2

BLEPLAT_PkaStartDhKey:

Start DH key computation

const uint32_t* local_private_key: table of 8 x 32-bit words that contains the local P-256 private key (Little Endian format)

const uint32_t* remote_public_key: table of 32 x 32-bit words that contains the remote P-256 public key (Little Endian format)

int: One of the return values described in the section 4.2

BLEPLAT_PkaReadDhKey:

Get result of DH key computation

uint32_t* dh_key: table of 8 x 32-bit words that is filled by the function with the generated DH key (Little Endian format)

int: One of the return values described in the section 4.2

BLEPLATCB_PkaComplete:

Callback function implemented by the Bluetooth® LE stack that must be called by the user to inform the Bluetooth® LE stack about completion of P-256 public key generation or DH key computation

None

int: One of the return values described in the section 4.2

Table 13: BLEPLAT PKA functions

4.2.5                    RNG functions

This function is called by the Bluetooth® LE stack to retrieve “n” x 32*bit words of random values.

Function

Parameters

Return Value

BLEPLAT_RngGet:

Get random values.

uint8_t n: number of 32-bit words to read.

uint32_t* val: pointer to a 32-bit table of size ‘n’ that are filled with random values by the function.

None

Table 14: BLEPLAT RNG function


 


ARM CC compiler and Keil µvision are registered trademarks owned by ARM

IAR C/C++ compiler is a registered trademark owned by IAR Systems

 

http://dita.st.com/dx/ditaexchange/Repository/Topics/disclaimer_PUBLIC.xml

 

Please Read Carefully

Information in this document is provided solely in connection with ST products. STMicroelectronics NV and its subsidiaries ("ST") reserve the right to make changes, corrections, modifications or improvements, to this document, and the products and services described herein at any time, without notice.

All ST products are sold pursuant to ST’s terms and conditions of sale.

Purchasers are solely responsible for the choice, selection and use of the ST products and services described herein, and ST assumes no liability whatsoever relating to the choice, selection or use of the ST products and services described herein.

No license, express or implied, by estoppel or otherwise, to any intellectual property rights is granted under this document. If any part of this document refers to any third party products or services it shall not be deemed a license grant by ST for the use of such third party products or services, or any intellectual property contained therein or considered as a warranty covering the use in any manner whatsoever of such third party products or services or any intellectual property contained therein.

UNLESS OTHERWISE SET FORTH IN ST’S TERMS AND CONDITIONS OF SALE ST DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY WITH RESPECT TO THE USE AND/OR SALE OF ST PRODUCTS INCLUDING WITHOUT LIMITATION IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE (AND THEIR EQUIVALENTS UNDER THE LAWS OF ANY JURISDICTION), OR INFRINGEMENT OF ANY PATENT, COPYRIGHT OR OTHER INTELLECTUAL PROPERTY RIGHT.

ST PRODUCTS ARE NOT DESIGNED OR AUTHORIZED FOR USE IN: (A) SAFETY CRITICAL APPLICATIONS SUCH AS LIFE SUPPORTING, ACTIVE IMPLANTED DEVICES OR SYSTEMS WITH PRODUCT FUNCTIONAL SAFETY REQUIREMENTS; (B) AERONAUTIC APPLICATIONS; (C) AUTOMOTIVE APPLICATIONS OR ENVIRONMENTS, AND/OR (D) AEROSPACE APPLICATIONS OR ENVIRONMENTS. WHERE ST PRODUCTS ARE NOT DESIGNED FOR SUCH USE, THE PURCHASER SHALL USE PRODUCTS AT PURCHASER’S SOLE RISK, EVEN IF ST HAS BEEN INFORMED IN WRITING OF SUCH USAGE, UNLESS A PRODUCT IS EXPRESSLY DESIGNATED BY ST AS BEING INTENDED FOR "AUTOMOTIVE, AUTOMOTIVE SAFETY OR MEDICAL" INDUSTRY DOMAINS ACCORDING TO ST PRODUCT DESIGN SPECIFICATIONS. PRODUCTS FORMALLY ESCC, QML OR JAN QUALIFIED ARE DEEMED SUITABLE FOR USE IN AEROSPACE BY THE CORRESPONDING GOVERNMENTAL AGENCY.

Resale of ST products with provisions different from the statements and/or technical features set forth in this document shall immediately void any warranty granted by ST for the ST product or service described herein and shall not create or extend in any manner whatsoever, any liability of ST.

 

ST and the ST logo are trademarks or registered trademarks of ST in various countries.

Information in this document supersedes and replaces all information previously supplied.

The ST logo is a registered trademark of STMicroelectronics. All other names are the property of their respective owners.

© 2024 STMicroelectronics - All rights reserved

STMicroelectronics group of companies

Australia - Belgium - Brazil - Canada - China - Czech Republic - Finland - France - Germany - Hong Kong - India - Israel - Italy - Japan - Malaysia - Malta - Morocco - Philippines - Singapore - Spain - Sweden - Switzerland - United Kingdom - United States of America

www.st.com