PSoC™ 6 MCU firmware design for BLE applications

About this document

Scope and purpose

AN215671 introduces the Bluetooth® low energy (BLE) stack used with PSoC 6 MCU with Bluetooth® low nergy (BLE) connectivity, the BLE component architecture, and the use of a dual-CPU processor for BLE applications. This application note shows how to design firmware for BLE applications. This application note uses the associated code examples to demonstrate the multi-master multi-slave feature of PSoC 6 BLE and validate the application using the CySmart BLE host emulation tool and Cypress’ iOS/Android CySmart application.

To access an ever-growing list of hundreds of PSoC code examples, please visit our code examples web page. You can also explore the Cypress video training library here.

Introduction

Bluetooth® low energy (BLE) is a low-power wireless standard introduced by the Bluetooth special interest group (SIG) for short-range communication. The BLE physical layer, protocol stack, and profile architecture are designed and optimized to minimize power consumption. Similar to classic Bluetooth, BLE operates in the 2.4 GHz ISM band with a maximum bandwidth of 2 Mbps.

PSoC 6 MCU with BLE connectivity (PSoC 6 BLE) is Infineon ultra-low-power PSoC device with dual CPUs specifically designed for wearables and internet of things (IoT) products. PSoC 6 BLE integrates a BLE 4.2 radio and a royalty-free protocol stack with enhanced security and privacy; it also has throughput compliant with the BLE 5.0 specification.

This application note introduces you to the BLE protocol stack in PSoC 6 BLE and discusses how to develop BLE applications using the PSoC creator BLE component. The BLE component has built-in support for the standard profiles defined by Bluetooth® SIG, which simplifies application development. In addition, this application note uses the code examples CE223508 and CE224714 to demonstrate the multi-master multi-slave feature of PSoC 6 BLE and validate the application using the CySmart BLE host emulation tool and Cypress’ iOS/Android CySmart application.

This application note assumes that you are familiar with the basics of BLE, CySmart 6 BLE, and the PSoC creator IDE. If you are new to PSoC 6 BLE, refer to AN210781 – getting started with PSoC 6 MCU with Bluetooth® low energy (BLE) connectivity. To get acquainted with PSoC creator IDE, see the PSoC Creator home page.

PSoC resources

Infineon provides a wealth of data at www.infienon.com to help you to select the right PSoC device and quickly and effectively integrate it into your design. The following is an abbreviated list of resources for PSoC 6 MCU:

See KBA223067 for a comprehensive list of PSoC 6 MCU resources.

BLE protocol implementation in PSoC 6 BLE

The BLE protocol stack used with PSoC 6 BLE integrates a low-energy controller and host, and provides a full and flexible API for developing BLE applications. The BLE stack consists of two major blocks: BLE host and BLE controller. Partitioning the stack into host and controller provides flexibility of implementing the protocol stack using the dual-CPU architecture of PSoC 6 BLE. Figure 1. BLE Architecture in PSoC 6 shows the dual-CPU and single-CPU BLE implementation in PSoC 6 BLE.

Figure 1. BLE Architecture in PSoC 6


The BLE stack is provided as a precompiled library along with the Cypress BLE middleware library, and packaged with Cypress peripheral driver library (PDL) 3.x. The BLE middleware library contains a comprehensive API that allows you to configure the BLE stack and the underlying hardware.

The BLE stack has the following features:

  • Operates in 2.4 GHz ISM band with a data rate of 2 Mbps, compliant with the BLE 5.0 specification
  • Multi-master multi-slave (MMMS) feature: supports up to four simultaneous connections in any combination of roles (central/peripheral)
  • Simultaneous support for all generic access profile roles – peripheral, central, broadcaster, and observer
  • Attribute protocol (ATT) that defines how the application data is organized and accessed
  • Generic attribute profile (GATT) that defines methods to access data defined by the ATT layer (GATT server and GATT client)
  • Support for BLE special interest group (SIG)-adopted GATT-based profiles and services
  • Security manager protocol (SMP) that provides a toolbox for secure data exchange over the BLE link. This toolbox includes:
    • Pairing methods: just works, passkey entry, out of band, numeric comparison
    • Authenticated man-in-the-middle (MITM) protection and data signing
  • Logical link control and adaptation protocol (L2CAP) connection-oriented channel
  • Link layer (LL) features which include:
    • Master and slave role
    • 128-bit AES encryption
    • Low duty cycle advertising
    • LE (low energy) ping

The BLE stack implements a layered architecture of the BLE protocol as shown in Figure 2. BLE protocol stack.

Figure 2. BLE protocol stack

../figures/image6.emf

BLE host

The BLE host implements the following protocol layers:

  • Generic access profile (GAP)
  • Generic attribute profile (GATT)
  • Attribute protocol
  • Security manager protocol (SMP)
  • Logical link control and adaptation protocol (L2CAP)
  • Host controller interface (HCI)

You do not need a full working knowledge of the complex BLE protocol to develop a BLE application. From an application point of view, it is sufficient to have a good understanding of the following:

  • GAP layer: This layer deals with how the BLE link is established between two devices
  • GATT layer: This layer deals with how the data is represented; GATT is the layer where the data values are transferred

In the remainder of the section, you will get an overview of GATT and GAP protocols and the related terms. You may refer to the Bluetooth® Core Specification for a detailed description of the protocol.

Generic access profile (GAP)

GAP is the lowest layer of the BLE stack that an application interface with. It includes parameters that govern advertising and connection, among other things. To establish a BLE link between two devices (Cypress BLE pioneer kit and a smartphone, for example), you need to understand the two GAP device roles:

  • GAP central: The GAP central is the device that initiates the connection with a peer device (GAP peripheral). A GAP central device scans for advertisements from GAP peripherals and establishes a connection with them. A smartphone that connects to a heart-rate measurement device is an example of a GAP central device
  • GAP peripheral: The GAP peripheral is the device that is connected to a GAP central device. A GAP peripheral advertises its presence and accepts the connection from a GAP central device

The Bluetooth® core specification defines observer and broadcaster roles in addition to the central and peripheral roles. Observers listen to what’s happening on the air; broadcasters send but do not receive information.

