Defining Application Behavior

The Sample Applications will often contain simple TI-RTOS tasks with a barebones messaging system between tasks. For more information on how the application tasks works in general, review Introduction.

Directed Advertisements as GATT Server

In BLE5-Stack 1.01.05.00, Privacy is always enabled. Most of the privacy features are handled by the GAP bond manager in the stack. To conserve flash memory, by default, the GAP bond manager does not enable GATT client features. The implication of these disabled GATT client features is that the GAP bond manager will not query the Central Address Resolution characteristic of the remote device.

In order to perform a directed advertisement when the initiator’s address is set to Private Resolvable Address, the peripheral device must read the Central Address Resolution characteristic of its remote device to make sure address resolution is supported. Failure to do so before sending directed advertisements violates the Bluetooth Core Specification Version 5.0.

By default, sample applications such as simple_peripheral does not define GATT_NO_CLIENT but initializes the GATT Client as shown below:

/*
 * Initialize GATT Client, used by GAPBondMgr to look for RPAO
 * characteristic for network privacy
 */
GATT_InitClient();

Compiler Options

For BLE5-Stack projects, compiler options are defined via .opt files that are included in the IDE’s TOOLS\defines folder. Each project’s build configuration will include its very own .opt file.

The predefined symbols in the .opt files are prefixed with a -D, which is standard commandline prefix notation across all the supported toolchains. Of the predefined symbols in the .opt files, some of them are configurable and some are not. See Bluetooth Low Energy Application Configuration Parameters and Bluetooth Low Energy Stack Configuration Parameters for reference as to which options are configurable.

The convention to disable a symbol in the .opt files is to put an ‘x’ in front of the name. For example, to disable power management, change -DPOWER_SAVING to -DxPOWER_SAVING. It is also possible to disable a symbol by commenting it out via ‘C - style’ syntax (e.g. /* -DPOWER_SAVING */)

Warning

Changes in an .opt file may not be detected by the compiler/toolchain. It is best to rebuild the entire project when a define is changed.

Linker Options

Linker symbols may need to be set or adjusted at the project level in order to control the memory layout of the generated image. The following procedure describes how to access and modify linker symbols.

CCS

  1. Open Project Properties
  2. Navigate to Build -> ARM Linker -> Command File Preprocessing
  3. Use the buttons highlighted in Figure 85. to add, delete, or edit a linker symbol.
../_images/ccs_linker_opts.png

Figure 85. CCS Linker Symbols

IAR

  1. Open the Project’s Options and select the Linker Category.
  2. Open the Config tab.
  3. View the Configuration File symbol definitions box (see Figure 86.).
  4. Add or edit the preprocessor symbols.
../_images/iar_linker_opts.png

Figure 86. IAR Defined Symbols Box

Creating Additional ICall Enabled Tasks

The objective of this section is to familiarize the programmer with the process of adding an RTOS task that can communicate with the BLE5-Stack. Tasks call functions within the BLE5-Stack must follow a few additional steps to register with ICall. These details are covered below:

1. Follow all the steps detailed in Tasks to create a TI-RTOS task.

  1. Modify the task’s init function to register with ICall (explained in ICall Initialization and Registration)
Listing 105. ICall Registration for custom task
1
2
3
4
5
6
// ******************************************************************
// N0 STACK API CALLS CAN OCCUR BEFORE THIS CALL TO ICall_registerApp
// ******************************************************************
// Register the current thread as an ICall dispatcher application
// so that the application can send and receive messages.
ICall_registerApp(&selfEntity, &syncEvent);
  1. Modify the task’s main function to pend on syncEvent (explained in ICall Thread Synchronization)
Listing 106. ICall Wait
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
static void NotificationTask_taskFxn(UArg a0, UArg a1)
{
  // Initialize application
  NotificationTask_init();

  // Application main loop
  for (;;)
  {
      // Waits for an event to be posted associated with the calling thread.
      // Note that an event associated with a thread is posted when a
      // message is queued to the message receive queue of the thread
      events = Event_pend(syncEvent, Event_Id_NONE, SBP_ALL_EVENTS, ICALL_TIMEOUT_FOREVER);

      //...
  }
  // ...
}
  1. Modify number of ICall enabled tasks:
  • Increase the following preprocessor defines:
    • ICALL_MAX_NUM_TASKS (App)
    • OSAL_MAX_NUM_PROXY_TASKS (Stack)
  • See Compiler Options for steps on how to change symbols.

Warning

If (OSAL_MAX_NUM_PROXY_TASKS + 1) != ICALL_MAX_NUM_TASKS the stack will abort.

  1. Modify number of ICall entities:
  • Increase the following preprocessor defines:
    • ICALL_MAX_NUM_ENTITIES (App)

For further description of the above preprocessor defines, please see Table 16.

Production and Direct Test Mode (PTM, DTM)