Note: Irrespective of the GAP role, the device at either end of a BLE link is referred to as a peer device.

Depending upon the GAP role of the device, the device can be in any of the following states:

  • Advertising: To establish a BLE link between two peer devices, the GAP peripheral must advertise to let central devices know of its presence. It sends out advertising packets at timed intervals, known as the advertising interval, that ranges from 20 ms to 10.24 s. The advertisement interval determines how fast a link is established.

    An advertisement packet can contain up to 31 bytes of data, which consist of the local device name, information pertaining to the services the device contains, etc. When a central device receives an advertisement packet, if the central device is configured as an active scanner, it may optionally send a request for more device-related data, called a scan request. The peripheral responds to the request by sending a scan response that can contain an additional 31 bytes

  • Scanning: Scanning is used by the GAP central to listen to advertisement packets from peer devices. In this context, you need to consider two parameters: Scan window and scan interval. The central device starts a scan once per scan interval. Within the interval, it will scan for the duration of the scan window. If the scan window is equal to the scan interval, the central device does a continuous scan
  • Initiating: When the central receives an advertisement packet, if it wants to establish a connection, it sends a connection request. This procedure is called “initiating”
  • Connected: The central and peripheral are in a connected state from the first data exchange. When connected, the central requests data from the peripheral at a specifically defined interval called the “connection interval”. The connection interval is dictated by the central when the link is established. A peripheral can send connection parameter update requests to the central. The connection interval must be between 7.5 ms and 4 ms per the Bluetooth® core specification.

    The link layer (LL) maintains the BLE link by sending at least one BLE packet in every connection interval. If the peripheral does not respond to packets from the central within the time frame, called “connection supervision timeout”, the link is considered lost. If the peripheral has no data to send and power consumption is of concern in your design, then it can choose to ignore a certain number of intervals. The number of ignored intervals is called the “slave latency”.

    For a proper operation, it is recommended to have connection supervision timeout as follows:

Generic attribute profile (GATT)

After the central device establishes a connection with the peripheral, both devices are said to be connected over a BLE link. On a connected BLE link, independent of the GAP role, the generic attribute profile (GATT) defines two profile roles based on the source and destination of the data:

  • GATT server: A GATT server is a device that contains the data or state. When configured by a GATT client, it sends data to the GATT client or modifies its local state. For example, a heart-rate measurement device is a GATT server that sends heart-rate data to a smartphone, which acts as the GATT client. Similarly, a smart bulb is a GATT server that contains the state of the bulb (ON/OFF) that can be configured by a smart switch, which acts as the GATT client
  • GATT client: A GATT client is a device that configures the state of a GATT server or receives data from a GATT Ssrver. For example, a smartphone that receives heart-rate information from the heart-rate measurement device is a GATT client

ATT protocol – organizing the data

The GATT server uses the ATT protocol, which organizes the data systematically in the form of an attribute table called GATT database. A GATT server uses attributes, characteristics, and services to represent and abstract data in a BLE device. A service contains one or more characteristics; each characteristic is composed of multiple attributes that contain the actual data. Figure 3. GATT database overview shows the GATT database hierarchy.

Figure 3. GATT database overview

../figures/image7.emf

Attribute: An attribute is the fundamental data container of the GATT layer that represents a discrete piece of information. The structure of an attribute consists of the following:

  • Attribute handle: Used to address the attribute. A handle is a unique index of the attribute in the GATT database
  • Attribute type: A 16-bit universally unique identifier (UUID) assigned by the Bluetooth® SIG that specifies the data contained in the attribute
  • Attribute value: Contains the actual data
  • Attribute permission: Specifies read/write permissions and security requirements for the attribute

Characteristic: A characteristic consists of at least two attributes: A characteristic declaration and an attribute that holds the value for the characteristic. All data that will be transferred through a GATT service must be mapped to a set of characteristics. It is a good that is to bundle the data so that each characteristic is a self-contained, single-instance data point. For example, if some pieces of data always change together, it will often make sense to collect them in one characteristic. The characteristic illustrated in Figure 3. GATT database overview has three attributes: Characteristic declaration, characteristic value, and the descriptor attribute.

Descriptors: Any attribute within a characteristic definition other than characteristic declaration attribute and characteristic value attribute is a descriptor. A descriptor is an additional attribute that provides more information about a characteristic, for instance, a human-readable description of the characteristic.

However, there is one special descriptor that is worth mentioning in particular: The client characteristic configuration descriptor (CCCD). This descriptor is added for any characteristic that supports the notify or indicate properties. Writing a ‘1’ to the CCCD enables notifications, while writing a ‘2’ enables indications. Writing a ‘0’ disables both notifications and indications. Notify and Indicate are the attribute properties that allow a GATT server to make the GATT client aware of the changes to a characteristic. The indicate property has application-level acknowledgment while notify does not have application-level acknowledgment.

Service: A service is composed of one or more related characteristics that define a function or feature of a device. GATT services typically include pieces of related functionality such as a sensor’s readings and settings, or the inputs and outputs of a human interface device.

Figure 4. GATT service example

../figures/image8.emf

Profile: A BLE profile is a specification that guarantees application-level interoperability between profile-compliant devices. It defines the role and configuration of different BLE layers and GATT service(s) to be supported to create a specific end application or use case. For example, in the case of a heart-rate monitoring device, the BLE heart rate profile defines the required GAP and GATT roles, and the GATT services to be supported by the heart-rate monitoring device to create an interoperable heart-rate monitoring device. The Bluetooth® SIG offers a set of predefined standard profiles for commonly used BLE end applications. In addition, you can create your own custom profiles that consist of standard or custom services.

The profile defines two application roles:

  • Sensor or server: The sensor profile role is supported by the application that has data. The sensor profile specification defines the required roles (for example, GATT/GAP roles) and behavior (for example, advertisement interval, GATT services to be supported) of the BLE device to support a sensor application use case. Following the sensor profile specification guarantees interoperability of the sensor application with any other device that implements the corresponding collector profile. For example, a heart-rate monitoring device that implements the heart rate sensor profile will be interoperable with all smartphones that implement the heart rate collector profile
  • Collector or client: The collector profile role is supported by the application that wants data. The collector profile specification defines the required BLE device roles and behavior to interoperate with and collect information from any device that implements the corresponding sensor profile specification

Figure 5. BLE data hierarchy1 illustrates the data abstraction and hierarchy in a BLE device.

Figure 5. BLE data hierarchy1

../figures/image9.png

Figure 6. BLE application level overview illustrates the application-level interaction of two connected BLE devices using the GAP and GATT protocol layers.

Figure 6. BLE application level overview

../figures/image10.emf
1 Image courtesy of Bluetooth® SIG
1 Image courtesy of Bluetooth® SIG

BLE controller

The BLE controller implements the link layer (LL) of the BLE protocol. In PSoC 6 BLE, LL is a hardware-firmware co-implementation. The LL firmware implements a state machine that manages and controls the physical BLE connections between devices. It supports all LL states such as advertising, scanning, initiating, and connecting. It implements all the key link control procedures such as LE encryption, LE connection update, LE channel update, and LE ping.

Managing multiple connections

The PSoC BLE stack may have up to four instances of the LL to support the multiple connection feature. Each LL instance caters to a particular BLE link and manages the LL functionality such as advertising, scanning, initiating, and connecting, independent of other BLE connection links.

During a connection event, the BLE stack assigns an identification number called “bdHandle” to the connecting peer device. A BLE event called CY_BLE_EVT_GAP_DEVICE_CONNECTED is triggered with an event parameter containing the bdHandle. During an active BLE connection, the application identifies the connected peer device using the bdHandle. Figure 7. Multiple BLE connections using PSoC 6 BLE illustrates a simplified block diagram on managing multiple BLE connections using PSoC 6 BLE.

Figure 7. Multiple BLE connections using PSoC 6 BLE

../figures/image11.emf

This section described how a BLE link is established using the GAP layer and how the data is represented using the GATT layer. With this background, let us examine the typical firmware flow for developing a BLE application.

1 Image courtesy of Bluetooth® SIG

Developing a BLE application: Firmware low

This section provides an overview of the minimal steps to be followed while developing BLE applications using PSoC 6 BLE. The BLE component in PSoC creator abstracts the BLE protocol into a simple and easy-to-use GUI. Figure 8. BLE component architecture shows a high-level architecture of the BLE component, which illustrates the relationship between the BLE stack layer and the route in which the application interacts with the component.

Figure 8. BLE component architecture

../figures/image12.emf

There are two major steps for developing a BLE application with PSoC 6 BLE:

  • Configure the BLE component
  • Write the firmware

The following sections provide the details on how to accomplish each task.

  • Configure the BLE component
    • Select the GAP role and number of simultaneous connections

      PSoC 6 BLE supports up to four simultaneous connections in any combinations of GAP roles (central, peripheral, observer, broadcaster). In this step, you configure the desired GAP roles and the number of simultaneous BLE connections

    • Select the BLE architecture

      PSoC 6 BLE offers dual CPU architecture, where the controller runs on the CM0+ CPU and host runs on CM4 CPU, and single CPU architecture, where both controller and host are run only on one CPU (either CM0+ or CM4). Figure 9. General BLE settings illustrates this sub steps A and B

      Figure 9. General BLE settings

      ../figures/image13.emf

      Assign the BLE subsystem (BLESS) interrupt to the CPU on which the BLE controller runs. In PSoC creator, assign the BLESS interrupt to the controller CPU in the Interrupts tab of the design wide resources window as shown in Figure 10. Assigning the BLESS interrupt to the BLE controller CPU. By default, the BLESS interrupt is assigned to the CM0+ CPU.

      Figure 10. Assigning the BLESS interrupt to the BLE controller CPU

      ../figures/image14.emf
      Note: The rest of the document assumes dual-CPU architecture for the BLE application.
    • Configure GAP settings

      Depending upon the GAP role of the device, you must configure a few settings specific to the role. For example, if the device is a GAP peripheral, then you must provide the advertisement settings, advertisement packet structure, etc. Similarly, if it is GAP central, you need to provide the scan setting and connection parameters. If the device has multiple roles, you need to provide the configuration settings for each GAP role. Figure 11. GAP general settings to Figure 15. GAP central configuration: Connection parameters show GAP configuration.

      Figure 11. GAP general settings

      ../figures/image15.emf
      Figure 12. GAP peripheral configuration: Advertisement settings

      ../figures/image16.emf
      Figure 13. GAP peripheral configuration: Advertisement packet

      ../figures/image17.emf
      Figure 14. GAP central configuration: Scan settings

      ../figures/image18.emf
      Figure 15. GAP central configuration: Connection parameters

      ../figures/image19.emf

      The parameters in GAP configuration settings are explained in chapter Generic access profile (GAP). For a detailed description of each parameter, see the BLE Component datasheet. Further, examples provided in chapter Section 5: BLE Design Examples illustrate how these parameters are set.

    • Configure GATT settings

      In this step, you include the services that you need in your application. The BLE component supports numerous Bluetooth® SIG-adopted GATT-based profiles and services. The component generates all the necessary code for a profile/service operation as configured in the component customizer. Figure 16. BLE component GATT configuration shows an example for configuring a standard heart rate service (HRS).

      Figure 16. BLE component GATT configuration

      ../figures/image20.emf

      This completes all the necessary steps for GAP and GATT profile-based settings. After you configure the BLE component, the next step is to write the firmware to initialize the design and register event handler functions to process the BLE events and data as required by your application

  • Write the firmware

    This section discusses the typical steps required by a BLE application firmware. For each major task, specific steps are explained along with sample firmware code. For detailed firmware steps, refer to the code examples referenced in Section 5: BLE Design Examples.

    • Firmware flow for the controller (CM0+ CPU for dual-CPU architecture)
      1. Start the BLE controller
      2. Process BLE events using the Cy_BLE_ProcessEvents()function

    The Cy_BLE_ProcessEvents()function checks the internal task queue in the BLE stack and processes any pending BLE operations. As shown in Figure 17. BLE connection interval, this function must be called at least once every ‘T’ intervals, where ‘T’ is equal to the connection interval or scan interval (if the device is a GAP central), or the connection interval or advertisement interval (if the device is a GAP peripheral) whichever is smaller.

    Figure 17. BLE connection interval

    ../figures/image21.emf

    The following code snippet shows the basic controller firmware flow:

    #include "project.h"
                   
    int main(void)
    {
      /* Enable global interrupts */
      __enable_irq();    
                   
      /* Start the controller portion of BLE. Host runs on the CM4 */
      if(Cy_BLE_Start(NULL) == CY_BLE_SUCCESS)
      {
        /* Enable CM4 only if BLE Controller started successfully. 
           CY_CORTEX_M4_APPL_ADDR must be updated if CM4 memory layout 
           is changed. */
      
      Cy_SysEnableCM4(CY_CORTEX_M4_APPL_ADDR);
      
      }
      else
      {
        /* Halt the CPU */
        CY_ASSERT(0u);
        
      }
                   
      for(;;)
      {
        /* Process the controller portion of the BLE events and wake up the host (CM4) and send data to the host via IPC if necessary */
        
        Cy_BLE_ProcessEvents();
                   
        /* Put CM0+ to Deep Sleep mode. The BLE hardware automatically wakes
                   up the CPU if processing is required */
        
        Cy_SysPm_DeepSleep(CY_SYSPM_WAIT_FOR_INTERRUPT);
      }
    }/*End of main function */
    • Firmware flow for the host (CM4 CPU for dual-CPU architecture)

      The interaction between BLE controller and the BLE host are event-driven. The BLE stack generates events that provide status and data to the application firmware running on the BLE Host