This page will describe Production Test Mode (PTM) which allows a CC2640R2F BLE application in a “single-chip” configuration to temporarily expose the host control interface (HCI) test commands over the serial interface when triggered externally to do so (e.g. holding a GPIO pin low during power up). This test mode allows the device to be connected to a Bluetooth RF Tester in order to run Direct Test Mode (DTM) commands on a production line using the final release firmware, while leaving the UART GPIO pins available for the application to use at all other times. Note that this page only considers UART, and not SPI, as the transport protocol since it uses the least amount of GPIO’s and throughput is not a factor for DTM.

Note

Note: DTM defines two interface methods for controlling the LE PHY: HCI and 2-wire UART. The TI Bluetooth Low Energy protocol stack only supports the HCI method for DTM and PTM.

Direct Test Mode (DTM)

DTM is a standard method for testing BLE devices using the DTM HCI commands. A number of wireless test equipment manufactures, including Anritsu (MT8852B), Keysight and Rhode and Schwarz, make BLE Testers that use this mode. It is very useful to use these testers during development or on the production line in order to verify the RF performance of a BLE system. Complementary to these testers, it is also possible to create your own PC application that sends these DTM commands over the serial link. DTM is very well described in the Bluetooth Core Specification Version 5.0 Volume 6 Part F. All DTM commands as well as TI Vendor Specific modem test commands are accessible in embedded (single-device) application via API calls as well as over HCI in the Host_Test sample application. Refer to the TI Vendor Specific HCI guide in the documents folder of the SimpleLink CC2640R2 SDK.

Production Test Mode (PTM)

One problem with DTM is that it relies on a certain stack configuration (network processor with HCI exposed over UART) in order to work with the testers, though many end-applications don’t use this configuration. This would require the customer, during production, to flash the wireless MCU with a network processor image (e.g., host_test) before testing, and then re-flash with the final product image. To circumvent this, the TI BLE-Stack has implemented a feature called Production Test Mode (PTM), which allows for an embedded software application to support direct test mode without exposing the HCI to the UART pins under normal operation. Note that the pins used for PTM can also be used for an application UART interface. In this case, it is necessary to ensure that the other device that is connected to the UART interface does not run at the same time that DTM is being exercised. If the device powers up and goes into PTM mode (by a GPIO being held high or low or some other stimulus), the UART will then be used for DTM commands. If the device powers up normally and does not go into PTM mode, then the UART can be initialized by the application and used to communicate with the other device. DTM commands can also be called by the embedded BLE application.

Those wishing to use PTM in their application, should reference the _PTM_ configuration of the simple_peripheral project. Diffing this build configuration to the default build configuration should show the steps needed to enable PTM mode.

Tip

When adding PTM mode to the application, it is recommended to change the NPI task to use Task_create(...) as opposed to construct. In this way, the RAM needed by the NPI runtime task stack is consuming RAM that is not used in the application’s default behavior.

In order to determine if a command is accessible via PTM mode, users should refer to the translation tables created in icall_hci_tl.c under the define PTM_MODE.

Note: Out of box PTM builds does not support enabling gapbondmgr due to the limited flash space.

Optimizing Bluetooth Low Energy Stack Memory Usage

Configuration of the Bluetooth Low Energy protocol stack is essential for maximizing the amount of RAM and flash memory available for the application. Refer to Stack Configurations to configure parameters that impact runtime RAM usage, such as the maximum allowable size and number of PDUs. The TI Bluetooth Low Energy protocol stack is implemented to use a small RAM footprint, and allow the application to control the behavior of the stack by using the runtime ICall heap. For example, an application that only sends one GATT notification per connection event must store only one PDU in the heap, whereas as an application that must send multiple notifications must enqueue multiple PDUs in the heap.

To increase the available flash memory allocated to the application project, minimize the flash usage of the protocol stack by including only Bluetooth Low Energy features required to implement the defined role of the device. The available protocol stack configurable features are described in Stack Configurations. Adding additional features to the protocol stack has the net effect of reducing the amount of flash memory to the application.

Flash optimization