The typical firmware flow for the host is as follows:

  • Register the application host callback function
  • The application host callback function is called when the BLE host needs to process pending stack events. The application host callback function processes the pending events by calling Cy_BLE_ProcessEvents(). Note that the application host callback function executes from within an ISR and must be very short.
  • Start the BLE host by providing the generic BLE generic event handler function
  • Register BLE service-specific event handlers
void BleAppHost_Callback(void)
{
  /* On every interrupt from the BLE Controller, process the pending
         Host events propagated from the BLE Controller */
  Cy_BLE_ProcessEvents();
}
         
int main(void)
{
  __enable_irq(); /* Enable global interrupts. */
         
  /* Start BLE component and register generic event handler */
  if(Cy_BLE_Start(GenericStackEventHandler) == CY_BLE_SUCCESS)
  {
         
    /* Register the Host application callback function */
    Cy_BLE_RegisterAppHostCallback(BleAppHost_Callback);
         
    /* Register Service Specific event handler*/
    Cy_BLE_HRS_RegisterAttrCallback(HRSEventHandler);
  }
  else
  {
    /* Halt the CPU */
    CY_ASSERT(0u);
  }
         
  for(;;)
  {
    /* Code specific to your application */
  }
}

BLE events are handled with the user-defined generic BLE stack event handler. In the above code snippet, GenericStackEventHandler() is a user-defined function to handle BLE events. The generic stack event handler must handle a few basic events from the stack. lists these events.

Table 1. Basic BLE stack events
BLE stack event name Event description Event handler action

CY_BLE_EVT_STACK_ON

BLE stack initialization is completed successfully

GAP central: Discover GAP peripherals using Cy_BLE_GAPC_StartScan().

GAP peripheral: Start the advertisement using Cy_BLE_GAPP_StartAdvertisement().

CY_BLE_EVT_GAP_DEVICE_CONNECTED

BLE link with the peer device is established

Application-specific action

CY_BLE_EVT_GAPP_ADVERTISEMENT_START_STOP

BLE stack advertisement start/stop event

Application-specific action

CY_BLE_EVT_GAP_DEVICE_DISCONNECTED

BLE link with the peer device is disconnected

GAP central: Discover GAP Peripherals using Cy_BLE_GAPC_StartScan().

GAP peripheral: Start the advertisement using Cy_BLE_GAPP_StartAdvertisement().

CY_BLE_EVT_HARDWARE_ERROR

BLE hardware error

Application-specific action

CY_BLE_EVT_STACK_SHUTDOWN_COMPLETE

BLE stack has been shut down

Application-specific action

The BLE Middleware Library provides functions for registering event handlers specific to standard BLE services. For example, Cy_BLE_HRS_RegisterAttrCallback(HRSEventHandler) registers the HRSEventHandler function to handle events specific to the heart rate service.

Code examples described in the Section 5: BLE Design Examples explain how to define and implement the generic event handler function and BLE service-specific event handlers. lists commonly used functions in a typical BLE design.

For a comprehensive list of BLE stack events and functions, see the Cypress BLE middleware library. To open the documentation, from PSoC creator, navigate to Help > Documentation > Peripheral Driver Library. Locate the Cypress BLE middleware library under the Middleware menu option.

Table 2. Basic BLE API functions
BLE API Function Description

Cy_BLE_Start()

Initializes the BLE stack and initializes the profile layer, schedulers, timers, and other platform-related resources required by the BLE component

Cy_BLE_GAPP_StartAdvertisement()

GAP peripherals use this function to start the advertisement using the advertisement data set in the BLE component

Cy_BLE_GAPP_StopAdvertisement()

GAP peripherals use this function to stop advertisement

Cy_BLE_GAPC_StartScan()

GAP central uses this function to discover GAP peripherals that are available for connection

Cy_BLE_GAPC_StopScan()

GAP central uses this function to stop the discovery of GAP peripherals

Cy_BLE_GAPC_ConnectDevice()

GAP central uses this function to send connection requests to the GAP peripheral with the connection parameters set in the BLE component

Cy_BLE_ProcessEvents()

Checks the internal task queue in the BLE stack and processes pending BLE events

Implementing low-power BLE design

Low-power operation is one of the major considerations when it comes to connected devices. PSoC 6 BLE provides low-power modes without sacrificing the performance. PSoC 6 BLE has several power modes that can affect either the whole system or just a single CPU. CPU power modes are active, sleep, and deep sleep as defined by Arm®. Device system power modes are low power (LP), ultra low power (ULP), deep sleep, and hibernate.

AN219528 – PSoC 6 MCU Low-Power/modes and Power Reduction Techniques describes the low-power design considerations and the low-power modes in PSoC 6 MCU. In this section, we shall see how to implement a low-power design involving BLE connectivity. For low-power support, configure the BLE Component as shown in Figure 18. Configuring BLE low-power support.

Figure 18. Configuring BLE low-power support

../figures/image23.emf

To operate the BLE component in low-power mode, it is mandatory to use an external watch crystal oscillator (WCO) as the source to the low-frequency clock (LFCLK) of PSoC 6 BLE. Figure 19. Enabling WCO for low-power operation shows configuring the WCO as the LFCLK source in the design wide resources.

Figure 19. Enabling WCO for low-power operation

../figures/image24.emf

In PSoC 6 BLE, wakeup from the low-power mode operation is possible with a set of interrupts handled by the wakeup interrupt controller (WIC) block of PSoC 6 BLE. The WIC block supports up to 41 interrupts that can wake up a CPU from the CPU deep sleep power mode. Refer to AN217666 – PSoC 6 MCU Interrupts for more details on PSoC 6 MCU interrupts.

The BLESS interrupt is a CPU deep sleep-capable interrupt source. As described previously, BLE is implemented based on a host-controller architecture. The discussion that follows is split into two parts based on the BLE architecture: The dual-CPU architecture and the single-CPU architecture.

Dual-CPU architecture

The BLESS interrupt is mapped to the BLE controller CPU. The host CPU and the controller CPU can independently go into low-power mode if there are no BLE events to be processed by them. The following sequence of events is involved in a typical low-power BLE design for dual-CPU architecture:

  • The BLESS interrupt wakes up the controller during every connection interval
  • The controller CPU then services the BLE event with Cy_BLE_ProcessEvents() in firmware
  • If the host must process a BLE event or data, the controller wakes up the host CPU using the inter-processor communication (IPC) interrupt
  • Upon receiving the BLE event or data through the IPC interrupt, the host CPU processes it using Cy_BLE_ProcessEvents() and registered event handler functions. If the host CPU requires the service of the controller CPU, the host sends the BLE data/event using IPC
Note: The BLE Component uses system IPC pipes for communication between the Host and the Controller. System IPC pipes and associated interrupts are automatically configured by PSoC Creator.
  1. The host CPU goes back to the low-power mode and waits for the IPC interrupt from the controller with the Cy_SysPm_DeepSleep(CY_SYSPM_WAIT_FOR_INTERRUPT) function
  2. The controller processes the BLE events/data from the Host (if any). The controller CPU goes back to the low power mode and waits for the BLESS interrupt using the Cy_SysPm_DeepSleep(CY_SYSPM_WAIT_FOR_INTERRUPT) function

Single-CPU Architecture

In single-CPU architecture, both the Controller and the Host runs on the same CPU (CM0+ or CM4). The CPU used by the BLE Component is hereafter referred to as the BLE CPU for the sake of explanation. The following sequence of events is involved in a typical low-power BLE design for single-CPU architecture:

  • The BLESS interrupt wakes up the BLE CPU
  • The Cy_BLE_ProcessEvents() function processes both the controller and the Host BLE events/data
  • The BLE CPU goes back to the low power mode and wait for the BLESS interrupt using the Cy_SysPm_DeepSleep(CY_SYSPM_WAIT_FOR_INTERRUPT) function
Note: When the design enables BLE low-power mode as shown in Figure 18. Configuring BLE low-power support, the BLE component registers the low-power callback function. When the low-power mode transition is about to occur using the Cy_SysPm_DeepSleep() function, the registered callback function is executed. The CPU enters low-power mode only if the BLE stack is ready for low-power operation. If the design involves other blocks capable of low-power operation, your application must define how power mode transitions occur. See ‘System Power Management’ in the PDL API Reference Manual.
Figure 20. Typical firmware flow for low-power BLE design

../figures/image25.emf

Implementing a secure BLE design

For every wireless device, protecting a user’s private data is of paramount significance. PSoC 6 BLE is compliant with the Bluetooth® low energy (BLE) 4.2 security features. The BLE stack in PSoC 6 BLE supports the security manager protocol (SMP) with the following features:

  • Encryption and authentication of user data
  • Authenticated man-in-the-middle (MITM) protection and data signing
  • Support for device bonding and different pairing methods such as just works, passkey entry, out of band, and numeric comparison
  • Pairing method selection based on the I/O capability of the GAP central and the GAP peripheral devices

This section discusses how to configure the BLE component to incorporate the security features into your design and handle them in firmware. For technical details on the BLE 4.2 security features, see the Bluetooth® Core Specification version 4.2 Volume 3 Part H. For details on developing secure embedded system with PSoC 6 MCU, see AN221111 – PSoC 6 MCU: Creating a Secure System.

Before proceeding further on the BLE security features, two new terms need to be introduced. The security manager protocol (SMP) layer of the BLE stack defines two roles for a BLE device in establishing a secure connection. They are:

Initiator: The link layer master always initiates a secure connection. Therefore, a GAP central device is the initiator.

Responder: The link layer slave responds to the secure connection request from the link layer master; therefore, a GAP peripheral device is the responder.

Configuring security features using the BLE component security mode and security level

PSoC 6 BLE supports two modes of security with multiple security levels within each mode as shows.

Table 3. BLE security modes and levels
Security mode Security level Remark

Mode 1

No security (no authentication, no encryption)

This mode is used in designs where data encryption is required

Unauthenticated pairing with encryption

Authenticated pairing with encryption

Authenticated LE secure connections pairing with encryption

Mode 2

Unauthenticated pairing with data signing

This mode is used in designs where data signing is required

Authenticated pairing with data signing

I/O Capabilities

Security levels described in take effect based on the device’s input and output capability. Every BLE device determines its peer device input and output capabilities during the pairing request phase explained in chapter Establishing secure BLE link: Firmware flow. summarizes the device capabilities configurable from the BLE component:

Table 4. Device I/O Capability
I/O capabilities Description GAP authentication required (Yes/No)

Display

Used in devices with display capability and may display authentication data

Yes

Display Yes/No

Used in devices with display and at least two input keys for the Yes/No action

Yes

Keyboard

Used in devices with numeric keypad

Yes

No Input No Output

Used in devices that do not have any capability to enter or display the authentication key data to the user