The following tips may be useful for reducing the footprint of the BLE5-Stack. In general, there is a feature vs. flash footprint tradeoff. Each of the improvements below offer a cost in terms of feature removal.

  • Verify that your application uses the optimize for flash size compiler optimization settings (default for TI projects).

  • Use only one page of SNV or do not use any NV pages if the GAP bond manager is not required. Set the NO_OSAL_SNV stack preprocessor option. See Using Simple NV for Flash Storage for a description of SNV.

  • Exclude the GATT client functionality by defining the GATT_NO_CLIENT predefined symbol in the stack project for peripheral devices. Alternatively, if you’re using a single-project example, the StackWrapper.a must be replaced with StackWrapper_GattNoClient.a in the Linker file search paths. This should only be done by devices that do not wish to discover the RPAO characteristic.

  • Remove or exclude debug DISPLAY, Two button menu or other unused drivers from the application project.

  • Use the stack library options defined in build_config.opt to pull in the smallest library available for the given use case. In general, this means a library that implements only one role (i.e. peripheral) with no additional features enabled (i.e. L2CAP CoC). See Stack Configurations.

    If you’re working on a non-stack library project, you can find the build_config.opt file in the app project folder.

  • Remove HAL Asserts by removing the EXT_HAL_ASSERT define from stack project.

  • Disable LE Secure Connections pairing if not needed. See LE Secure Connections on how to do this. Once LE Secure Connections is disabled in the app, then all the functions in ECCROMCC26XX.c can be stubbed out to simply return ECCROMCC26XX_STATUS_SUCCESS. Note that the ECC driver must still be present in the build, but stubbing the functions will save around 1.3kB of flash.

    Listing 108. Stubbing out ECC driver
    1
    2
    3
    4
    5
    int8_t ECCROMCC26XX_genKeys(uint8_t *privateKey, uint8_t *publicKeyX,
                            uint8_t *publicKeyY, ECCROMCC26XX_Params *params)
    {
      return (ECCROMCC26XX_STATUS_SUCCESS);
    }
    
  • If LESC is removed as above, then any code referencing SECURE_CONNS_CFG can be removed.

RAM optimization

The following tips may be useful for reducing the RAM footprint of the BLE5-Stack. It is important to remember that often removing RAM results in reduced throughput or features, the tradeoffs listed below should be evaluated carefully.

  • If using L2CAP CoC, reference RAM Considerations for defines that may configure L2CAP CoC functionality and their RAM implications

  • Set MAX_NUM_PDU and MAX_PDU_SIZE to reduce the amount of packets that can be queued up by the stack at a time. This will reduce heap consumption.

  • Disable LE Secure Connections pairing if not needed. See LE Secure Connections on how to do this. This will save ECCROMCC26XX_NIST_P256_WORKZONE_LEN_IN_BYTES during pairing. Removing LESC also removes the requirement of having MAX_PDU_SIZE set to 69, this can be overriden in ble_user_config.h to as low as 27.

  • The LE Data Length Extension feature will default to an RX size of 251. If the peer device also supports DLE and a connMaxRxOctets value is negotiated > 27 (default) then the controller will allocate connMaxRxOctets*4. 4 is the number of receive buffers in the controller and is a fixed parameter of the stack. However, connMaxRxOctets can be limited by either disabling Data Length Extension or limiting the max of TX and RX ocetets. Trimming the values of TX and RX is covered in RAM Considerations when using DLE.

  • Carefully set MAX_NUM_BLE_CONNS. This define has a large affect on the amount of dynamic memory used by the stack. Below is a list of structures that the stack will alloc on initialization based on number of Connections. Each structure is multiplied by MAX_NUM_BLE_CONNS. This is not an exhaustive list A rule of thumb is that the stack will allocate the sizes of the structures above on initialization, and around ~(1070 + connMaxRxOctets*4) per connection on connect.

    • sizeof(linkDBItem_t) : Link data base entry for each connection
    • sizeof( l2capChannel_t ) : At least one signaling channel for each connection
    • sizeof(prepareWrites_t) : Structure to hold prepare write table
    • GATT_MAX_NUM_PREPARE_WRITES * sizeof( attPrepareWriteReq_t ) : Prepare write queue.
    • sizeof(llConnState_t): Structure to hold connection information
    • 2*sizeof(dataQ_t) : Each connection’s RX and TX data queue
  • Check for heap failures by checking heapmgrMemFail from Debugging Common Heap Issues. If heap failures are occurring, attempt to tune stack build configuration using the features and defines above. See Stack Configurations for options that can be configured in the stack.

  • If heap failures still occur after optimizing the BLE-Stack build, the size of the heap can be increased by reducing the size of static allocation. Static allocation (.bss, .data) includes globally defined buffers, runtime task stacks, and other structures that are instantiated without the use of malloc.

    • Trim task stack sizes by inspecting them using Task –> Detailed view in TI-RTOS Object Viewer. If there is unused space their size can be decreased.
    • The system stack can be reduced in a similar way, its usage is shown under HWI –> Module view in ROV. Changing the system stack size is covered in System Stack.

Warning

The above RAM estimations may vary by release, and are not an exhaustive list. It is intended as a way to allow the developer to profile the RAM requirements based on the desired settings. The best way to estimate RAM usage is to measure it in the field using the techniques covered in Debugging Common Heap Issues

See Check System Flash and RAM Usage With Map File for the procedure to check the size of the configured protocol stack.

Defining Bluetooth Low Energy Behavior

This step involves using Bluetooth Low Energy protocol stack APIs to define the system behavior and adding profiles, defining the GATT database, configuring the security model, and so forth. Use the concepts explained in BLE5-Stack as well as the Bluetooth Low Energy API reference in BLE Stack API Reference.