No

Keyboard and Display

Used in devices like PCs and tablets

Yes

Figure 21. Configuring BLE security settings

../figures/image26.emf

When two devices want to communicate securely with BLE, they need to follow authentication procedure called “pairing”. PSoC 6 BLE supports four pairing methods compliant with BLE 4.2 feature as follows:

  • Just works: When the I/O capability of the device is set to No Input No Output and no MITM protection is required, the BLE device uses this pairing method
  • Passkey entry: The user either inputs an identical passkey into both devices, or one device displays the passkey and the user enters that passkey into the other device
  • Numeric comparison: Both devices display a six-digit number and the user authenticates by selecting ‘Yes’ if both devices display the same number
  • Out of band (OOB): This pairing method is used when both devices have access to an out-of-band mechanism to discover the devices as well as exchange the information used in the pairing procedure

See AN99209 – PSoC 4 BLE and PRoC BLE: Bluetooth® LE 4.2 Features for an elaborate description on BLE pairing process and establishing a secure connection.

The pairing method is determined based on the device security mode and the I/O capability of the interacting BLE devices as summarized in .

Table 5. Pairing method based on the I/O capabilities of interacting BLE devices
GAP role Initiator

Responder

I/O capabilities

Display only

Display (Yes/No)

Keyboard only

No Input No Output

Keyboard and display

Display only

Just works

Just works

Passkey entry

Just works

Passkey entry

Display (Yes/No)

Just works

Numeric comparison

Passkey entry

Just works

Numeric comparison

Keyboard only

Passkey entry

Passkey entry

Passkey entry

Just works

Passkey entry

No Input No Output

Just works

Just works

Just works

Just works

Just works

Keyboard and display

Passkey entry

Numeric comparison

Passkey entry

Just works

Numeric comparison

Establishing secure BLE link: Firmware flow

The following steps illustrate the firmware flow for establishing a secure BLE link:

  • The pairing procedure requires generating a set of security keys. These keys need to be generated irrespective of the GAP role. The BLE device exchanges the generated key with the peer device during the key exchange stage of the authentication procedure. On the CY_BLE_EVT_STACK_ON BLE event, generate the keys using the Cy_BLE_GAP_GenerateKeys() function
  • Upon successful generation of security keys, the CY_BLE_EVT_GAP_KEYS_GEN_COMPLETE event is triggered. Set the device identity address using the Cy_BLE_GAP_SetIdAddress() function
  • On CY_BLE_EVT_GAP_DEVICE_CONNECTED or CY_BLE_EVT_GAP_ENHANCE_CONN_COMPLETE event, the BLE device sets the security keys using the Cy_BLE_GAP_SetSecurityKeys() function. The Link Layer of the BLE stack uses these keys for encrypting the data
  • The initiator sends a pairing request using Cy_BLE_GAP_AuthReq(). The parameter passed through this function contains the security mode/level, I/O capability, encryption key size, etc. This triggers the CY_BLE_EVT_GAP_AUTH_REQ BLE event at the GAP peripheral
  • The GAP peripheral (responder) sends a request to the GAP central device (Initiator) to initiate the pairing procedure using the Cy_BLE_GAP_AuthReq() function. This triggers the CY_BLE_EVT_GAP_AUTH_REQ BLE event at the GAP central device
  • On receiving the CY_BLE_EVT_GAP_AUTH_REQ event, the GAP peripheral responds with Cy_BLE_GAPP_AuthReqReply(). The pairing response contains much of the same information as the Initiator pairing request parameter
  • On successful pairing information exchange, the BLE stack generates the CY_BLE_EVT_GAP_SMP_NEGOTIATED_AUTH_INFO event at both the GAP central and GAP peripheral devices
  • During the authentication procedure, the BLE stack generates one of the following events based on the BLE device’s I/O capabilities and security modes:
    • CY_BLE_EVT_GAP_PASSKEY_DISPLAY_REQUEST
    • CY_BLE_EVT_GAP_KEYPRESS_NOTIFICATION
    • CY_BLE_EVT_GAP_NUMERIC_COMPARISON_REQUEST
  • On successful completion of the pairing procedure, the BLE stack generates the CY_BLE_EVT_GAP_AUTH_COMPLETE event

    If authentication fails, CY_BLE_EVT_GAP_AUTH_FAILED is generated. Typically, this event is handled by disconnecting the BLE link using the CY_BLE_GAP_Disconnect() function.

lists the sequence of BLE stack events and the action to be taken when using the LE secure connection feature.

Table 6. BLE events and corresponding actions for LE secure connections
BLE stack event(s) Event handler action

CY_BLE_EVT_STACK_ON

Generate the security keys using Cy_BLE_GAP_GenerateKeys()

CY_BLE_EVT_GAP_KEYS_GEN_COMPLETE

Set the device identity address using Cy_BLE_GAP_SetIdAddress()

CY_BLE_EVT_GAP_DEVICE_CONNECTED or

CY_BLE_EVT_GAP_ENHANCE_CONN_COMPLETE

Set the security keys using Cy_BLE_GAP_SetSecurityKeys()

Additionally, if it is a GAP peripheral, send a request to the GAP central to initiate pairing using Cy_BLE_GAP_AuthReq()

CY_BLE_EVT_GAP_AUTH_REQ

GAP central: Initiate pairing using Cy_BLE_GAP_AuthReq()

GAP peripheral: Respond to the pairing request using Cy_BLE_GAPP_AuthReqReply()

CY_BLE_EVT_GAP_SMP_NEGOTIATED_AUTH_INFO

Initiate application-specific action

CY_BLE_EVT_GAP_PASSKEY_DISPLAY_REQUEST

Display the 6-decimal-digit value extracted from the event parameter

CY_BLE_EVT_GAP_KEYPRESS_NOTIFICATION

The BLE stack generates this event when a keypress (secure connections) is received from the peer device

CY_BLE_EVT_GAP_NUMERIC_COMPARISON_REQUEST

This event indicates that the device must display a passkey during the secure connection pairing procedure

Call Cy_BLE_GAP_AuthPassKeyReply() with valid parameters on receiving this event

CY_BLE_EVT_GAP_AUTH_COMPLETE

This event indicates that the authentication procedure is completed

Initiate application-specific action

CY_BLE_EVT_GAP_AUTH_FAILED

This event indicates that the authentication process between two devices has failed

Typically, upon receiving this event, the BLE device disconnects the BLE link using CY_BLE_GAP_Disconnect()

list the API functions commonly used for establishing a secure BLE connection. For a comprehensive list of BLE events and API functions specific to LE secure connection, see Cypress BLE Middleware Library.

Table 7. API functions for LE secure connection
API Description

Cy_BLE_GAP_SetSecurityKeys()

This function sets the security keys that are to be exchanged with a peer device during the key exchange stage of the authentication procedure and sets it in the BLE stack

Cy_BLE_GAP_GenerateKeys()

This function generates the security keys as per application requirement

Cy_BLE_GAP_AuthReq()

This function starts the authentication/pairing procedure with the peer device

Cy_BLE_GAPP_AuthReqReply()

The GAP peripheral device uses this function to send the pairing response in the authentication/pairing procedure

Cy_BLE_GAP_FixAuthPassKey()

This function sets or clears a fixed passkey to be used during the authenticated pairing procedure

Device bonding

The pairing procedure explained above is required to authenticate a peer device. If bonding is enabled, the device has the provision to store the link key of a previously authenticated link. If the bonding data is stored, and then if a connection is lost and re-established, bonded devices can resume the communication without the need of authentication again.

lists the API functions to handle device bonding in the firmware. Figure 22. Firmware flow for secure BLE design with bonding shows the flowchart for handling the pairing and bonding procedure in a secure BLE design.

Figure 22. Firmware flow for secure BLE design with bonding

../figures/image27.emf
Table 8. API functions for bonding
API function Description

Cy_BLE_StoreBondingData()

This function writes the new bonding data from the RAM to the dedicated flash location as defined by the BLE middleware

Cy_BLE_GAP_GetBondList()

This function returns the count and list of bonded devices

Cy_BLE_GAP_RemoveDeviceFromBondList()

This function removes the specified device from the bond list

Additional BLE design considerations

Design considerations discussed in this section are optional steps that you can incorporate in your design based on your application requirements.

Link layer settings

The link layer (LL) is the part of the BLE protocol stack that handles advertising, scanning, creating, and maintaining connections. The LL of the BLE protocol stack supports BLE 4.2 features such as LE data packet length extension and link layer privacy.

LE data packet length extension

The LE data packet length extension feature enables applications to get higher throughput, lower power consumption, etc. These benefits are available under the following conditions:

  • Both BLE devices support LE data packet length extension
  • Higher-layer protocols use greater than the default (23 bytes) maximum transmission unit (MTU) size
Figure 23. Configuring BLE link layer settings

../figures/image28.emf

When a BLE connection is established, the BLE stack automatically negotiates TX and the RX payload sizes with the peer device. Negotiated maximum TX and RX payload sizes are reported to the application through the CY_BLE_EVT_DATA_LENGTH_CHANGE BLE stack event.

BLE stack event Event handler action

CY_BLE_EVT_DATA_LENGTH_CHANGE

Informative event.

This event reports the negotiated TX and RX payload sizes

LE 2-Mbps data rate

The BLE protocol stack in PSoC 6 BLE supports the BLE 5.0-compliant data rate of 2 Mbps. To use the 2-Mbps data rate, you need to enable this feature under the link layer settings tab of the BLE component as shown in Figure 23. Configuring BLE link layer settings. Note that the usage of the term PHY settings corresponds to the BLE data rate settings.

lists the BLE stack events and the action to be taken while configuring PHY settings.

Table 9. BLE events associated with PHY configuration
BLE stack event Event handler action

CY_BLE_EVT_SET_PHY_COMPLETE

Indicates the completion of Cy_BLE_SetPhy()

CY_BLE_EVT_PHY_UPDATE_COMPLETE

Indicates that the controller has changed the transmitter PHY or receiver PHY in use

CY_BLE_EVT_GET_PHY_COMPLETE

Indicates the completion of Cy_BLE_GetPhy().

lists the functions used for configuring the BLE data rate.

Table 10. API functions for handling PHY settings
API Description

Cy_BLE_SetPhy

Allows the application to set the PHY for the current connection

Cy_BLE_GetPhy

Allows the application to read the current PHY setting for the specified connection

See the BLE Component datasheet for more details on LL configuration parameters. For a comprehensive list of BLE events and API functions, refer to Infineon BLE middleware library.

See AN99209 – PSoC 4 BLE and PRoC BLE: Bluetooth® LE 4.2 Features for an elaborate description on BLE 4.2 features. See CE212742 – BLE 4.2 Data Length Security Privacy with PSoC 6 MCU with BLE Connectivity for details on implementing LE secure connection and the data length extension (DLE) features of BLE.

BLE design examples

Now that you are familiar with basic firmware flow for BLE design using PSoC 6 BLE, it is time to get hands-on for designing BLE applications. This section discusses two BLE design examples illustrating the multi-master multi-slave (MMMS) capability of PSoC 6 BLE. Note that both the code examples discussed in this section are based on dual-CPU BLE architecture and the firmware is developed in an RTOS environment.

Multi-master multi-slave: Implementing four BLE slaves

This design illustrates the connectivity between PSoC 6 BLE, acting as a GAP peripheral and GATT server, and four BLE-enabled devices (a personal computer running the CySmart BLE host emulation tool, or a mobile device running the CySmart mobile app) acting as a GAP central and GATT client. This design is available as a code example: CE223508PSoC 6 MCU implementing BLE multi-connection (4 slaves).

About the design

In this design example, PSoC 6 MCU is configured as a GAP peripheral and a GATT server and can connect to as many as four GAP central devices.

PSoC 6 BLE implements the BLE multi-slave functionality that consists of the following services as shown in Figure 24. BLE services implemented by PSoC 6 BLE:

  • Device information service
  • Health thermometer service
  • Custom service for RGB LED with color and intensity control
  • 128-bit long characteristic read/write custom service
  • A custom notification service

Connected GAP central devices can access the GATT database.

Figure 24. BLE services implemented by PSoC 6 BLE

../figures/image29.emf

The code example, CE223508, features the following:

  • BLE connectivity
    • Advertisement and connection with four GAP central devices
    • Five services (RGB LED, health thermometer service, device information, read/write 128-bit long custom service and custom notification service)
    • Data transfer over BLE using notifications, read, and write
  • RGB LED color and intensity control using configurable digital blocks of PSoC 6 MCU
  • The ADC in PSoC 6 MCU scans two differential channels and averages multiple samples without the need for CPU intervention for accurate temperature measurement from a thermistor circuit
  • Device information service gives manufacturer and/or vendor information about the device
  • 128-bit read/write custom service
  • The custom notification sends notifications to connected devices about any changes to the GATT database. It sends a two-byte data: the first byte identifies the device that modified the data; the second byte identifies the characteristic that has been modified
  • Low-power operation using the deep sleep mode with multi-counter watchdog timer (MCWDT) and GPIO interrupts
  • The orange (LED8) and red (LED9) LEDs on the kit are used to show the status:
    • If the device is in hibernate mode, red LED will be ON
    • The orange LED will blink if the device is advertising

Figure 25. Firmware flow diagram for PSoC 6 MCU implementing BLE multi-connection (4 slaves) shows the firmware flow of CE223508.

Figure 25. Firmware flow diagram for PSoC 6 MCU implementing BLE multi-connection (4 slaves)

../figures/image30.emf

Multi-master multi-slave: Implementing three BLE masters and one BLE slave

This design demonstrates how to configure PSoC 6 BLE in simultaneous multiple master and single slave mode of operation. This design configures PSoC 6 BLE as three BLE central roles and one BLE peripheral role (MMMS). The BLE multi-master single slave project is used in conjunction with the CE215119 BLE battery level code example for PSoC 6 MCU or PSoC 4 devices to demonstrate the operation in simultaneous multiple master and single slave modes. For a detailed explanation on the design and implementation of the BLE design, see CE224714 – PSoC 6 MCU Implementing BLE Multi-connection (3 Masters 1 Slave) .

About the design

Figure 26. Multi-master single slave

../figures/image31.emf

The multi-master single slave project uses three BLE central connections and one peripheral connection:

  • The central is configured as a generic attribute profile (GATT) client with a battery service that can communicate with a peer device in the generic access profile (GAP) peripheral and GATT server roles. Use the existing CE215119 – BLE battery level code examples for PSoC 6 BLE/PSoC 4 devices or an application that can simulate a GATT server with a battery service as a peer device.
  • The peripheral is configured as a GATT server with three battery services. This configuration represents the battery level of the three peripherals that the device is connected to. Figure 26. Multi-master single slave shows a block diagram of the multi-master single slave example

Figure 27. Firmware flow diagram for multi-master single slave shows the firmware flow of CE224714.

Figure 27. Firmware flow diagram for multi-master single slave

../figures/image32.emf

Summary

This application note introduced the BLE stack architecture and its implementation in PSoC 6 BLE. The application note further discussed the typical firmware flow and design considerations, such as low-power design and establishing BLE secure connection, for developing BLE applications. The code examples CE223508 and CE224714 discuss multi-master multi-slave (MMMS) feature of the BLE stack used with PSoC 6 BLE and illustrate the firmware flow for developing MMMS BLE applications.

References

Application Notes

AN210781 – Getting Started with PSoC 6 MCU with Bluetooth® Low Energy (BLE) Connectivity

Describes PSoC 6 MCU with BLE connectivity devices and how to build your first PSoC creator project

AN218241PSoC 6 MCU Hardware Design Considerations

Describes how to design a hardware system around a PSoC 6 MCU device

AN215656PSoC 6 MCU: Dual-CPU System Design

Describes the dual-CPU architecture in PSoC 6 MCU, and shows how to build a simple dual-CPU design

AN221111PSoC 6 MCU: Creating a Secure System

Describes how to create a secure embedded system with PSoC 6 MCU

AN213924PSoC 6 MCU Bootloader Software Development Kit (SDK) Guide

Provides comprehensive information on how to use the bootloader software development kit (SDK) to develop bootloadable systems for PSoC 6 MCU products

AN219434 – Importing PSoC Creator Code into an IDE for a PSoC 6 MCU Project

Describes how to import the code generated by PSoC creator into your preferred IDE

AN99209 – PSoC 4 BLE and PRoC BLE: Bluetooth® LE 4.2 Features

Provides an overview of the Bluetooth® low energy (BLE) 4.2 features and explains their usage at the application level

PSoC™ creator code examples

CE223508PSoC 6 MCU Implementing BLE Multi-connection (4 Slaves)

Demonstrates the implementation of multi-slave functionality of the PSoC 6 MCU with BLE connectivity (PSoC 6 BLE) device

CE224714PSoC 6 MCU Implementing BLE Multi-connection (3 Masters 1 Slave)

Demonstrates how to configure the PSoC 6 MCU with Bluetooth® low energy (BLE) connectivity device in simultaneous multiple master and single slave modes of operation

CE212742 – BLE 4.2 Data Length Security Privacy with PSoC 6 MCU with BLE Connectivity

Demonstrates the new BLE 4.2 and 5.0 features of the PSoC creator BLE component

CE215119 – BLE Battery Level with PSoC 6 BLE

Demonstrates the operation of Bluetooth® low energy (BLE) battery service (BAS) using the PSoC creator BLE component

CE216767PSoC 6 MCU with Bluetooth® Low energy (BLE) Connectivity Bootloader

Demonstrates simple over the air (OTA) bootloading with PSoC 6 MCU with BLE connectivity

Device documentation

PSoC 6 MCU: PSoC 63 with BLE Datasheet

PSoC 6 MCU: PSoC 63 with BLE architecture technical reference manual

Development kit documentation

CY8CKIT-062-BLE PSoC 6 BLE Pioneer Kit

For more BLE code examples with PSoC 6 BLE, visit our GitHub repository: PSoC 6 MCU BLE Connectivity Design s

Revision history

Document version Date of release Description of changes

**

2018-09-21

New Application Note.

*A

2021-03-27

Migrated to Infineon template.

1 Image courtesy of Bluetooth® SIG