Developer's Guide
Developer's Guide
Developer's Guide
Preface....................................................................................................................................... 11
1 Overview ........................................................................................................................... 13
1.1 Introduction .................................................................................................................. 13
1.2 Bluetooth low energy Protocol Stack Basics ........................................................................... 14
2 TI Bluetooth low energy Software Development Platform ........................................................ 16
2.1 Hardware and Software Architecture Overview ........................................................................ 17
2.1.1 ARM Cortex M0 (Radio Core) ................................................................................... 17
2.1.2 ARM Cortex M3 (System Core) ................................................................................. 18
2.2 Protocol Stack and Application Configurations ......................................................................... 18
2.3 Solution Platform ........................................................................................................... 19
2.4 Directory Structure ......................................................................................................... 19
2.4.1 Examples Folder .................................................................................................. 20
2.4.2 Source Folder ...................................................................................................... 21
2.5 Sample Applications ....................................................................................................... 21
2.6 Setting up the Integrated Development Environment ................................................................. 22
2.6.1 Installing the SDK ................................................................................................. 22
2.6.2 IAR .................................................................................................................. 22
2.6.3 Code Composer Studio ........................................................................................... 26
2.7 Working With Hex Files.................................................................................................... 31
2.8 Accessing Preprocessor Symbols ....................................................................................... 31
2.9 Top-Level Software Architecture ......................................................................................... 33
2.9.1 Standard Project Task Hierarchy ............................................................................... 34
3 RTOS Overview .................................................................................................................. 35
3.1 RTOS Configuration ....................................................................................................... 35
3.2 Semaphores ................................................................................................................ 36
3.2.1 Initializing a Semaphore .......................................................................................... 37
3.2.2 Pending a Semaphore ............................................................................................ 37
3.2.3 Posting a Semaphore ............................................................................................. 37
3.3 RTOS Tasks ............................................................................................................... 37
3.3.1 Creating a Task .................................................................................................... 38
3.3.2 Creating the Task Function ...................................................................................... 39
3.4 Clocks ........................................................................................................................ 39
3.4.1 API .................................................................................................................. 40
3.4.2 Functional Example ............................................................................................... 41
3.5 Queues ...................................................................................................................... 41
3.5.1 API .................................................................................................................. 42
3.5.2 Functional Example ............................................................................................... 43
3.6 Idle Task ..................................................................................................................... 44
3.7 Power Management........................................................................................................ 44
3.8 Hardware Interrupts ........................................................................................................ 45
3.9 Software Interrupts ......................................................................................................... 45
3.10 Flash ......................................................................................................................... 46
3.10.1 Flash Memory Map .............................................................................................. 47
3.10.2 Application and Stack Flash Boundary ........................................................................ 48
3.10.3 Using Simple NV for Flash Storage............................................................................ 48
List of Figures
1-1. Bluetooth low energy Protocol Stack .................................................................................... 14
2-1. SimpleLink CC2640 Block Diagram ..................................................................................... 17
2-2. Single-Device Processor Configuration ................................................................................. 18
2-3. Simple Network Processor Configuration ............................................................................... 18
2-4. Bluetooth low energy Stack Development System .................................................................... 19
2-5. Full Verbosity ............................................................................................................... 23
2-6. Custom Argument Variables .............................................................................................. 24
2-7. IAR Workspace Pane ...................................................................................................... 25
2-8. Installation Details .......................................................................................................... 27
2-9. Installation Details .......................................................................................................... 27
2-10. Import CCS Projects ....................................................................................................... 29
2-11. Project Explorer Structure ................................................................................................. 30
2-12. IAR Defined Symbols Box................................................................................................. 32
2-13. CCS Predefined Symbols ................................................................................................. 33
2-14. Top-Level Software Architecture ......................................................................................... 34
3-1. RTOS Execution Threads ................................................................................................. 35
3-2. Semaphore Functionality .................................................................................................. 36
3-3. General Task Topology .................................................................................................... 39
3-4. Queue Messaging Process ............................................................................................... 42
3-5. Preemption Scenario....................................................................................................... 46
3-6. System Flash Map ......................................................................................................... 47
3-7. System Memory Map ...................................................................................................... 50
3-8. Disabling Frontier Tool from Stack Project in IAR ..................................................................... 54
3-9. Disabling Frontier Tool from Stack Project in CCS .................................................................... 55
4-1. ICall Application – Protocol Stack Abstraction ......................................................................... 57
4-2. ICall Messaging Example ................................................................................................. 61
4-3. SBP Task Flow Chart ...................................................................................................... 63
5-1. GAP State Diagram ........................................................................................................ 68
5-2. Connection Event and Interval ........................................................................................... 69
5-3. Slave Latency ............................................................................................................... 70
5-4. GAP Abstraction ............................................................................................................ 72
5-5. Application Using GAPRole_TerminateConnection() .................................................................. 74
5-6. Tracing the GAP_LINK_TERMINATED_EVENT ....................................................................... 75
5-7. Application Using GAPCentralRole_StartDiscovery() ................................................................. 76
5-8. Tracing the GAP_DEVICE_DISCOVERY_EVENT .................................................................... 78
5-9. GATT Client and Server ................................................................................................... 79
5-10. Simple GATT Profile Characteristic Table from BTool ................................................................ 80
5-11. GATT Client Abstraction................................................................................................... 82
5-12. GATT Server Abstraction.................................................................................................. 85
5-13. Attribute Table Initialization ............................................................................................... 86
5-14. Get and Set Profile Parameter ........................................................................................... 94
5-15. Sniffer Capture Example .................................................................................................. 98
5-16. Parameters With Secure Connections ................................................................................. 100
5-17. Parameters Without Secure Connections ............................................................................. 100
5-18. Parameters With IO Capabilities ........................................................................................ 101
5-19. Flow Diagram Example .................................................................................................. 103
5-20. Just Works Pairing ........................................................................................................ 105
5-21. Interaction Between the GAPBondMgr and the Application ........................................................ 107
5-22. Numeric Comparison ..................................................................................................... 109
5-23. GAPBondMgr Example With Bonding Enabled ....................................................................... 111
5-24. Resolving List ............................................................................................................. 113
5-25. L2CAP Architectural Blocks ............................................................................................. 115
5-26. L2CAP Packet Fragmentation .......................................................................................... 116
5-27. Sample Connection and Data Exchange Between a Master and Slave Device Using a L2CAP
Connection-Oriented Channel in LE Credit Based Flow Control Mode ........................................... 118
5-28. PDU Sizes ................................................................................................................. 119
5-29. Read RSSI Command ................................................................................................... 122
5-30. RSSI Event ................................................................................................................ 123
5-31. PER Command ........................................................................................................... 125
5-32. PER Event ................................................................................................................. 126
5-33. Memory Mapping ......................................................................................................... 128
6-1. Drivers Folder ............................................................................................................. 131
9-1. Break on Read Access ................................................................................................... 144
9-2. Error Scan ................................................................................................................. 144
9-3. Viewing State of RTOS Tasks .......................................................................................... 145
9-4. Viewing the System Stack in Hwi ....................................................................................... 145
9-5. Adding RTOS ROM Symbol in IAR Project ........................................................................... 150
9-6. IAR Disassembly Without ROM Symbols ............................................................................. 151
9-7. IAR Disassembly With ROM ............................................................................................ 151
9-8. Adding RTOS ROM Symbol in CCS Project .......................................................................... 151
9-9. CCS Disassembly Without ROM Symbols ............................................................................ 152
9-10. CCS Disassembly With ROM Symbols ................................................................................ 152
9-11. Exception Information .................................................................................................... 154
9-12. PC Exception Example................................................................................................... 155
List of Tables
2-1. SDK Parent Folders ........................................................................................................ 19
2-2. Source Folders ............................................................................................................. 21
2-3. Supported Tools and Software ........................................................................................... 22
3-1. Flash System Map Definitions ............................................................................................ 47
3-2. OSAL_SNV Values ........................................................................................................ 48
3-3. Boundary Address Symbols .............................................................................................. 53
5-1. GAP Bond Manager Terminology ........................................................................................ 99
5-2. Definition of Terms........................................................................................................ 113
5-3. Data Length Update Procedure Sizes and Times .................................................................... 119
5-4. Bluetooth low energy Stack Configuration Parameters .............................................................. 129
5-5. Bluetooth low energy Protocol Stack Features ....................................................................... 130
9-1. Application Preprocessor Symbols ..................................................................................... 158
9-2. Stack Preprocessor Symbols............................................................................................ 159
H-1. API Function Map ......................................................................................................... 229
H-2. API Function Map ......................................................................................................... 231
References
Refer to the BLE-Stack release notes for the specific TI-RTOS component version associated with the
SDK.
1. TI Bluetooth low energy Vendor-Specific HCI Reference Guide v2.2.x,
C:\ti\simplelink\ble_sdk_2_02_xx_xxxxx\TI_BLE_Vendor_Specific_HCI_Guide.pdf
2. TI CC26x0 Technical Reference Manual, (SWCU117)
3. Measuring Bluetooth Low Energy Power Consumption Application Report, (SWRA478)
4. TI-RTOS Documentation Overview,
C:\TI\tirtos_cc13xx_cc26xx_x_xx_xx_xx\docs\Documentation_Overview_cc13xx_cc26xx.html
5. TI-RTOS Getting Started Guide,
C:\TI\tirtos_cc13xx_cc26xx_x_xx_xx_xx\docs\Getting_Started_Guide_cc13xx_cc26xx.pdf
6. TI-RTOS User's Guide, C:\TI\tirtos_cc13xx_cc26xx_x_xx_xx_xx\docs\Users_Guide.pdf
7. TI-RTOS SYS/BIOS Kernel User's Guide, C:\ti\tirtos_cc13xx_cc26xx_x_xx_xx_xx\products\bios_<as
installed>\docs\Bios_User_Guide.pdf
8. TI-RTOS Power Management for CC26xx,
C:\TI\tirtos_cc13xx_cc26xx_x_xx_xx_xx\docs\Power_Management.pdf
9. TI SYS/BIOS API Guide, C:\TI\tirtos_cc13xx_cc26xx_x_xx_xx_xx\products\bios_<as
installed>\docs\Bios_APIs.html
10. CC26xxware DriverLib API, C:\ti\tirtos_cc13xx_cc26xx_x_xx_xx_xx\products\cc26xxware_<as
installed>\doc\doc_overview.html
11. Sensor Controller Studio,http://www.ti.com/tool/sensor-controller-studio
12. TI-RTOS Drivers API Reference,
C:\TI\tirtos_cc13xx_cc26xx_x_xx_xx_xx\products\tidrivers_cc13xx_cc26xx_<as
installed>\docs\doxygen\html\index.html
13. CC2640 Simple Network Processor API Guide, C:\ti\simplelink\ble_sdk_2_02_xx_xxxxx\sap_<as
installed>\docs\CC2640 Simple Network Processer API Guide.pdf
14. ARM Cortex-M3 Devices Generic User's Guide,
http://infocenter.arm.com/help/topic/com.arm.doc.dui0552a/DUI0552A_cortex_m3_dgug.pdf
Available for download from the Bluetooth Special Interest Group (SIG) website. Registration may be
required.
15. Specification of the Bluetooth System, Covered Core Package, Version: 4.2 (02-Dec-2014),
https://www.bluetooth.com/specifications/bluetooth-core-specification
16. Adopted GATT Profile and Service Specifications,https://www.bluetooth.com/specifications/gatt
Links
17. TI Bluetooth low energy Wiki, www.ti.com/ble-wiki
18. Latest Bluetooth low energy Stack Download, www.ti.com/ble-stack
SimpleLink, Code Composer Studio, SmartRF are trademarks of Texas Instruments.
ARM, Cortex are registered trademarks of ARM Limited.
iBeacon is a trademark of Apple Inc.
Bluetooth is a registered trademark of Bluetooth SIG.
iOS is a registered trademark of Cisco.
Android is a trademark of Google Inc.
Eddystone is a trademark of Google Inc..
Intel is a registered trademark of Intel Corporation.
Windows 7 is a registered trademark of Microsoft Inc.
Python is a registered trademark of PSF.
ZigBee is a registered trademark of ZigBee Alliance.
Overview
The purpose of this document is to give an overview of the TI SimpleLink™ Bluetooth® low energy
CC26x0 wireless MCU software development kit to begin creating a Bluetooth low energy (BLE) custom
application. This document also introduces the Bluetooth low energy specification. Do not use this
document as a substitute for the complete Bluetooth specification. For more details, see the Specification
of the Bluetooth System or some introductory material at the TI Bluetooth low energy Wiki.
1.1 Introduction
Version 4.2 of the Bluetooth specification allows for two systems of wireless technology: Basic Rate (BR:
BR/EDR for Basic Rate/Enhanced Data Rate) and Bluetooth low energy. The Bluetooth low energy
system was created to transmit small packets of data, while consuming significantly less power than
BR/EDR devices.
The TI Bluetooth low energy protocol stack (BLE-Stack) v2.2.x includes these new features from Version
4.2 of the specification:
• LE Secure Connections
• LE Data Length extension
• LE Privacy 1.2
The stack also supports the following 4.1 features:
• LE L2CAP Connection-Oriented Channel Support
• LE Link Layer Topology
• LE Ping
• Slave Feature Exchange
• Connection Parameter Request
These features are optional in the 4.2 specification, and can be selectively enabled at build time.
The Bluetooth low energy protocol stack (or protocol stack) consists of the controller and the host. This
separation of controller and host derives from the implementation of classic Bluetooth BR/EDR devices,
where the two sections are implemented separately. Any profiles and applications sit on top of the GAP
and GATT layers of the protocol stack.
The physical layer (PHY) is a 1-Mbps adaptive frequency-hopping GFSK (Gaussian frequency-shift
keying) radio operating in the unlicensed 2.4-GHz ISM (industrial, scientific, and medical) band.
The link layer (LL) controls the RF state of the device, with the device in one of five states:
• Standby
• Advertising
• Scanning
• Initiating
• Connected
Advertisers transmit data without connecting, while scanners scan for advertisers. An initiator is a device
that responds to an advertiser with a request to connect. If the advertiser accepts the connection request,
both the advertiser and initiator enter a connected state. When a device is connected, it connects as either
master or slave. The device initiating the connection becomes the master and the device accepting the
request becomes the slave.
The host control interface (HCI) layer provides communication between the host and controller through a
standardized interface. This layer can be implemented either through a software API or by a hardware
interface such as UART, SPI, or USB. Standard HCI commands and events are specified in the
Specification of the Bluetooth System. TI's proprietary commands and events are specified in TI Bluetooth
low energy Vendor-Specific HCI Reference Guide v2.2.1.
The link logical control and adaption protocol (L2CAP) layer provides data encapsulation services to the
upper layers, allowing for logical end-to-end communication of data. The security manager (SM) layer
defines the methods for pairing and key distribution, and provides functions for the other layers of the
protocol stack to securely connect and exchange data with another device. See Section 5.3.5 for more
information on TI's implementation of the SM layer. The generic access protocol (GAP) layer directly
interfaces with the application and/or profiles, to handle device discovery and connection-related services
for the device. GAP handles the initiation of security features. See Section 5.1 for more information on TI's
implementation of the GAP layer.
The attribute protocol (ATT) layer protocol allows a device to expose certain pieces of data or attributes, to
another device. The generic attribute protocol (GATT) layer is a service framework that defines the sub-
procedures for using ATT. Data communications that occur between two devices in a Bluetooth low
energy connection are handled through GATT sub-procedures. The application and/or profiles will directly
use GATT. See Section 5.3 for more information on TI's implementation of the ATT and GATT layers.
The TI royalty-free Bluetooth low energy software development kit (SDK) is a complete software platform
for developing single-mode Bluetooth low energy applications. This kit is based on the SimpleLink
CC2640, complete System-on-Chip (SoC) Bluetooth low energy solution. The CC2640 combines a 2.4-
GHz RF transceiver, 128-KB in-system programmable memory, 20KB of SRAM, and a full range of
peripherals. The device is centered on an ARM® Cortex®-M3 series processor that handles the application
layer and Bluetooth low energy protocol stack and an autonomous radio core centered on an ARM
Cortex®-M0 processor that handles all the low-level radio control and processing associated with the
physical layer and parts of the link layer. The sensor controller block provides additional flexibility by
allowing autonomous data acquisition and control independent of the Cortex-M3 processor, further
extending the low-power capabilities of the CC2640. Figure 2-1 shows the block diagram. For more
information on the CC2640, see the CC26xx Technical Reference Manual (TRM).
NOTE: This kit supports development of Bluetooth low energy applications on the following
SimpleLink CC26x0 wireless MCUs: CC2640 and CC2650. The multi-standard CC2650
wireless MCU supports Bluetooth low energy as well as other wireless protocols, such as
ZigBee® and 6LoWPAN. The CC2640 supports Bluetooth low energy only. All code
generated from the BLE-Stack v2.2.x SDK is binary compatible and exchangeable with both
the CC2650 and CC2640 wireless MCUs in the same device package configuration.
Throughout this document, CC2640 and CC2650 may be used interchangeably.
16 TI Bluetooth low energy Software Development Platform SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Hardware and Software Architecture Overview
SWRU393E – October 2010 – Revised March 2018 TI Bluetooth low energy Software Development Platform 17
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Hardware and Software Architecture Overview www.ti.com
CC2640
Application
Host
Controller
Figure 2-2. Single-Device Processor Configuration Figure 2-3. Simple Network Processor
Configuration
18 TI Bluetooth low energy Software Development Platform SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Solution Platform
SWRU393E – October 2010 – Revised March 2018 TI Bluetooth low energy Software Development Platform 19
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Directory Structure www.ti.com
20 TI Bluetooth low energy Software Development Platform SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Directory Structure
SWRU393E – October 2010 – Revised March 2018 TI Bluetooth low energy Software Development Platform 21
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Setting up the Integrated Development Environment www.ti.com
NOTE: If installing the Bluetooth low energy SDK to a nondefault path, do not exceed the maximum
length of the file system namepath. Actual paths may differ from the figures.
2.6.2 IAR
IAR contains many features beyond the scope of this document. More information and documentation can
be found at www.iar.com.
development using the CC2640, TI recommends purchasing the complete version of IAR without
any restrictions. You can find the information on purchasing the complete version of IAR at
https://www.iar.com/buy.
2. Run the ti_emupack_setup.exe file in the IAR installation, <iar_install>\arm\drivers\ti-xds.
NOTE: IAR is usually installed to C:\Program Files (x86)\IAR Systems. The full, non-code size
restricted version of IAR is required.
NOTE: For full verbosity during building, TI recommends showing all the build output messages.
SWRU393E – October 2010 – Revised March 2018 TI Bluetooth low energy Software Development Platform 23
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Setting up the Integrated Development Environment www.ti.com
NOTE: If any additional argument groups on the Workspace or Global tabs are present that conflict
with the CC26xx TI-RTOS group, disable the groups. If these tools are installed to a non-
default location, these variables must be manually updated.
NOTE: The simple_peripheral project is referenced throughout this document. All of the Bluetooth
low energy projects included in the development kit have a similar structure.
NOTE: This workspace file is for the simple_peripheral project. When selected, the files associated
with the workspace become visible in the Workspace pane on the left side of the screen. See
Figure 2-7.
24 TI Bluetooth low energy Software Development Platform SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Setting up the Integrated Development Environment
This and all CC26x0 project workspaces contain the following projects. The stack and application project
names vary based on the evaluation board.
• The application project (cc2650em_app)
• The Bluetooth low energy protocol stack project (cc2650em_stack)
Select either project as the active project by clicking the respective tab at the bottom of the workspace
pane. In Figure 2-7, the Overview tab is selected. This tab displays the file structure for both projects
simultaneously. In this case, use the drop-down menu at the top of the workspace pane to select the
active project. Each of these projects produces a separate downloadable object. TI chose this dual-image
architecture so that the application can be updated independent of the stack. The simple_peripheral
sample project is the primary reference target for the description of a generic application in this guide. The
simple_peripheral project implements a basic Bluetooth low energy peripheral device including a GATT
server with GATT services. This project can be a framework for developing peripheral-role applications.
SWRU393E – October 2010 – Revised March 2018 TI Bluetooth low energy Software Development Platform 25
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Setting up the Integrated Development Environment www.ti.com
NOTE:
• Do not modify the CPU Variant in the project settings. All sample projects are
configured with a CPU type, and changing this setting (that is, from CC2640 to
CC2650) may result in build errors.
• All CC2640 and CC2650 code is binary-compatible and interchangeable for
Bluetooth low energy-Stack software builds in the same device package
configuration.
• The CPU type is the same for all silicon package types.
Because the workspace is split into two projects (application and stack), the following is the specific
sequence for compilation and download.
1. Select the new stack project.
2. Select Project→ Download→ Download Active Application to download the stack project.
3. Select the application project.
NOTE: The stack project defines the flash and RAM boundary parameters used by the application
project. Any modifications to the stack project require a rebuild of the stack project, followed
by a rebuild of the application project to use the new boundary settings. See Section [3.12
Frontier Tool].
After the initial build, if the stack project is not modified, do the following:
NOTE: When the application is downloaded (that is, flash memory programmed), you can use
Project→ Debug without Downloading.
Sample applications that implement the Over the Air Download (OAD) firmware update capability require
the Boot Image Manager (BIM) project to be built. Refer to the CC2640 BLE OAD User's Guide for more
details.
26 TI Bluetooth low energy Software Development Platform SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Setting up the Integrated Development Environment
5. After installation completes, select Help→ About Code Composer Studio to verify the installation
details (see Figure 2-8 and Figure 2-9 for an illustrative example).
6. Verify that the ARM Compiler Tools matches the version as specified in the BLE-Stack release notes
and that CC26xx Device Support is updated to the latest available version. Use the Help -> Check for
SWRU393E – October 2010 – Revised March 2018 TI Bluetooth low energy Software Development Platform 27
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Setting up the Integrated Development Environment www.ti.com
Updates menu to check for updated components. Refer to Section 2.6.3.2 to install a specific TI ARM
Compiler version.
NOTE: This is the CCS directory for the simple_peripheral project. CCS discovers two projects (the
application project and the stack project).
5. Click the box next to an application project (depending on your development platform) and the stack
project to select them.
6. Select Copy projects into workspace.
28 TI Bluetooth low energy Software Development Platform SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Setting up the Integrated Development Environment
Click the project name in the file explorer to select the project as the active project. In Figure 2-11, the
application is selected as the active project. Each of these projects produces a separate, downloadable
image. TI chose this dual-image architecture so that the application can be updated independent of the
stack.
SWRU393E – October 2010 – Revised March 2018 TI Bluetooth low energy Software Development Platform 29
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Setting up the Integrated Development Environment www.ti.com
The simple_peripheral sample project is the primary sample application for the description of a generic
application in this guide. The simple_peripheral project implements a basic Bluetooth low energy
peripheral device including a GATT server with GATT services. This project can be used as a framework
for developing peripheral-role applications.
NOTE:
• Do not modify the CPU Variant in the project settings.
• All sample projects are configured with a CPU type and changing this setting
(that is, from CC2640 to CC2650) may result in build errors.
• All CC2640/CC2650 code is binary compatible and interchangeable for
Bluetooth low energy software stack builds.
• The CPU type is the same for all silicon package types.
Because the workspace is split into two projects (application and stack), the following is the specific
sequence for compilation and download.
1. Set the stack project as the active project.
30 TI Bluetooth low energy Software Development Platform SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Working With Hex Files
NOTE: The stack project defines flash and RAM boundary parameters used by the application
project. Any modifications to the stack project will require a rebuild of the stack project
followed by a rebuild of the application project to use the new boundary settings. See
Section 3.12.
After the initial build and download, if the stack project is not modified, do the following:
1. Build the application.
2. Download the application.
Sample applications that implement the Over the Air Download (OAD) firmware update capability require
the Boot Image Manager (BIM) project to be built. Refer to the CC2640 BLE OAD User's Guide for more
details.
NOTE: In IAR:
1. Open the Project Options for either project in the C/C++ Compiler Category.
2. Open the Preprocessor tab.
3. View the Defined symbols box (see Figure 2-12).
SWRU393E – October 2010 – Revised March 2018 TI Bluetooth low energy Software Development Platform 31
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Accessing Preprocessor Symbols www.ti.com
32 TI Bluetooth low energy Software Development Platform SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Top-Level Software Architecture
SWRU393E – October 2010 – Revised March 2018 TI Bluetooth low energy Software Development Platform 33
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Top-Level Software Architecture www.ti.com
• The stack image includes the lower layers of the Bluetooth low energy protocol stack from the LL up to
and including the GAP and GATT layers (see Figure 1-1). Most of the Bluetooth low energy protocol
stack code is provided as a library.
• The application image includes the profiles, application code, drivers, and the ICall module.
34 TI Bluetooth low energy Software Development Platform SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Chapter 3
SWRU393E – October 2010 – Revised March 2018
RTOS Overview
TI-RTOS is the operating environment for Bluetooth low energy projects on CC2640 devices. The TI-
RTOS kernel is a tailored version of the SYS/BIOS kernel and operates as a real-time, pre-emptive,
multithreaded operating system with tools for synchronization and scheduling (XDCTools). The SYS/BIOS
kernel manages four distinct levels of execution threads (see Figure 3-1).
• Hardware interrupt service routines (ISRs)
• Software interrupt routines
• Tasks
• Background idle functions
This section describes these four execution threads and various structures used throughout the RTOS for
messaging and synchronization. In most cases, the underlying RTOS functions have been abstracted to
higher-level functions in the util.c file. The lower-level RTOS functions are described in the SYS/BIOS
module section of the TI SYS/BIOS API Guide. This document also defines the packages and modules
included with the TI-RTOS.
The default project configuration is to use elements of the RTOS from the CC26xx ROM. In this case,
some RTOS features are unavailable. If any ROM-unsupported features are added to the RTOS
configuration file, use an RTOS in flash configuration. Using RTOS in flash consumes additional flash
memory. The default RTOS configuration supports all features required by the respective example
projects in the SDK.
See the TI-RTOS documentation for a full description of configuration options.
3.2 Semaphores
The kernel package provides several modules for synchronizing tasks such as the semaphore.
Semaphores are the prime source of synchronization in the CC2640 software and are used to coordinate
access to a shared resource among a set of competing tasks (that is, the application and Bluetooth low
energy stack). Semaphores are used for task synchronization and mutual exclusion.
Figure 3-2 shows the semaphore functionality. Semaphores can be counting semaphores or binary
semaphores. Counting semaphores keep track of the number of times the semaphore is posted with
Semaphore_post(). When a group of resources are shared between tasks, this function is useful. Such
tasks might call Semaphore_pend() to see if a resource is available before using one. Binary semaphores
can have only two states: available (count = 1) and unavailable (count = 0). Binary semaphores can be
used to share a single resource between tasks or for a basic-signaling mechanism where the semaphore
can be posted multiple times. Binary semaphores do not keep track of the count; they track only whether
the semaphore has been posted.
// Configure task
Task_Params_init(&taskParams);
taskParams.stack = sbpTaskStack;
taskParams.stackSize = SBP_TASK_STACK_SIZE;
taskParams.priority = SBP_TASK_PRIORITY;
The task creation is done in the main() function, before the SYS/BIOS scheduler is started by
BIOS_start(). The task executes at its assigned priority level after the scheduler is started.
TI recommends using the existing application task for application-specific processing. When adding an
additional task to the application project, the priority of the task must be assigned a priority within the
RTOS priority-level range, defined in the appBLE.cfg RTOS configuration file.
/* Reduce number of Task priority levels to save RAM */
Task.numPriorities = 6;
Do not add a task with a priority equal to or higher than the Bluetooth low energy protocol stack task and
related supporting tasks (for example, the GapRole task). See Section 2.9.1 for details on the system task
hierarchy.
Ensure the task has a minimum task stack size of 512 bytes of predefined memory. At a minimum, each
stack must be large enough to handle normal subroutine calls and one task preemption context. A task
preemption context is the context that is saved when one task preempts another as a result of an interrupt
thread readying a higher priority task. Using the TI-RTOS profiling tools of the IDE, the task can be
analyzed to determine the peak task stack usage.
NOTE: The term created describes the instantiation of a task. The actual TI-RTOS method is to
construct the task. See Section 3.11.5 for details on constructing RTOS objects.
In the simple_peripheral task, the task spends most of its time in the blocked state, where it is pending a
semaphore. When the semaphore of the task is posted to from an ISR, callback function, queue, and so
forth, the task becomes ready, processes the data, and returns to this paused state. See Section 4.2.1 for
more detail on the functionality of the simple_peripheral task.
3.4 Clocks
Clock instances are functions that can be scheduled to run after a certain number of clock ticks. Clock
instances are either one-shot or periodic. These instances start immediately upon creation, are configured
to start after a delay, and can be stopped at any time. All clock instances are executed when they expire
in the context of a software interrupt. The following example shows the minimum resolution is the RTOS
clock tick period set in the RTOS configuration.
/* 10 us tick period */
Clock.tickPeriod = 10;
Each tick, which is derived from the RTC, launches a clock SWI that compares the running tick count with
the period of each clock to determine if the associated function should run. For higher-resolution timers, TI
recommends using a 16-bit hardware timer channel or the sensor controller.
3.4.1 API
You can use the RTOS clock module functions directly (see the clock module in the SYS/BIOS API 0). For
usability, these functions have been extracted to the following functions in util.c.
Parameters
• pClock – pointer to clock instance structure
• clockCB – function to be called upon clock expiration
• clockDuration – length of first expiration period
• clockPeriod – length of subsequent expiration periods. If set to 0, clock is a one-shot
clock.
• startFlag – TRUE to start immediately, FALSE to wait. If FALSE, Util_startClock()
must be called later.
• arg – argument passed to callback function
3.5 Queues
Queues let applications process events in order by providing a FIFO ordering for event processing. A
project may use a queue to manage internal events coming from application profiles or another task.
Clocks must be used when an event must be processed in a time-critical manner. Queues are more useful
for events that must be processed in a specific order.
The Queue module provides a unidirectional method of message passing between tasks using a FIFO. In
Figure 2-14, a queue is configured for unidirectional communication from task A to task B. Task A pushes
messages onto the queue and task B pops messages from the queue in order. Figure 3-4 shows the
queue messaging process.
3.5.1 API
The RTOS queue functions have been abstracted into functions in the util.c file. See the Queue module in
the TI SYS/BIOS API Guide for the underlying functions. These utility functions combine the Queue
module with the ability to notify the recipient task of an available message through semaphores. In
CC2640 software, the semaphore used for this process is the same semaphore that the given task uses
for task synchronization through ICall. For an example of this, see the SimpleBLECentral_enqueueMsg()
function. Queues are commonly used to limit the processing time of application callbacks in the context of
the higher level priority task. In this manner, the higher priority task pushes a message to the application
queue for processing later instead of immediate processing in its own context. Section 3.5 further
describes this process.
return FALSE;
}
2. Statically allocate and then construct queue.
// Queue object used for app messages
static Queue_Struct appMsg;
static Queue_Handle appMsgQueue;
…
// Create an RTOS queue for messages to be sent to app.
apMsgQueue = Util_constructQueue(&appMsg);
3. Wait for button to be pressed and processed in application context (in the following diagram, green
corresponds to the processor running in the application context and red corresponds to an HWI).
Application wakes up
// If RTOS queue is not empty, process app
and realizes the queue
message
is not empty. The top
if (!Queue_empty(appMsgQueue))
message is popped and {
processed... sbvEvt_t *pMsg =
(sbcEvt_t*)Util_dequeueMsg(appMsgQueue);
if (pMsg)
{
// Process message
SimpleBLECentral_processAppMsg(pMsg);
...
static void
SimpleBLECentral_processAppMsg(sbcEvt_t *pMsg)
...and the appropriate
{
processing function is
switch (pMsg->event)
called based on the
{
SBC_KEY_CHANGE_E
...
VT.
case SBC_KEY_CHANGE_EVT:
SimpleBLECentral_handleKeys(0, pMsg-
>status);
break;
...
}
}
NOTE: To preserve the RTOS heap, the amount of dynamically created SWIs must be limited as
described in Section 3.11.5.
3.10 Flash
The flash is split into erasable pages of 4kB. The various sections of flash and their associate linker files
are as follows.
• Application Image: code space for the application project. This image is configured in the linker
configuration file of the application: cc26xx_app.icf (IAR) and cc26xx_app.cmd (CCS).
• Stack Image: code space for the stack project. This image is configured in the linker configuration file
of the stack: cc26xx_stack.icf (IAR) and cc26xx_ stack.cmd (CCS).
• Simple NV (SNV): area used for nonvolatile memory storage by the GAP Bond Manager and also
available for use by the application. See Section 3.10.3 for configuring SNV. When configured, the
SNV flash storage area is part of the stack image.
• Customer Configuration Area (CCA): the last sector of flash used to store customer-specific chip
configuration (CCFG) parameters. The unused space of the CCA sector is allocated to the application
project. See Section 3.10.4.
Table 3-1 summarizes the Flash System Map definitions from Figure 3-6 and provides the associated
linker definitions or symbols that can be found in the respective IDE linker files.
Other values for OSAL_SNV are invalid. Using less than the maximum value has the net effect of
allocating more code space to the application or stack project. SNV can be read from or written to using
the following APIs.
The following example shows how to read and write an array of bytes using SNV flash:
#define BUF_LEN 10
#define SNV_ID_APP 0x80
uint8 buf[BUF_LEN] = {0,};
// Initialize application
simple_peripheral_init();
uint8 status = SUCCESS;
No prior initialization of a NV item ID is required; the OSAL SNV manager initializes the NV ID when first
accessed by a successful osal_snv_write() call.
When reading or writing large amounts of data to SNV, TI recommends placing the read/write data in
statically (linker) allocated arrays or buffers allocated from the heap. Placing large amounts of data in local
arrays may result in a task stack overflow.
By default, osalSnvId_t and osalSnvLen_t are type defined as uint8. To use uint16-type definitions, define
the preprocessor symbol OSAL_SNV_UINT16_ID in both the application and stack projects.
For IAR:
define region FLASH_LAST_PAGE = mem:[from(FLASH_SIZE) - 0x1000 to FLASH_SIZE-1];
...
place at end of FLASH_LAST_PaGE { readonly section .ccfg };
See the TI CC26x0 Technical Reference Manual (SWCU117) for details on CCFG fields and related
configuration options, including how to set the CCFG to disable access to internal flash memory contents.
In IAR, to change the size of the CSTACK, adjust the STACK_SIZE symbol value in the linker file of the
application.
For CCS, the RTOS system stack is defined by the Program.stack parameter in the appBLE.cfg RTOS
configuration file:
/* main() and Hwi, Swi stack size */
Program.stack = 1024;
BIOS.heapSize = 1668;
This heap (HeapMem) is used to initialize RTOS objects and allocate the task runtime stack of the
Bluetooth low energy protocol stack. TI chose this size of this heap to meet the system initialization
requirements. Due to the small size of this heap, TI does not recommend allocating memory from the
RTOS heap for general application use. For more information on the TI-RTOS heap configuration, see the
Heap Implementations section of the TI-RTOS SYS/BIOS Kernel User's Guide.
The application must use a separate heap. The ICall module uses an area of application RAM which can
be used by the various tasks. The size of this ICall heap is defined by the HEAPMGR_SIZE preprocessor
definition in the application project. Using a non-zero value sets the ICall heap to the specified value, while
a HEAPMGR_SIZE value of zero (0) auto sizes the heap to a size equal to the amount of available free
RAM not allocated by the linker. By default, the simple_peripheral project uses the auto size feature.
Although the ICall heap is defined in the application project, this heap is also shared with the Bluetooth
low energy protocol stack. APIs that allocate memory (such as GATT_bm_alloc()) allocate memory from
the ICall heap.
To profile the amount of ICall heap used, define the HEAPMGR_METRICS preprocessor symbol in the
application project. Refer to Section 9.6 to determine the size of the ICall heap when the auto heap size
feature is enabled..
NOTE: The auto heap size feature does not determine the amount of heap needed for the
application. The system designer must ensure that the heap has the required space to meet
the application’s runtime memory requirements.
The following is an example of dynamically allocating a variable length (n) array using the ICall heap:
//define pointer
uint8_t *pArray;
By declaring a static Clock_Struct object and passing this object to Clock_construct(), the .DATA section
for the actual Clock_Struct is used; not the limited RTOS heap. Clock_create() would cause the RTOS to
allocate the Clock_Struct using the limited heap of the RTOS.
This example shows how clocks and RTOS objects should be initialized throughout a project. If creating
RTOS objects, the size of the RTOS heap may require adjustment in app_ble.cfg.
3.12 Configuration of RAM and Flash Boundary Using the Frontier Tool
The frontier tool is a utility to automatically adjust the respective RAM and flash boundary address
symbols shared between the application and stack projects. Frontier runs as a post-build step of the stack
project, and adjusts the respective RAM and flash boundaries based on analysis of the stack linker and
map files. No project files are modified by the frontier tool. The frontier tool does not modify any source
code or perform any compiler or linker optimization; the tool adjusts and updates the respective flash and
RAM boundary addresses, located in the compiler and linker configuration files used by the application
and stack project.
The frontier tool is installed to the following path within the SDK:
$BLE_INSTALL$\tools\frontier\frontier.exe
The python source for this tool is also included.
Table 3-3 shows the boundary address symbols updated by the frontier tool.
All sample application projects are, by default, configured to use the frontier tool; thus, no user
configuration of the frontier tool is required. The boundary files may be updated when the stack
configuration is changed, or when any files are updated in the stack project that result in a change in the
size of the stack image. It is therefore required to rebuild the application project anytime the stack project
is built.
Note for previous SDK users: The frontier tool replaces the boundary tool used in earlier SDKs.
NOTE: The values in boundary linker configuration file and Boundary C definition file must match.
The Application
This section describes the application portion of the simple_peripheral project, which includes the
following:
• Pre-RTOS initialization
• simple_peripheral task: This is the application task, which is the lowest priority task in the system. The
code for this task is in simple_peripheral.c and simple_peripheral in the Application IDE folder.
• ICall: This interface module abstracts communication between the stack and other tasks.
NOTE: The GAPRole task is also part of the application project workspace. The functionality of this
task relates more closely to the protocol stack.
Section 5.2 describes this functionality.
#ifndef POWER_SAVING
/* Set constraints for Stanby, powerdown and idle mode */
Power_setConstraint(Power_SB_DISALLOW);
Power_setConstraint(Power_IDLE_PD_DISALLOW);
#endif // POWER_SAVING
SimpleBLEPeripheral_createTask();
return 0;
}
Chapter 3 describes how the application and GAPRole tasks are constructed. The stack task is created
here as well in ICall_createRemoteTasks(). The ICall module is initialized through ICall_init(). In terms of
the IDE workspace, main.c exists in the application project (when the project is compiled and placed in the
allocated section of flash of the application).
4.2 ICall
4.2.1 Introduction
Indirect Call Framework (ICall) is a module that provides a mechanism for the application to interface with
the Bluetooth low energy protocol stack services (that is, Bluetooth low energy stack APIs) as well as
certain primitive services provided by the RTOS (for example, thread synchronization). ICall allows the
application and protocol stack to operate efficiently, communicate, and share resources in a unified RTOS
environment.
The central component of the ICall architecture is the dispatcher, which facilitates the application program
interface between the application and the Bluetooth low energy protocol stack task across the dual-image
boundary. Although most ICall interactions are abstracted within the Bluetooth low energy protocol stack
APIs (for example, GAP, HCI, and so forth), the application developer must understand the underlying
architecture for the Bluetooth low energy protocol stack to operate properly in the multithreaded RTOS
environment.
The ICall module source code is provided in the ICall and ICall Bluetooth low energy IDE folders in the
application project.
NOTE: The ICall framework is not the GATT server and client architecture as defined by the
Bluetooth low energy protocol.
Calling ICall_init() initializes the ICall primitive service (for example, heap manager) and framework.
Calling ICall_createRemoteTasks() creates but does not start the Bluetooth low energy protocol stack
task. Before using ICall protocol services, the server and client must enroll and register with ICall. The
server enrolls a service, which is defined at build time. Service function handler registration uses a globally
defined unique identifier for each service. For example, Bluetooth low energy uses
ICALL_SERVICE_CLASS_BLE for receiving Bluetooth low energy protocol stack messages through ICall.
The following is a call to enroll the Bluetooth low energy protocol stack service (server) with ICall in
osal_icall_ble.c:
// ICall enrollment
/* Enroll the service that this stack represents */
ICall_enrollService(ICALL_SERVICE_CLASS_BLE, NULL, &entity, &sem);
The registration mechanism is used by the client to send and/or receive messages through the ICall
dispatcher.
For a client (for example, application task) to use the Bluetooth low energy stack APIs, the client must first
register its task with ICall. This registration usually occurs in the task initialization function of the
application. The following is an example from simple_peripheral_int() in simple_peripheral:
// Register the current thread as an ICall dispatcher application
// so that the application can send and receive messages.
ICall_registerApp(&selfEntity, &sem);
The application supplies the selfEntity and sem inputs. These inputs are initialized for the task of the client
(for example, application) when the ICall_registerApp() returns are initialized. These objects are
subsequently used by ICall to facilitate messaging between the application and server tasks. The sem
argument represents the semaphore for signaling and the selfEntity represents the destination message
queue of the task. Each task registering with ICall have unique sem and selfEntity identifiers.
NOTE: Bluetooth low energy protocol stack APIs defined in ICallBLEApi.c and other ICall primitive
services are not available before ICall registration.
milliseconds is a time-out period in milliseconds. If not already returned after this time-out period, the
function returns with ICALL_ERRNO_TIMEOUT. If ICALL_TIMEOUT_FOREVER is passed as
milliseconds, the ICall_wait() blocks until the semaphore is posted. Allowing an application or a server
thread to block yields the processor resource to other lower priority threads or conserves energy by
shutting down power and/or clock domains when possible.
The semaphore associated with an RTOS thread is signaled by either of the following conditions:
• A new message is queued to the RTOS thread queue of the application.
• ICall_signal() is called to unblock the semaphore.
ICall_signal() is used so an application or a server can add its own event to unblock ICall_wait() and
synchronize the thread. ICall_signal() accepts semaphore handle as its sole argument as follows:
//static inline ICall_Errno ICall_signal(ICall_Semaphore msgem)
ICall_signal(sem);
The semaphore handle associated with the thread is obtained through either ICall_enrollService() call or
ICall_registerApp() call.
NOTE: Do not call an ICall function from a stack callback. This action can cause ICall to abort (with
ICall_abort()) and break the system.
This initialization function (simple_peripheral_init()) configures several services for the task and sets
several hardware and software configuration settings and parameters. The following list contains some
common examples:
• Initializing the GATT client
• Registering for callbacks in various profiles
• Setting up the GAPRole
• Setting up the Bond Manager
• Setting up the GAP layer
• Configuring hardware modules such as LCD, SPI, and so forth
For more information on all of these examples, see their respective sections in this guide.
NOTE: In the application initialization function, ICall_registerApp() must be called before any stack
API is called.
if (errno == ICALL_ERRNO_SUCCESS)
{
...
When an event or other stimulus occurs and is processed, the task waits for the semaphore and remains
in a blocked state until there is another reason to process. Figure 4-3 shows this flow.
As shown in Figure 4-3, various reasons cause the semaphore to be posted to and the task to become
active to process.
{
if ((src == ICALL_SERVICE_CLASS_BLE) && (dest == selfEntity))
{
ICall_Event *pEvt = (ICall_Event *)pMsg;
if (pMsg)
{
ICall_freeMsg(pMsg);
}
}
NOTE: In the code, the pEvt->signature is always equal to 0xFFFF if the event is coming from the
Bluetooth low energy protocol stack.
When selecting an event value for an intertask event, the value must be unique for the given task and
must be a power of 2 (so only 1 bit is set). Because the pEvt->event variable is initialized as uint16_t, this
initialization allows for a maximum of 16 events. The only event values that cannot be used are those
already used for Bluetooth low energy OSAL global events (stated in bcomdef.h):
/************************************************************
* BLE OSAL GAP GLOBAL Events
*/
#define GAP_EVENT_SIGN_COUNTER_CHANGED 0x4000 //!< The device level sign counter changed
NOTE: These intertask events are a different set of events than the intratask events mentioned in
Section 4.3.2.4.
if (!Queue_empty(appMsgQueue))
{
sbpEvt_t *pMsg = (sbpEvt_t *)Util_dequeueMsg(appMsgQueue);
if (pMsg)
{
// Process message.
SimpleBLEPeripheral_processAppMsg(pMsg);
The function that sets this bit in the events variable must also post to the semaphore to wake up the
application for processing. An example of this process is the clock handler that handles clock timeouts
(see Section 3.4.2). The following is an example of processing the periodic event from the main task
function of simple_peripheral:
if (events & SBP_PERIODIC_EVT)
{
events &= ~SBP_PERIODIC_EVT;
Util_startClock(&periodicClock);
NOTE: When adding an event, the event must be unique for the given task and must be a power of
2 (so that only one bit is set). Because the events variable is initialized as uint16_t, this
initialization allows for a maximum of 16 internal events.
Similar to the bitfield approach adopted by the previous section, the application can define custom events
to be registered with the RTOS; instead of manually assigning the bitfields, the predefined RTOS events
are used. For ARM devices such as the CC2640, up to 32 events can be used. The code snippet below
shows the events defined in simple_ap.
#define AP_NONE Event_Id_NONE // No Event
#define AP_EVT_PUI Event_Id_00 // Power-Up Indication
#define AP_EVT_ADV_ENB Event_Id_01 // Advertisement Enable
#define AP_EVT_ADV_END Event_Id_02 // Advertisement Ended
#define AP_EVT_CONN_EST Event_Id_03 // Connection Established
#define AP_EVT_CONN_TERM Event_Id_04 // Connection Terminated
#define AP_EVT_AUTHENTICATION Event_Id_05 // Authentication IO
#define AP_EVT_SECURITY Event_Id_06 // Security State event
#define AP_EVT_START_PERIODIC_CLOCK Event_Id_07 // Start the periodic
#define AP_EVT_BUTTON_SELECT Event_Id_24 // SELECT Button Press
#define AP_EVT_BUTTON_UP Event_Id_25 // UP Button Press
#define AP_EVT_BUTTON_DOWN Event_Id_26 // DOWN Button Press
#define AP_EVT_BUTTON_LEFT Event_Id_27 // LEFT Button Press
#define AP_EVT_BUTTON_RIGHT Event_Id_28 // RIGHT Button Press
#define AP_ERROR Event_Id_29 // Error
Similar to the semaphore approach, the application can pend on events, allowing execution of the task to
block until the event occurs. See the code snippet from the simple_ap below.
Using the andFlags and orFlags of the event module, the user can configure the pend call to wait until a
specific combination of events occurs. When a certain event occurs, the application can post the event,
such as the below example from simple_ap.
Event_post(apEvent, AP_EVT_BUTTON_LEFT);
Further documentation on the event module can be found in the TI-RTOS kernel documentation, located
at $TI_RTOS_INSTALL$/docs.
4.3.3 Callbacks
The application code also includes various callbacks to protocol stack layers, profiles, and RTOS modules.
To ensure thread safety, processing must be minimized in the actual callback and the bulk of the
processing should occur in the application context. Two functions are defined per callback (consider the
GAPRole state change callback):
NOTE: No blocking RTOS function calls or protocol stack APIs should be performed in a callback
function. Such function calls may result in an abort or undefined behavior. Always perform
protocol stack and RTOS blocking calls from the application task context.
• The actual callback: This function is called in the context of the calling task or module (for example,
the GAPRole task). To minimize processing in the calling context, this function should enqueue an
event to the queue of the application for processing.
static void SimpleBLEPeripheral_stateChangeCB(gaprole_States_t newState)
{
SimpleBLEPeripheral_enqueueMsg(SBP_STATE_CHANGE_EVT, newState);
}
• The function to process in the application context: When the application wakes up due to the
enqueue from the callback, this function is called when the event is popped from the application queue
and processed.
static void SimpleBLEPeripheral_processStateChangeEvt(gaprole_States_t newState)
{
...
}
This section describes the functionality of the Bluetooth low energy protocol stack and provides a list of
APIs to interface with the protocol stack. The stack project and its associated files serve to implement the
Bluetooth low energy protocol stack task. This is the highest priority task in the system and it implements
the Bluetooth low energy protocol stack as shown in Figure 1-1.
Most of the Bluetooth low energy protocol stack is object code in a single library file (TI does not provide
the protocol stack source code as a matter of policy). A developer must understand the functionality of the
various protocol stack layers and how they interact with the application and profiles. This section explains
these layers.
Based on the role for which the device is configured, Figure 5-1 shows the states of the device. The
following describes these states.
• Standby: The device is in the initial idle state upon reset.
• Advertiser: The device is advertising with specific data letting any initiating devices know that it is a
connectable device (this advertisement contains the device address and can contain some additional
data such as the device name).
• Scanner: When receiving the advertisement, the scanning device sends a scan request to the
advertiser. The advertiser responds with a scan response. This process is called device discovery. The
scanning device is aware of the advertising device and can initiate a connection with it.
• Initiator: When initiating, the initator must specify a peer device address to which to connect. If an
68 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Generic Access Profile (GAP)
advertisement is received matching that address of the peer device, the initiating device then sends
out a request to establish a connection (link) with the advertising device with the connection
parameters described in Section 5.1.1.
• Slave/Master: When a connection is formed, the device functions as a slave if the advertiser and a
master if the initiator.
Different applications may require different connection intervals. As described in Section 5.1.3, these
requirements affect the power consumption of the device. For more detailed information on power
consumption, see Measuring Bluetooth Smart Power Consumption Application Report (SWRA478).
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 69
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Generic Access Profile (GAP) www.ti.com
• Slave Latency – This parameter gives the slave (peripheral) device the option of skipping a number of
connection events. This ability gives the peripheral device some flexibility. If the peripheral does not
have any data to send, it can skip connection events, stay asleep, and save power. The peripheral
device selects whether to wake or not on a per connection event basis. The peripheral can skip
connection events but must not skip more than allowed by the slave latency parameter or the
connection fails. See Figure 5-3 for more details.
• Supervision Time-out – This time-out is the maximum amount of time between two successful
connection events. If this time passes without a successful connection event, the device terminates the
connection and returns to an unconnected state. This parameter value is represented in units of 10 ms.
The supervision time-out value can range from a minimum of 10 (100 ms) to 3200 (32.0 s). The time-
out must be larger than the effective connection interval (see Section 5.1.2 for more details).
70 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Generic Access Profile (GAP)
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 71
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Generic Access Profile (GAP) www.ti.com
Six seconds after a connection is established, the GAP layer automatically sends a connection parameter
update. See Section 5.2.1 for an explanation of how the parameters are configured, and Section B.2 for a
more detailed description of these parameters. This action can be disabled by setting
DEFAULT_ENABLE_UPDATE_REQUEST to FALSE.
Access the GAP layer through direct calls or through the GAPRole task as described in Section 5.2. Use
the GAPRole task rather than direct calls when possible. Section 5.1.8 describes the functions and
parameters that are not handled or configured through the GAPRole task and must be modified directly
through the GAP layer.
GAP_SetParamValue(TGAP_LIM_DISC_ADV_INT_MIN, advInt);
GAP_SetParamValue(TGAP_LIM_DISC_ADV_INT_MAX, advInt);
GAP_SetParamValue(TGAP_GEN_DISC_ADV_INT_MIN, advInt);
GAP_SetParamValue(TGAP_GEN_DISC_ADV_INT_MAX, advInt);
}
The above code sets the advertising interval for limited and general advertising modes. By default, the
peripheral advertises in general discoverable mode. To use limited discoverable mode, the corresponding
fields inside the advertising data packet should be changed by defining
DEFAULT_DISCOVERABLE_MODE to GAP_ADTYPE_FLAGS_LIMITED.
72 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com GAPRole Task
uint16_t advertOffTime = 0;
2. Initialize the GAPRole task and pass application callback functions to GAPRole (see Section B.3). This
should also occur in the application initialization function.
// Start the Device
VOID GAPRole_StartDevice(&SimpleBLEPeripheral_gapRoleCBs);
3. Send GAPRole commands from the application. Figure 5-5 is an example of the application using
GAPRole_TerminateConnection(), assuming a connection has already been established. Green
corresponds to the app context and red corresponds to the protocol stack context.
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 73
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
GAPRole Task www.ti.com
simple_peripheral.c:
Application calls
GAPRole function
GAPRole_TerminateConnection();
NOTE: The return value only indicates whether the attempt to terminate the connection initiated
successfully. The actual termination of connection event is returned asynchronously and is
passed to the application through a callback. The API in Section B.3 lists the return
parameters for each command and associated callback function events.
4. The GAPRole task processes most of the GAP-related events passed to it from the Bluetooth low
energy protocol stack. The GAPRole task also forwards some events to the application. When a link is
terminated, the GAPRole automatically restarts advertising.Figure 5-6 is an example tracing the
GAP_LINK_TERMINATED_EVENT from the Bluetooth low energy protocol stack to the application.
Green corresponds to the app context. Orange corresponds to the GAPRole context. Red corresponds
to the protocol stack context.
74 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com GAPRole Task
peripheral.c:
GAPRole notifies the // Notify the application with the new state change
application of the if (pGapRoles_AppCGs && pGapRoles_AppCGs->pfnStateChange)
event through the {
callback function, pGapRoles_AppCGs->pfnStateChange(gapRole_state);
posting semaphore to }
application and event simple_peripheral.c:
to queue static void SimpleBLEPeripheral_stateChangeCB(gaprole_States_t
newState)
{
SimpleBLEPeripheral_enqueueMsg(SBP_STATE_CHANGE_EVT,
newState);
}
simple_peripheral.c:
static void SimpleBLEPeripheral_processAppMsg(sbpEvt_t *pMsg)
{
switch (pMsg->hdr.event)
{
case SBP_STATE_CHANGE_EVT:
Application wakes up
SimpleBLEPeripheral_processStateChangeEvt((gaprole_States_t)
to process sempahore
pMsg->hdr.state);
and event from queue. «
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 75
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
GAPRole Task www.ti.com
2. Start the GAPRole task. This involves passing function pointers to application callback function to the
central GAPRole. See Section C.3 for a detailed description of the callbacks. This should also occur in
the application initialization function.
VOID GAPCentralRole_StartDevice(&SimpleBLECentral_roleCB);
3. Send GAPRole commands from the application. Figure 5-7 is an example of the application using
GAPCentralRole_StartDiscovery(). Green corresponds to the app context and red corresponds to the
Bluetooth low energy protocol stack context.
central.c:
bStatus_t GAPCentralRole_StartDiscovery(uint8_t mode, uint8_t
activeScan, uint8_t whiteList)
{
gapDevDiscReq_t params;
GAPRole function calls
GAP function to send params.taskID = Call_getLocalMsgEntityId(
ICALL_SERVICE_CLASS_BLE_MSG, selfEntity);
command to BLE
params.mode = mode;
Stack
params.activeScan = activeScan;
params.whiteList = whiteList;
ICALL
return GAP_DeviceDiscoveryRequest(¶ms);
}
76 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com GAPRole Task
NOTE: The return value from the protocol stack indicates only whether or not the attempt to perform
device discovery was initiated. The actual device discovered is returned asynchronously as a
GAP event forwarded through the central GAPRole callbacks as described below.
Section C.1 lists the return parameters for each command and associated callback events.
4. The GAPRole task performs some processing on the GAP events it receives from the protocol stack.
The task also forwards some events to the application. Figure 5-8 is an example tracing the
GAP_DEVICE_DISCOVERY_EVENT, prompted by the command from step 3, from the protocol stack
to the application. Green corresponds to the app context. Orange corresponds to the GAPRole context.
Red corresponds to the protocol stack context.
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 77
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
GAPRole Task www.ti.com
central.c:
static uint8_t gapCentralRole_ProcessGAPMsg(gapEventHdr_t
GAPRole receives the *pMsg)
message and sends {
the // Pass event to app
gapCentralRoleEvent if (pGapCentralRoleCB && pGapCentralRoleCB->eventCB)
to the application {
return (pGapCentralRoleCB->eventCB((gapCentralRoleEvent_t
callback function
*)pMsg));
...
simple_central.c:
static void SimpleBLECentral_processAppMsg(sbcEvt_t *pMsg)
{
switch (pMsg->hdr.event)
{
case SBC_STATE_CHANGE_EVT:
SimpleBLECentral_processStackMsg((ICall_Hdr *)pMsg->pData);
«
The GATT roles of client and server are independent from the GAP roles of peripheral and central. A
peripheral can be either a GATT client or a GATT server, and a central can be either a GATT client or a
GATT server. A peripheral can act as both a GATT client and a GATT server. For a hands-on review of
GATT services and characteristics, see SimpleLink Academy Module 1.
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 79
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Generic Attribute Profile (GATT) www.ti.com
80 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Generic Attribute Profile (GATT)
• SIMPLEPROFILE_CHAR4 – a 1-byte value that cannot be directly read or written from a GATT client
device (This value is notifiable: This value can be configured for notifications to be sent to a GATT
client device.)
• SIMPLEPROFILE_CHAR5 – a 5-byte value that can be read (but not written) from a GATT client
device
The following is a line-by-line description of the simple profile attribute table, referenced by the following
handle.
• 0x001F is the simple_gatt_profile service declaration. This declaration has a UUID of 0x2800
(Bluetooth-defined GATT_PRIMARY_SERVICE_UUID). The value of this declaration is the UUID of
the simple_gatt_profile (custom-defined).
• 0x0020 is the SimpleProfileChar1 characteristic declaration. This declaration can be thought of as a
pointer to the SimpleProfileChar1 value. The declaration has a UUID of 0x2803 (Bluetooth-defined
GATT_CHARACTER_UUID). The value of the declaration characteristic, as well as all other
characteristic declarations, is a 5-byte value explained here (from MSB to LSB):
– Byte 0: the properties of the SimpleProfileChar1 as defined in the Bluetooth specification (The
following are some of the relevant properties.)
• 0x02: permits reads of the characteristic value
• 0x04: permits writes of the characteristic value (without a response)
• 0x08: permits writes of the characteristic value (with a response)
• 0x10: permits of notifications of the characteristic value (without acknowledgment)
• 0x20: permits notifications of the characteristic value (with acknowledgment)
The value of 0x0A means the characteristic is readable (0x02) and writeable (0x08).
– Bytes 1–2: the byte-reversed handle where the SimpleProfileChar1 value is (handle 0x0021)
– Bytes 3–4: the UUID of the SimpleProfileChar1 value (custom-defined 0xFFF1)
• 0x0021 is the SimpleProfileChar1 value. This value has a UUID of 0xFFF1 (custom-defined). This
value is the actual payload data of the characteristic. As indicated by its characteristic declaration
(handle 0x0020), this value is readable and writeable.
• 0x0022 is the SimpleProfileChar1 user description. This description has a UUID of 0x2901 (Bluetooth-
defined). The value of this description is a user-readable string describing the characteristic.
• 0x0023 – 0x002F are attributes that follow the same structure as the simpleProfileChar1 described
previously with regard to the remaining four characteristics. The only different attribute, handle 0x002B,
is described as follows.
• 0x002B is the SimpleProfileChar4 client characteristic configuration. This configuration has a UUID of
0x2902 (Bluetooth-defined). By writing to this attribute, a GATT server can configure the
SimpleProfileChar4 for notifications (writing 0x0001) or indications (writing 0x0002). Writing 0x0000 to
this attribute disable notifications and indications.
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 81
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Generic Attribute Profile (GATT) www.ti.com
82 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Generic Attribute Profile (GATT)
NOTE: The example uses GATT_WriteCharValue(), which is triggered by a left key press in the
SimpleBLECentral application. Green corresponds to the app context and red corresponds to
the protocol stack context.
Application calls
simpleBLECentral.c:
GATT function
status = GATT_WriteCharValue(connHandle, &req,
selfEntity);
GATT function is
ICallBLEApi.c
translated into ATT bStatus_t GATT_WriteCharValue(uint16
function and sent to connHandle, attWriteReq_t *pReq, unit8, taskID)
stack task. {
return gattRequest(connHandle, (attMsg_t
*)pReq, taskId, ATT_WRITE_REQ);
ICALL }
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 83
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Generic Attribute Profile (GATT) www.ti.com
4. Receive and handle the response to the GATT client procedure in the application. In this example, the
application receives an ATT_WRITE_RSP event. See Section D.6 for a list of GATT commands and
their corresponding ATT events. Green corresponds to the app context and red corresponds to the
protocol stack context.
ICALL
simpleBLECentral.c:
if (ICall_fetchServiceMsg(&src, &dest, (void
Application task **)&pMsg) == ICALL_ERRnO_SUCCESS)
receives GATT {
message from BLE if ((src == ICALL_SERVICE_CLASS_BLE) && (dest ==
Stack selfEntity))
{
// Process inter-task message
SimpleBLECentral_processStackMsg((ICall_Hdr
*)pMsg);
...
SimpleBLECentral.c:
static void
SimpleBLECentral_processStackMsg(ICall_Hdr *pMsg)
{
switch (pMsg->event)
{
case GATT_MSG_EVENT:
SimpleBLECentral_processGATTMsg((gattMsgEvent_t
*)pMsg);
break;
...
static void
SimpleBLECentral_processGATTMsg(gattMsgEvent_t *pMsg)
Application processes
{
stack message to
...
handle the write else if ((pMsg->method == ATT_WRITE_RSP) ||
response ((pMsg->method == ATT_ERROR_RSP) &&
(pMsg-
>msg.errorRsp.reqOpcode == ATT_WRITE_REQ)))
{
...
else
{
// After a successful write, display the
value that was // written and increment
value
LCD_WRITE_STRING_VALUE("Write sent:",
charVal++, 10, LCD_PAGE2);
...
84 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Generic Attribute Profile (GATT)
NOTE: Even though the event sent to the application is an ATT event, it is sent as a GATT protocol
stack message (GATT_MSG_EVENT).
5. A GATT client may also receive asynchronous data from the GATT server as indications or
notifications other than receiving responses to its own commands. Registering to receive these ATT
notifications and indications is required as in Step 2. These notifications and indications are also be
sent as ATT events in GATT messages to the application and must be handled as described in
Section 5.3.2.
The design process involves creating GATT profiles that configure the GATTServApp module and use its
API to interface with the GATT layer. In this case of a GATT server, direct calls to GATT layer functions
are unnecessary. The application then interfaces with the profiles.
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 85
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Generic Attribute Profile (GATT) www.ti.com
#ifndef FEATURE_OAD_ONCHIP
SimpleProfile_AddService(GATT_ALL_SERVICES); // Simple GATT Profile
#endif //!FEATURE_OAD_ONCHIP
86 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Generic Attribute Profile (GATT)
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 87
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Generic Attribute Profile (GATT) www.ti.com
The type is set to the Bluetooth SIG-defined primary service UUID (0x2800). A GATT client must read this
attribute, so the permission is set to GATT_PERMIT_READ. The pValue is a pointer to the UUID of the
service, custom-defined as 0xFFF0.
// Simple Profile Service attribute
static CONST gattAttrType+t simpleProfileService = { ATT_BT_UUID_SIZE,
simpleProfileServUUID };
NOTE: An important distinction exists between these properties and the GATT permissions of the
characteristic value. These properties are visible to the GATT client stating the properties of
the characteristic value. The GATT permissions of the characteristic value affect its
functionality in the protocol stack. These properties must match that of the GATT
permissions of the characteristic value. Section 5.3.4.2.1.3 expands on this idea.
The type is set to the custom-defined simpleProfilechar1 UUID (0xFFF1). The properties of the
characteristic value in the attribut table must match the properties from the characteristic value
declaration. The pValue is a pointer to the location of the actual value, statically defined in the profile as
follows.
88 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Generic Attribute Profile (GATT)
// Characteristic 1 Value
static uint8 simpleProfileChar1 = 0;
The type is set to the Bluetooth SIG-defined client characteristic configuration UUID (0x2902) GATT
clients must read and write to this attribute so the GATT permissions are set to readable and writeable.
The pValue is a pointer to the location of the client characteristic configuration array, defined in the profile
as follows.
static gattCharCfg_t *simpleProfileChar4Config;
NOTE: Client characteristic configuration is represented as an array because this value must be
cached for each connection. The catching of the client characteristic configuration is
described in more detail in Section 5.3.4.2.2.
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 89
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Generic Attribute Profile (GATT) www.ti.com
return ( SUCCESS );
}
else
{
return ( bleAlreadyInRequestedMode );
}
}
The application must then define a callback of this type and pass it to the simple_gatt_profile with the
SimpleProfile_RegisterAppCBs() function. This occurs in simple_peripheral.c as follows.
// Simple GATT Profile Callbacks
#ifndef FEATURE_OAD_ONCHIP
static simpleProfileCBs_t SimpleBLEPeripheral_simpleProfileCBs =
{
SimpleBLEPeripheral_charValueChangeCB // Characteristic value change callback
};
#endif //!FEATURE_OAD_ONCHIP
...
// Register callback with SimpleGATTprofile
SimpleProfile_RegisterAppCBs(&SimpleBLEPeripheral_simpleProfileCBs);
See Section 5.3.4.2.4 for further information on how this callback is used.
90 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Generic Attribute Profile (GATT)
simpleGATTProfile.c
static bStatus_t simpleProfile_ReadAttrCB(......)
Profile copies the value
{
of the characteristic into
the data pointer and if ( pAttr->type.len == ATT_BT_UUID_SIZE )
returns this to {
GATTServApp // 16-bit UUID
uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr-
>type.uuid[1]);
switch (uuid )
{
case SIMPLEPROFILE_CHAR1_UUID:
*pLen = 1;
pValue[0] = *pAttr->pValue;
break;
...
GATTServApp returns
the attribute value to the
stack to be returned Library Code
over-the-air to the GATT
Client
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 91
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Generic Attribute Profile (GATT) www.ti.com
NOTE: The processing is in the context of the protocol stack. If any intensive profile-related
processing that must be done in the case of an attribute read, this should be split up and
done in the context of the Application task. See the following write request for more
information.
gattservapp.c:
GATTServApp receives // Find the owner of the attribute
GATT_MSG_EVENT,
pAttr = GATT_FindHandle( handle, &service );
processes it to call
if ( pAttr != NULL )
profile callback.
{
// Find out the owner's callback functions
pfnGATTWriteAttrCB_t pfnCB =
gattServApp_FindWriteAttrCB( service);
if ( pfnCB != NULL )
{
//Try to write the new value
status = (*pfnCB)( connHandle, pAttr,
pValue, len, offset, method);
...
92 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Generic Attribute Profile (GATT)
simpleGATTProfile.c
static bStatus_t
simpleProfile_WriteAttrCB(......)
{
if ( pAttr->type.len == ATT_BT_UUID_SIZE )
{
Profile stores the value uint16 uuid = BUILD_UINT16( pAttr-
from the characteristic >type.uuid[0], pAttr->type.uuid[1]_;
write as the new switch ( uuid )
characteristic value. {
// Write the value
if ( status == SUCCESS )
{
uint8 *pCurValue = (uint8 *)pAttr-
>pValue;
*pCurValue = pValue[0];
...
notifyApp = SIMPLEPROFILE_CHAR3;
simpleBLEPeripheral.c
static void
I SimpleBLEPeripheral_charValueChangeCB(uint8_t
Status is returned paramID)
C
through {
A GATTServApp to
L
stack to send
over-the-air to SimpleBLEPeripheral_enqueueMsg(SBP_CHAR_CHANGE_E
L GATT Client VT, paramID);
}
Library Code
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 93
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Generic Attribute Profile (GATT) www.ti.com
simpleBLEPeripheral.c
static void
SimpleBLEPeripheral_processAppMsg(sbpEvt_t
*pMsg)
{
switch (pMsg->event)
{
case SBP_STATE_CHANGE_EVT:
SimpleBLEPeripheral_processStateChangeEvt
((gaprole_States_t)pMsg->status);
Application wakes up to do ...
additional write-related static void
processing SimpleBLEPeripheral_processCharValueChangeEvt(un
it8+t paramID)
{
switch (paramID)
{
case
SIMPLEPROFILE_CHAR3:SimpleProfile_GetParameter(S
IMPLEPROFILE_CHAR3, &newValue);
LCD_WRITE_STRING_VALUE("Char 3:",
(uint16_t)newValue, 10, LCD_PAGE4)l
NOTE: Minimizing the processing in protocol stack context is important. In this example, additional
processing beyond storing the attribute write value in the profile (that is, writing to the LCD)
occurs in the application context by enqueuing a message in the queue of the application.
94 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Generic Attribute Profile (GATT)
The code for this function is displayed in the following code snippet (from simple_gatt_profile.c). Besides
setting the value of the static simpleProfileChar4, this function also calls GATTServApp_ProcessCharCfg
because it has notify properties. This action forces GATTServApp to check if notifications have been
enabled by the GATT Client. If so, the GATTServApp sends a notification of this attribute to the GATT
Client.
bStatus_t SimpleProfile_SetParameter( uint8 param, uint8 len, void *value )
{
bStatus_t ret = SUCCESS
switch ( param )
{
case SIMPLEPROFILE_CHAR4:
if ( len == sizeof ( uint8 ) )
{
simpleProfileChar4 = *((uint8*)value);
NOTE: If the return value of the notification or indication is SUCCESS (0x00), the stack freed the
memory.
3. Use GATT_bm_free() to free the memory if the return value is something other than SUCCESS (for
example, blePending).
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 95
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Generic Attribute Profile (GATT) www.ti.com
if ( status != SUCCESS )
{
GATT_bm_free( (gattMsg_t *)¬i, ATT_HANDLE_VALUE_NOTI );
}
}
else
{
status = bleNoResources;
}
For other GATT procedures, take similar steps as noted in the API in Appendix D
96 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Generic Attribute Profile (GATT)
No more ATT requests or indications can be sent wirelessly during the connection. The application
may want to terminate the connection due to this violation. As an example in simple_peripheral, the
LCD is updated.
else if (pMsg->method == ATT_FLOW_CTRL_VIOLATED_EVENT)
{
// ATT request-response or indication-confirmation flow control is
// violated. All subsequent ATT requests or indications will be dropped.
// The app is informed in case it wants to drop the connection.
5.3.7.1 Authentication
Characteristics that require authentication cannot be accessed until the client has gone through an
authenticated pairing method. This verification is performed within the stack, with no processing required
by the application. The only requirement is for the characteristic to be registered properly with the GATT
server.
For example, characteristic 5 of the simple_gatt_profile allows on authenticated reads.
// Characteristic Value 5
{
{ ATT_BT_UUID_SIZE, simpleProfilechar5UUID },
GATT_PERMIT_AUTHEN_READ,
0,
simpleProfileChar5
},
When an un-authenticated client attempts to read this value, the GATT server automatically rejects it with
ERROR_INSUFFICIENT_AUTHEN (0x41), without invoking the simpleProfile_ReadAttrCB(). See an
example of this in Figure 5-15.
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 97
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Generic Attribute Profile (GATT) www.ti.com
After the client has successfully authenticated, read/write requests are forwarded to the profiles read/write
callback. See the code below for a simple_gatt_profile example:
case SIMPLEPROFILE_CHAR5_UUID:
*pLen = SIMPLEPROFILE_CHAR5_LEN;
VOID memcpy( pValue, pAttr->pValue, SIMPLEPROFILE_CHAR5_LEN );
break;
5.3.7.2 Authorization
Authorization is a layer of security provided in addition to what BLE already implements. Because
applications are required to define their own requirements for authorization, the stack forwards read/write
requests on these characteristics to the application layer of the profile.
For the profile to register for authorization information from the GATT server, it must define an
authorization callback with the stack. The simple_gatt_profile does not do this by default, but below is an
example of how it could be modified to do this.
1. Register profile level authorization callback.
CONST gattServiceCBs_t simpleProfileCBs =
{
simpleProfile_ReadAttrCB, // Read callback function pointer
simpleProfile_WriteAttrCB, // Write callback function pointer
simpleProfile_authorizationCB // Authorization callback function pointer
};
2. Implement authorization callback code.
static bStatus_t simpleProfile_authorizationCB( uint16 connHandle,
gattAttribute_t *pAttr,
uint8 opcode )
{
//This is just an example implementation, normal use cases would require
//more complex logic to determine that the device is authorized
if(clientIsAuthorized)
return SUCCESS;
else
return ATT_ERR_INSUFFICIENT_AUTHOR;
}
The authorization callback executes in the stack context; thus, intensive processing should not be
performed in this function. The implementation is left up to the developer; the above callback should be
treated as a shell. The return value should be either SUCCESS if the client is authorized to access the
characteristic, or ATT_ERR_INSUFFICIENT_AUTHOR if they have not yet obtained proper authorization.
Authorization requires the connection to be authenticated beforehand, or
ATT_ERR_INSUFFICIENT_AUTHEN will be sent as an error response.
98 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com GAP Bond Manager and LE Secure Connections
NOTE: If a characteristic that requires authorization is registered with the GATT server, but no
application level authorization callback is defined, the stack will return ATT_ERR_UNLIKELY.
Because this error can be cryptic, TI recommends using an authorization callback.
5.4.1 Overview
The GAP Bond Manager is a configurable module that offloads most of the security mechanisms from the
application. Table 5-1 lists the terminology.
NOTE: Performing all of these steps is unnecessary. For example, two devices may choose to pair
but not bond.
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 99
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
GAP Bond Manager and LE Secure Connections www.ti.com
The selection of the association model and whether or not pairing will succeed is based upon the following
parameters (all tables from Section 2.3.5.1 of Vol 3, Part h of the Bluetooth 4.2 Spec). The GAPBondMgr
parameters, as they map to the table parameters below are listed here. For more information on these
parameters, see the GAPBondMgr API.
• GAPBOND_LOCAL_OOB_SC_ENABLED: OOB Set / Not Set
• GAPBOND_MITM_PROTECTION: MITM Set / Not Set
• GAPBOND_IO_CAPABILITIES: IO Capabilities
• GAPBOND_SECURE_CONNECTION: secure connections supported / not supported
Beyond what the spec defines, this parameter also affects whether or not pairing succeeds, as
described in the GAPBondMgr API.
If both devices support secure connections, use Figure 5-16 to decide upon the next step.
If at least one device does not support secure connections, use Figure 5-17 to decide upon the next step.
If, based on one of the previous tables, IO capabilities are to be used to determine the association model,
use Figure 5-18.
100 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com GAP Bond Manager and LE Secure Connections
102 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com GAP Bond Manager and LE Secure Connections
GAPBondMgr handles
GAP_AUTHENTICATIO gapbondmgr.c:
N_COMPLETE stack uint16 GAPBondMgr_ProcessEvent( uint8 task_id, uint16 events )
message and calls {
application callback if ( events & GAP_BOND_SYNC_CC_EVT )
{
if ( gapBondMgr_SyncCharCfg( pAuthEvt->connectionHandle ) )
{
if ( pGapBondCB && pGapBondCB->pairStateCB )
{
pGapBondCB->pairStateCB( pAuthEvt->connectionHandle,
GAPBOND_PAIRING_STATE_COMPLETE, SUCCESS );
...
security_example_central.c:
static void security_examples_central_pairStateCB(uint16_t connHandle,
uint8_t state, uint8_t status)
{
Callback stores state uint8_t *pData;
and status, sets event, if ((pData = ICall_malloc(sizeof(uint8_t))))
and posts semaphore {
to wake up application *pData = status;
security_examples_central_enqueueMsg(SEC_PAIRING_STATE_EVT,
state, pData);
}
security_examples_central.c:
static void security_examples_central_processAppMsg(secEvt_t *pMsg)
{
switch (pMsg->hdr.event)
{
case SEC_PAIRING_STATE_EVT:
{
security_examples_central_processPairState(pMsg->hdr.state,
*pMsg->pData);
«
static void security_examples_central_processPairState(uint8_t state,
Application wakes up uint8_t status)
{
to process event
else if (state == GAPBOND_PAIRING_STATE_COMPLETE)
{
if (status == SUCCESS)
{
DISPLAY_WRITE_STRING("Pairing success", LCD_PAGE2);
}
else
{
DISPLAY_WRITE_STRING_VALUE("Pairing fail: %d", status,
LCD_PAGE2);
}
}
Figure 5-19. Flow Diagram Example
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 103
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
GAP Bond Manager and LE Secure Connections www.ti.com
NOTE: The code snippets here are not complete functioning examples, and are only intended for
illustration purposes. See the security_examples for a complete example.
Figure 5-20 describes the interaction between the GAPBondMgr and the application for Just Works
pairing. As shown, the application receives a GAPBOND_PAIRING_STATE_STARTED event once the
pairing request has been sent, and a GAPBOND_PAIRING_STATE_COMPLETE event once the pairing
process has completed. At this time, the link is encrypted.
104 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com GAP Bond Manager and LE Secure Connections
GAP_LINK_ESTABLISHED_EVENT
GAPBondMgr_LinkEst()
GAP_Authenticate()
Pairing Req
GAPBOND_PAIRING_
STATE_STARTED
Encryption
Req / Rsp
GAP_AUTHENTICATION
_COMPLETE_EVENT
GAPBOND_PAIRING_
STATE_COMPLETE
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 105
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
GAP Bond Manager and LE Secure Connections www.ti.com
if ((pData = ICall_malloc(sizeof(gapPasskeyNeededEvent_t))))
{
memcpy(pData->deviceAddr, deviceAddr, B_ADDR_LEN);
pData->connectionHandle = connHandle;
pData->uiInputs = uiInputs;
pData->uiOutputs = uiOutputs;
Depending on what the uiInputs and uiOutputs returned from the GAPBondMgr, the passcode must either
be displayed or entered. The passcode is then sent to the GAPBondMgr using
GAPBondMgr_PasscodeRsp(), so that pairing can continue. In this case, the password is statically set to
111111. In a real product, the password will likely be randomly generated, and the device must expose a
way for the user to enter the passcode, then send it to the GAPBondMgr using
GAPBondMgr_PasscodeRsp(). There is an example of this in the security_examples projects. The
complete interaction between the GAPBondMgr and the application is shown in Figure 5-21.
106 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com GAP Bond Manager and LE Secure Connections
GAP_LINK_ESTABLISHED_EVENT
GAPBondMgr_LinkEst()
GAP_Authenticate()
Pairing Req
GAPBOND_PAIRING_
STATE_STARTED
GAP_PASSKEY_NEEDED_
EVENT
Passcode Callback
Enter /
Display
Passcode
GAPBondMgr_PasscodeRsp()
GAP_PasscodeUpdate()
Encryption
Req / Rsp
GAP_AUTHENTICATION
_COMPLETE_EVENT
GAPBOND_PAIRING_
STATE_COMPLETE
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 107
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
GAP Bond Manager and LE Secure Connections www.ti.com
In this case, the third parameter of GAPBondMgr_PasscodeRsp, which usually accepts a passcode, is
overloaded to send TRUE to the stack to indicate that the codes match and to continue with pairing.
108 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com GAP Bond Manager and LE Secure Connections
GAP_LINK_ESTABLISHED_EVENT
GAPBondMgr_LinkEst()
GAP_Authenticate()
Pairing Req
GAPBOND_PAIRING_
STATE_STARTED
GAP_PASSKEY_NEEDED_
EVENT
Passcode Callback
Display
Code
Codes
match
GAPBondMgr_PasscodeRsp()
GAP_PasscodeUpdate()
Encryption
Req / Rsp
GAP_AUTHENTICATION
_COMPLETE_EVENT
GAPBOND_PAIRING_
STATE_COMPLETE
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 109
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
GAP Bond Manager and LE Secure Connections www.ti.com
With bonding enabled, the GAPBondMgr stores the long-term key transferred during the pairing process to
SNV. See Section 5.4.4.6 for more information. After this is completed, the application is notified through
the GAPBOND_PAIRING_STATE_COMPLETE event. GAPBOND_PAIRING_STATE_COMPLETE is only
passed to the application pair state callback when initially connecting, pairing, and bonding. For future
connections to a bonded device, the security keys are loaded from flash, thus skipping the pairing
process. In this case, only PAIRING_STATE_BONDED is passed to the application pair state callback.
This is illustrated in Figure 5-23.
110 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com GAP Bond Manager and LE Secure Connections
GAP_LINK_ESTABLISHED_EVENT
GAPBondMgr_LinkEst()
GAP_Authenticate()
Pairing Req
GAPBOND_PAIRING_
STATE_STARTED
This section will vary depending on the pairing type. See above examples for more information.
Encryption
Req / Rsp
GAP_AUTHENTICATION
_COMPLETE_EVENT
GAPBOND_PAIRING_
STATE_COMPLETE
GAP_LINK_ESTABLISHED_EVENT
GAPBondMgr_LinkEst()
GAP_Bond()
Encryption
Req / Rsp
GAP_BOND_COMPLETE
_EVENT
GAPBOND_PAIRING_
STATE_BONDED
5.4.5.1 Summary
This BLE–Stack SDK supports the privacy feature that reduces the ability to track an LE device over a
period of time, by changing the Bluetooth device address on a frequent basis. LE Privacy 1.2 extends
privacy to the controller by allowing the controller to both resolve peer and generate local resolvable
private addresses (RPAs). It is used during connection mode and connection procedures. Table 5-2 lists
the definition of terms related to the privacy feature.
112 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com GAP Bond Manager and LE Secure Connections
If the controller is unable to resolve the peer RPAs, or the white list takes no actions for the incoming
address, the address is still passed to the host. If the local device or peer device wishes, it can initiate a
bonding sequence to exchange IRKs as well as device identity addresses. If these are exchanged, the
host can use those parameters to update the controller’s resolving list, and even update the white list, so
that the controller can automatically form a connection with the peer during a future connection attempt.
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 113
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Logical Link Control and Adaptation Layer Protocol (L2CAP) www.ti.com
It can be verified with a sniffer that the address changes when advertising. The default timeout value
between private (resolvable) address changes is 15 minutes. This can be modified by the
GAP_SetParamValue() API:
114 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Logical Link Control and Adaptation Layer Protocol (L2CAP)
NOTE: The actual size is limited by the amount of memory available on the specific device being
implemented. L2CAP also permits per-channel flow control and retransmission.
Term Description
L2CAP channel The logical connection between two endpoints in peer devices,
characterized by their Channel Identifiers (CIDs)
SDU or L2CAP SDU Service Data Unit: a packet of data that L2CAP exchanges with
the upper layer and transports transparently over an L2CAP
channel using the procedures specified in this document
PDU or L2CAP PDU Protocol Data Unit: a packet of data containing L2CAP protocol
information fields, control information, and/or upper layer
information data
Maximum Transmission Unit (MTU) The maximum size of payload data, in octets, that the upper
layer entity can accept (that is, the MTU corresponds to the
maximum SDU size).
Maximum PDU Payload Size (MPS) The maximum size of payload data in octets that the L2CAP
layer entity can accept (that is, the MPS corresponds to the
maximum PDU payload size).
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 115
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Logical Link Control and Adaptation Layer Protocol (L2CAP) www.ti.com
The size of the L2CAP PDU also defines the size of the Attribute Protocol Maximum Transmission Unit
(ATT_MTU). By default, LE devices assume the size of the L2CAP PDU is 27 bytes, which corresponds to
the maximum size of the LE packet that can transmit in a single connection event packet. In this case, the
L2CAP protocol header is 4 bytes, resulting in a default size for ATT_MTU of 23.
NOTE: When using the LE Data Length Extension feature, the length of the LE packet can be up to
251 bytes. See Section 5.6.
116 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Logical Link Control and Adaptation Layer Protocol (L2CAP)
Increasing the size of the ATT_MTU increases the amount of data that can be sent in a single ATT
packet. The longest attribute that can be sent in a single packet is (ATT_MTU-1) bytes. Procedures, such
as notifications, have additional length restrictions. If an attribute value has a length of 100 bytes, a read
of this entire attribute requires a read request to obtain the first (ATT_MTU-1) bytes, followed by multiple
read blob request to obtain the subsequent (ATT_MTU-1) bytes. To transfer the entire 100 bytes of
payload data with the default ATT_MTU = 23 bytes, five request or response procedures are required,
each returning 22 bytes. If the exchange MTU procedure was performed and an ATT_MTU was
configured to 101 bytes (or greater), the entire 100 bytes could be read in a single read request or
response procedure.
NOTE: Due to memory and processing limitations, not all Bluetooth low energy systems support
larger MTU sizes. Know the capabilities of expected peer devices when defining the behavior
of the system. If the capability of peer devices is unknown, design the system to work with
the default 27-byte L2CAP PDU/23-byte ATT_MTU size. For example, sending notifications
with a length greater than 20 bytes (ATT_MTU-3) bytes results in truncation of data on
devices that do not support larger MTU sizes.
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 117
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
LE Data Length Extension www.ti.com
Figure 5-27. Sample Connection and Data Exchange Between a Master and Slave Device Using a L2CAP
Connection-Oriented Channel in LE Credit Based Flow Control Mode
For more information on these L2CAP APIs, refer to the L2CAP API in Appendix G.
5.6.1 Summary
The data length extension feature allows the LE controller to send data channel packet data units (PDUs)
with payloads of up to 251 bytes of application data, while in the connected state. Furthermore, a new
PDU size can be negotiated by either side at any time during a connection. Previously, the controller’s
largest data channel payload was 27 bytes. This increases the data rate by around 2.5×, compared to
Bluetooth Core Specification version 4.0 and 4.1 devices (if both devices support extended packet length
and are configured properly).
118 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com LE Data Length Extension
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 119
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
LE Data Length Extension www.ti.com
Once a connection is formed, the controller handles negotiating a packet size with the peer device. If both
devices are set up to use data length extension, a throughput increase is observed.
120 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com HCI
5.7 HCI
The host controller interface (HCI) layer is a thin layer which transports commands and events between
the host and controller elements of the Bluetooth protocol stack. In a pure network processor application
(that is, the host_test project), the HCI layer is implemented through a transport protocol such as SPI or
UART. In embedded wireless MCU projects such as simple_peripheral or the simple_np project, the HCI
layer is implemented through function calls and callbacks within the wireless MCU. All of the commands
and events discussed, such as ATT, GAP, and so forth, pass from the upper layers of the protocol stack
through the HCI layer to the controller. Likewise, the controller sends received data and events to the host
and upper layers through HCI.
As well as standard Bluetooth LE HCI commands, a number of HCI extension vendor-specific commands
are available which extend some of the functionality of the controller for use by the application. See
Appendix H for a description of available HCI and HCI extension commands.
The TI BLE-Stack supports a network processor configuration (host_test) that allows an application to
running on an external MCU to interface to the TI BLE-Stack. The network processor can accept all LE
HCI commands; however, because the BLE host and controller both reside on the wireless MCU, some
HCI commands will have their corresponding events consumed by the TI BLE host. Thus, it is not possible
to interface an external, off-chip Bluetooth host to the CC2640 wireless MCU using standard HCI LE
commands. Network processor configurations should use both HCI and TI vendor-specific HCI commands
to implement an external Bluetooth application.
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 121
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
HCI www.ti.com
2. Find mapping to BLE stack command. Using the table in Appendix H, this command maps to
HCI_ReadRssiCmd().
3. Using the API from Step 1, fill in the parameters and call the command from somewhere in the
application. This specific command should be called after a connection is formed. There is only
command parameter here: a 2-byte connection handle. In the case of this example, the connection
handle is 0x0000:
HCI_ReadRssiCmd(0x0000);
122 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com HCI
2. This command returns a Command Complete event, so add this as a case in the processing of
HCI_GAP_EVENT_EVENT:
static uint8_t SimpleBLEPeripheral_processStackMsg(ICall_Hdr *pMsg)
{
uint8_t safeToDealloc = TRUE;
switch (pMsg->event)
{
case HCI_GAP_EVENT_EVENT:
{
// Process HCI message
switch(pMsg->status)
{
// Process HCI Command Complete Event
case HCI_COMMAND_COMPLETE_EVENT_CODE:
{
// Parse Command Complete Event for opcode and status
hciEvt_CmdComplete_t* command_complete = (hciEvt_CmdComplete_t*)pMsg;
uint8_t status = command_complete->pReturnParam[0];
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 123
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
HCI www.ti.com
First, the status of the stack message is checked to see what type of HCI event it is. In this case, it is an
HCI_COMMAND_COMPLETE_EVENT_CODE (0x0E). Then the event returned from the stack as a
message (pMsg) is cast to an (hciEvt_CmdComplete_t*), which is defined as:
// Command Complete Event
typedef struct
{
osal_event_hdr_t hdr;
uint8 numHciCmdPkt;
uint16 cmdOpcode;
uint8 *pReturnParam;
} hciEvt_CmdComplete_t;
Next, the cmdOpcode is checked and it is found that it matches HCI_READ_RSSI (0x1405). Then the
status of the event is checked. The core spec API from above states that the first byte of the return
parameters is the Status.
Then, check to see if this RSSI value is for the correct handle. The core spec API states that the second
and third bytes of the return parameters are the Handle.
Finally, the RSSI value is stored. The core spec API states that the fourth byte of the return parameter is
the RSSI.
124 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com HCI
2. The BLE Stack function that implements this command is found under the Command column:
HCI_EXT_PacketErrorRateCmd.
3. Using the API from Step 1, fill in the parameters and call the command from somewhere in the
application. The first parameter is a 2-byte connHandle, which is 0x00 for this example. The second
parameter is a 1-byte command, which is 0x01, to read the counters. Therefore, use:
HCI_EXT_PacketErrorRateCmd( 0, HCI_EXT_PER_READ );
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 125
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
HCI www.ti.com
126 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com HCI
2. As stated in the Events Genereated section of the command API, this command returns a Command
Complete event; thus add this as a case in the processing of HCI_GAP_EVENT_EVENT:
static uint8_t SimpleBLEPeripheral_processStackMsg(ICall_Hdr *pMsg)
{
uint8_t safeToDealloc = TRUE;
switch (pMsg->event)
{
case HCI_GAP_EVENT_EVENT:
{
// Process HCI message
switch(pMsg->status)
{
// Process HCI Vendor Specific Command Complete Event
case HCI_VE_EVENT_CODE:
{
// Parse Command Complete Event for opcode and status
hciEvt_VSCmdComplete_t* command_complete = (hciEvt_VSCmdComplete_t*)pMsg;
First, the status of the stack message is checked to see what type of HCI event it is. In this case, it is an
HCI_VE_EVENT_CODE (0xFF).
Next, the event returned from the stack as a message (pMsg) is cast to an (hciEvt_VSCmdComplete_t*),
which is defined as:
typedef struct
{
osal_event_hdr_t hdr;
uint8 length;
uint16 cmdOpcode;
uint8 *pEventParam;
} hciEvt_VSCmdComplete_t;
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 127
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Run-Time Bluetooth low energy Protocol Stack Configuration www.ti.com
From the fourth byte of pEventParam on, the event API from the TI BLE Vendor-Specific Guide is used for
parsing, starting at the third parameter. This is the case for all vendor-specific events. For this example,
the fourth byte of pEventParam corresponds to the cmdVal parameter. This is shown in memory and
explained further below.
First the status is checked by reading the third byte of the event parameters (command_complete-
>pEventParam[2]). This is shown in yellow in Figure 5-33.
Starting from the fourth byte of the event parameters (command_complete->pEventParam[3]), the event
API states that the next parameter is a one-byte cmdVal. This is checked to verify that this event
corresponds to a read of the PER counters. This is shown in pink.
Continuing parsing using the event API, the next parameter is a two-byte numPkts. This is found by
building a uint16_t out of the fifth and sixth bytes of the event parameters. This is shown in blue. In a
similar fashion, numCrcErr is found from the seventh and eight bytes of the event parameters (shown in
green).
Next, numEvents is found from the ninth and tenth bytes of the event parameters (shown in orange).
Finally, numMissedEvents is found from the eleventh and twelfth bytes of the event parameters (shown in
purple).
Because the ble_user_config.h file is shared with projects within the SDK, TI recommends defining the
configuration parameters in the preprocessor symbols of the application when using a nondefault value.
For example, to change the maximum PDU size from the default 27 to 162, set the preprocessor symbol
MAX_PDU_SIZE=162 in the preprocessor symbols for the application project. Increasing certain
parameters may increase heap memory use by the protocol stack; adjust the HEAPMGR_SIZE as
required (if not using auto sized heap). See Section 9.2 lists the available configuration parameters.
128 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Configuring Bluetooth low energy Protocol Stack Features
NOTE: Selecting the correct stack configuration is essential in optimizing the amount of flash
memory available to the application. To conserve memory, exclude certain Bluetooth low
energy protocol stack features that may not be required.
SWRU393E – October 2010 – Revised March 2018 The Bluetooth low energy Protocol Stack 129
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Configuring Bluetooth low energy Protocol Stack Features www.ti.com
130 The Bluetooth low energy Protocol Stack SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Chapter 6
SWRU393E – October 2010 – Revised March 2018
The TI-RTOS provides a suite of CC26xx peripheral drivers that can be added to an application. The
drivers provide a mechanism for the application to interface with the CC26xx onboard peripherals and
communicate with external devices. These drivers make use of DriverLib to abstract register access.
There is significant documentation relating to each RTOS driver located at the RTOS installation path.
Refer to the BLE-Stack release notes for the specific location. . This section only provides an overview of
how drivers fit into the software ecosystem. For a description of available features and driver APIs, refer to
the TI-RTOS API Reference.
The driver source files can be found in their respective folder at $TI_RTOS_DRIVERS_BASE$\ti\drivers.
The $TI_RTOS_DRIVERS_BASE$ argument variable refers to the installation location and can be viewed
in IAR Tools→ Configure Custom Argument Variables menu. For CCS, the corresponding path variables
are defined in the Project Options→ Resource→ Linked Resources, Path Variables tab.
To add a driver to a project, include the C and include file of respective driver in the application file (or
files) where the driver APIs are referenced.
For example, to add the PIN driver for reading or controlling an output I/O pin, add the following:
#include <ti/drivers/pin/PINCC26XX.h>
Also add the following RTOS driver files to the project under the Drivers→PIN folder:
• PINCC26XX.c
• PINCC26XX.h
• PIN.h
SWRU393E – October 2010 – Revised March 2018 Peripherals and Drivers 131
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Board File www.ti.com
The board file links in another gateway board file located at $INSTALL$\
src\components\hal\src\target\<board_type>, which finally links in the actual board file from the RTOS
install.
132 Peripherals and Drivers SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Creating a Custom Board File
See the PIN driver documentation for more information on configuring this table.
6.5.1 PIN
The PIN driver allows control of the I/O pins for software-controlled general-purpose I/O (GPIO) or
connections to hardware peripherals. The SimpleBLECentral or SensorTagExample projects use the PIN
driver. As stated in Section 6.2, the pins must first be initialized to a safe state (configured in the board
file) in main(). After this initialization, any module can use the PIN driver to configure a set of pins for use.
The following is an example of configuring the simple_peripheral task to use one pin as an interrupt and
another as an output, to toggle when the interrupt occurs. IOID_x pin numbers map to DIO pin numbers
as referenced in TI CC26x0 Technical Reference Manual (SWCU117). The following table lists pins used
and their mapping on the Smart RF 06 board. These are already defined in the board file.
SWRU393E – October 2010 – Revised March 2018 Peripherals and Drivers 133
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Available Drivers www.ti.com
2. Declare the pin configuration table and pin state and handle variables to be used by the
simple_peripheral task.
static PIN_Config SBP_configTable[] =
{
Board_LED1 | PIN_GPIO_OUTPUT_EN | PIN_GPIO_LOW | PIN_PUSHPULL | PIN_DRVSTR_MAX,
Board_KEY_UP | PIN_INPUT_EN | PIN_PULLUP | PIN_HYSTERESIS,
PIN_TERMINATE
};
NOTE: This ISR is setting an event in the application task and waking it up to minimize processing
in the hwi context.
4. Define the event and related processing (in simple_peripheral_taskFxn()) to handle the event from the
above ISR.
#define SBP_BTN_EVT
if (events & SBP_BTN_EVT)
{
events &= ~SBP_BTN_EVT; //clear event
//toggle LED1
if (LED_value)
{
PIN_setOutputValue(hSbpPins, Board_LED1 , LED_value--);
}
else
{
PIN_setOutputValue(hSbpPins, Board_LED1, LED_value++);
}
}
5. Open the pins for use and configure the interrupt in simple_peripheral_init().
// Open pin structure for use
hSbpPins = PIN_open(&sbpPins, SBP_configTable);
// Register ISR
PIN_registerIntCb(hSbpPins, buttonHwiFxn);
// Configure interrupt
PIN_setConfig(hSbpPins, PIN_BM_IRQ, Board_KEY_UP | PIN_IRQ_NEGEDGE);
// Enable wakeup
PIN_setConfig(hSbpPins, PINCC26XX_BM_WaKEUP, Board_KEY_UP|PINCC26XX_WAKEUP_NEGEDGE);
6. Compile
7. Download
8. Run
NOTE: Pushing the Up button on the SmartRF06 toggles LED1. No debouncing is implemented.
134 Peripherals and Drivers SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Available Drivers
// 1000 ms
#define RCOSC_CALIBRATION_PERIOD 1000
NOTE: Use of the internal RCOSC_LF requires a sleep clock accuracy (SCA) of 500 ppm.
SWRU393E – October 2010 – Revised March 2018 Peripherals and Drivers 135
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Chapter 7
SWRU393E – October 2010 – Revised March 2018
Sensor Controller
The sensor controller engine (SCE) is an autonomous processor within the CC2640. The SCE can control
the peripherals in the sensor controller independently of the main CPU. The main CPU does not have to
wake up to (for example) execute an ADC sample or poll a digital sensor over SPI, and it saves both
current and wake-up time that would otherwise be wasted. A PC tool lets you configure the sensor
controller and choose which peripherals are controlled and which conditions wake up the main CPU. The
sensor controller studio (SCS) is a stand-alone IDE to develop and compile microcode for execution on
the SCE. Refer to Sensor Controller Studio for more details on the SCS, including documentation
embedded within the SCS IDE.
Startup Sequence
For a complete description of the CC2640 reset sequence, see TI CC26x0 Technical Reference Manual
(SWCU117).
NOTE: Because the ROM bootloader uses predefined DIO pins for internal flash programming,
allocate these pins in the layout of your board. For details on the pins allocated to the
bootloader based on the chip package type, see TI CC26x0 Technical Reference Manual
(SWCU117) .
8.2 Resets
Use only hard resets to reset the device. From software, a reset can occur through one of the following.
HCI_EXT_ResetSystemCmd(HC_EXT_RESET_SYSTEM_HARD);
HAL_SYSTEM_RESET();
In IAR, select the Board Reset option from the following Reset (back arrow) Debug Menu drop-down box.
Chapter 9
SWRU393E – October 2010 – Revised March 2018
138 Development and Debugging SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Breakpoints
9.2 Breakpoints
Both IAR and CCS reserve one of the instruction comparators. Five hardware breakpoints are available
for debugging. This section describes setting breakpoints in IAR and CCS.
For an overview of the active and inactive breakpoints, click on View→ Breakpoints.
NOTE: Conditional breaks require a debugger response and may halt the processor long enough to
break. For example, a conditional break can break an active Bluetooth low energy
connection if the condition is false or the skip count has yet to be reached.
• Go to the line.
– Press F9.
• Right-click on the line.
– Select Toggle Breakpoint (Code).
A breakpoint set on line 92 looks like the following.
For an overview of the active and inactive breakpoints, click View→ Breakpoints.
NOTE: Conditional breaks require a debugger response and may halt the processor long enough to
break. For example, a conditional break can break an active Bluetooth low energy
connection if the condition is false or the skip count has not been reached.
140 Development and Debugging SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Breakpoints
9.2.3 Considerations When Using Breakpoints With an Active Bluetooth low energy
Connection
Because the Bluetooth low energy protocol is timing sensitive, any breakpoints that break the execution
long enough to lose network timing and breaks the link. Place breakpoints as close as possible to where
the relevant debug information can be read or step through the relevant code segment to debug. This
closeness also lets you experiment on breakpoint placements by restarting debugging and repeating the
conditions that cause the code to hit the breakpoint.
SWRU393E – October 2010 – Revised March 2018 Development and Debugging 141
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Watching Variables and Registers www.ti.com
142 Development and Debugging SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Memory Watchpoints
NOTE: IAR may remove the variable during optimization. If so, add the __root directive to volatile.
NOTE: If a data watchpoint with value match is used, two of the four watchpoints are used.
This example configuration ensures that if 0x42 is written to the memory location for Characteristic 1 in the
Bluetooth low energy simple_peripheral example project. The device halts execution.
NOTE: IAR currently does not support the watchpoint functionality with the XDS debuggers, but an
IAR I-Jet can be used to accomplish this.
1. Right-click a variable.
2. Select Set Data Breakpoint for myVar to add it to the active breakpoints.
SWRU393E – October 2010 – Revised March 2018 Development and Debugging 143
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
TI-RTOS Object Viewer www.ti.com
Figure 9-1 shows a break on read access when the value matches 0x42.
144 Development and Debugging SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com TI-RTOS Object Viewer
The following list explains the column in Figure 9-3 (see Section 3.3 for more information on runtime
stacks).
• address: This column shows the memory location of the Task_Struct instance for each task.
• priority: This column shows the TI-RTOS priority for the task.
• mode: This column shows the current state of the task.
• fxn: This column shows the name of the entry function of the task.
• arg0, arg1: These columns show abitrary values that can be given to entry function of the task. In the
image, the ICall_taskEntry is given 0xb001, which is the flash location of the entry function of the RF
stack image and 0x20003a30 (the location of bleUserCfg_t user0Cfg, defined in main()).
• stackPeak: This column shows the maximum run-time stack memory used based on watermark in
RAM, where the stacks are prefilled with 0xBE and there is a sentinel word at the end of the run-time
stack.
NOTE: Function calls may push the stack pointer out of the run-time stack, but not actually write to
the entire area. A stack peak near stackSize but not exceeding it may indicate stack
overflow.
• stackSize: This column shows the size of the runtime stack, configured when instantiating a task.
• stackBase: This column shows the logical top of the runtime stack of the task (usage starts at
stackBase + stackSize and grows down to this address).
• blockedOn: This column shows the type and address of the synchronization object; the thread is
blocked on if available. For semaphores, the addresses are listed under Semaphore→ Basic.
The hwiStackPeak, hwiStackSize, and hwiStackBase can be used to check for system stack overflow.
SWRU393E – October 2010 – Revised March 2018 Development and Debugging 145
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
TI-RTOS Object Viewer www.ti.com
NOTE: The auto heap size feature does not determine the amount of heap needed for the
application. The system designer must ensure that the heap has the required space to meet
the application’s runtime memory requirements.
To calculate the size of the ICall heap by inspecting the application map file in IAR:
The size of the ICall heap is the difference between the address of the last item in the .bss section and the
start address of the system stack (CSTACK). For example, the simple_peripheral_cc2650lp_app.map file,
at the end of the PLACEMENT SUMMARY:
146 Development and Debugging SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Optimizations
"A4": 0x400
CSTACK 0x20003f68 0x400 <Block>
CSTACK uninit 0x20003f68 0x400 <Block tail>
- 0x20004368 0x400
The size of the ICall heap in this example is the address of the start of CSTACK minus the address of the
last item in .bss:
0x20003f68 - 0x20001d34 = 0x2230 or 8752 bytes
NOTE: Due to memory placement, the actual heap size may be up to 4 bytes less.
To calculate the size of the ICall heap by inspecting the application map file in CCS:
The size of the heap is determined by the heapStart and heapEnd global symbol addresses. For example,
the simple_peripheral_cc2650lp_app.map file:
20003f68 heapEnd
20001dd2 heapStart
NOTE: Due to memory placement, the actual heap size may be up to 4 bytes less.
9.7 Optimizations
While debugging, turn off or lower optimizations to ease single-stepping through code. This optimization is
possible at the following levels.
SWRU393E – October 2010 – Revised March 2018 Development and Debugging 147
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Optimizations www.ti.com
In CCS:
Project Properties→ CCS Build→ ARM Compiler→ Optimization
148 Development and Debugging SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Optimizations
NOTE: Do single-file optimizations with care because this also overrides the project-wide
preprocessor symbols.
In CCS:
1. Right-click on the file in the Workspace pane.
2. Choose Properties.
3. Change the optimization level of the file using the same menu in the CCS project-wide optimization
menu.
SWRU393E – October 2010 – Revised March 2018 Development and Debugging 149
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Optimizations www.ti.com
In CCS:
#pragma FUNCTION_OPTIONS(SimpleBLEPeripheral_taskFxn,"--opt_level=0" )
static void SimpleBLEPeripheral_taskFxn(UArg a0, UArg a1)
{
// Initialize application
SimpleBLEPeripheral_init();
// Application main loop
for (;;)
...
2. Debug the project, and look at the disassembly to verify the extra ROM symbols. For example, notice
the difference between two Disassembly with and without ROM symbols when an exception occurs, as
150 Development and Debugging SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Optimizations
2. Observe the ROM functions in the Disassembly (View -> Disassembly); for example, when an
exception occurs as shown in Figure 9-9 and Figure 9-10.
SWRU393E – October 2010 – Revised March 2018 Development and Debugging 151
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Optimizations www.ti.com
152 Development and Debugging SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Deciphering CPU Exceptions
Setting m3Hwi.enableException to false enables the minimal handler, which fills out the global
Hwi_ExcContext structure that the ROV looks at to show the decoded exception. By setting up an
excHookFunc, the minimal exception handler will call this function and pass along a pointer to the
exception context for the user to work with. This structure is defined in <ti/sysbios/family/arm/m3/Hwi.h>.
SWRU393E – October 2010 – Revised March 2018 Development and Debugging 153
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Deciphering CPU Exceptions www.ti.com
When an exception occurs, the device should end up in that infinite loop. Inspect the ROV -> Hwi ->
Exception information as shown in Figure 9-11.
In this case, a bus fault was forced in the function myTaskFxn by dereferencing address 0x0000 and
trying to write to it:
*((uint8_t *)0) = 1;
This instruction was placed on line 134 of main.c, as indicated.To get a precise location, the write buffer
was disabled as described earlier.
It can be instructive to look at the disassembly view for the locations specified by PC (program counter)
and LR (link register). PC is the presumed exception location, and LR is normally the location the failing
function should have returned to. As an example, the PC at this exception:
154 Development and Debugging SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Debugging a Program Exit
As seen both from the disassembly and from the register printout above, the literal 1 was attempted to be
stored at location 0, which is not allowed.
This code sequence can be seen in the disassembly when the ICall_abort() function is called, which can
be caused by the following:
• Calling an ICall function from a stack callback
• Misconfiguring of additional ICall tasks or entities
• Incorrect ICall task registering
A breakpoint can be set in the ICall_abort function to trace from where this error is coming.
Some generic assert causes that can be returned in the callback include HAL_ASSERT_CAUSE_TRUE,
HAL_ASSERT_CAUSE_OUT_OF_MEMORY, and HAL_ASSERT_CAUSE_ICALL_ABORT. The user can
decide how to handle these asserts in the callback. By default, it goes into spinlock for most of the
asserts.
The assert can also define a subcause that gives a more specific reason for the assert. An example of a
subcause is HAL_ASSERT_OUT_OF_HEAP, which describes the type of memory causing the assert for
HAL_ASSERT_CAUSE_OUT_OF_MEMORY.
SWRU393E – October 2010 – Revised March 2018 Development and Debugging 155
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Assert Handling www.ti.com
If no application callback is registered, the default assert callback is called and returns without further
action unless HAL_ASSERT_SPIN is defined in the application project, which traps the application in an
infinite while loop. In addition, one of the following can also be defined in the stack project if it is not
caught in the application callback:
• HAL_ASSERT_RESET: Resets the device
• HAL_ASSERT_LIGHTS: Turn on the hazard lights (to be configured by user)
• HAL_ASSERT_SPIN: Spinlock in a while loop indefinitely
Enable these by ensuring that one of the above corresponding symbols are defined in the preprocessor
symbols.
See hal_assert.h and hal_assert.c in the stack project for implementation details.
if (divisor == 0)
{
HAL_ASSERT_SET_SUBCAUSE( HAL_ASSERT_CAUSE_DIV_BY_ZERO );
HAL_ASSERT( HAL_ASSERT_CAUSE_ARITHMETIC_ERROR );
}
quotient = dividend/divisor;
...
4. The assert handler in the application should catch the assert, as in the example below of
AppAssertHandler defined in simple_peripheral.c:
void AppAssertHandler(uint8 assertCause, uint8 assertSubcause)
{
Board_openDisplay(BOARD_DISPLAY_TYPE_LCD);
Board_writeString(">>>APP ASSERT", 0);
// check the assert cause
switch (assertCause)
{
case HAL_ASSERT_CAUSE_ARITHMETIC_ERROR:
if (assertSubcause == HAL_ASSERT_CAUSE_DIV_BY_ZERO)
{
Board_writeString("***ERROR***", 1);
Board_writeString(">> DIV_BY_ZERO ERROR!", 2);
}
else
{
Board_writeString("***ERROR***", 1);
Board_writeString(">> ARITHMETIC ERROR!", 2);
}
156 Development and Debugging SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Debugging Memory Problems
break;
default:
Board_writeString("***ERROR***", 1);
Board_writeString(">> DEFAULT SPINLOCK!", 2);
HAL_ASSERT_SPINLOCK;
}
return;
}
9.12.1 Modifying
To disable a symbol, put an x in front of the name. To disable power management, change
POWER_SAVING to xPOWER_SAVING.
9.12.2 Options
Table 9-1 lists the preprocessor symbols used by the application in the simple_peripheral project. Symbols
that must remain unmodified are marked with an N in the Modify column while modifiable; configurable
symbols are marked with a Y.
SWRU393E – October 2010 – Revised March 2018 Development and Debugging 157
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Preprocessor Options www.ti.com
158 Development and Debugging SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Check System Flash and RAM Usage With Map File
Table 9-2 lists the only stack preprocessor options that may be modified:
9.13 Check System Flash and RAM Usage With Map File
Both application and stack projects produce a map file which can be used to compute the combined flash
and RAM system memory usage. Both projects have their own memory space and both map files must be
analyzed to determine the total system memory usage. The map file is in the output folder of the
respective project in IAR. To compute the total memory usage, do as follows.
1. Open the application map file (that is, simple_peripheral_cc2650em_app.map).
NOTE: At the end of the file, three lines contain a breakdown of memory usage for read-only code,
read-only data, and read/write data.
2. Add the two values for read-only code and read-only data memory.
NOTE: This sum is the total flash memory usage for the application project. The read/write data
memory is the total RAM usage by the application project.
SWRU393E – October 2010 – Revised March 2018 Development and Debugging 159
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Chapter 10
SWRU393E – October 2010 – Revised March 2018
A system designer must have a firm grasp on the general system architecture, application, and Bluetooth
low energy stack framework to implement a custom Bluetooth low energy application. This section
provides indications and guidance on where and how to start implementing a custom application based on
information presented in the previous sections. Decide what role and purpose the custom application
should have. If an application is tied to a specific service or profile, start with that sample application. An
example is the heart rate sensor project, which implements the heart rate adopted profile. Otherwise, base
your project on one of the following sample applications that implement one of the fundamental GAP roles:
• simple_central
• simple_peripheral
• simple_broadcaster
• simple_observer
160 Creating a Custom Bluetooth low energy Application SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Optimizing Bluetooth low energy Stack Memory Usage
When adding a new task that makes protocol stack API calls, including calls to OSAL SNV, the task must
register with ICall as described in Section 4.2.4. Additionally, project preprocessor settings for
OSAL_MAX_NUM_PROXY_TASKS, ICALL_MAX_NUM_TASKS, and CALL_MAX_NUM_ENTITIES may
need to be increased based on the number of added tasks (see Section 9.11).
See Section 9.13 for the procedure to check the size of the configured protocol stack.
SWRU393E – October 2010 – Revised March 2018 Creating a Custom Bluetooth low energy Application 161
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Defining Bluetooth low energy Behavior www.ti.com
162 Creating a Custom Bluetooth low energy Application SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Chapter 11
SWRU393E – October 2010 – Revised March 2018
11.1 Introduction
TI-RTOS is the new operating environment for Bluetooth low energy projects on CC26xx devices. This
software is a multithreaded environment where the protocol stack, application, and its profiles exist on
different threads. TI-RTOS has similar features to OSAL but different mechanisms for accomplishing them.
This section covers the main differences between TI-RTOS and OSAL when developing applications on
top of the Bluetooth low energy protocol stack. Although the incorporation of the RTOS is a major
architecture change, Bluetooth low energy APIs and related procedures are similar to CC254x.
This section covers the following topics:
• OSAL
• Application and stack separation with ICall
• Threads, semaphores, and queues
• Peripheral Drivers
• Event Processing
Most of these differences are unique to TI-RTOS. This section covers these differences and how they
relate to OSAL.
11.2 OSAL
A major change in moving to TI-RTOS is the complete removal of the application from the OSAL
environment. While the stack code uses OSAL within its own thread, the application thread can only use
the APIs of OSAL that are defined in ICallBleAPI.c. Many functions such as osal_memcpy(),
osal_memcmp(), and osal_mem_alloc() are unavailable. These functions have been replaced by TI-
RTOS, C run time, and ICall APIs.
SWRU393E – October 2010 – Revised March 2018 Porting from CC254x to CC2640 163
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Peripheral Drivers www.ti.com
Profile callbacks that run in the context of the Bluetooth low energy protocol stack thread are made re-
entrant by storing event data and posting a semaphore of the application to process in the context of the
application. Similarly, key press events and clock events that run in ISR context also post semaphores to
pass events to the application. Unique to TI-RTOS, queues are how applications process events in the
order the events were called and make callback functions from profiles and the stack re-entrant. The
queues also provide a FIFO ordering for event processing. An example project may use a queue to
manage internal events from an application profile or a GAP profile role (for example, Peripheral or
Central). ICall uses a queue and it is accessed through the ICall API. For a description of the TI-RTOS
objects used by the Bluetooth low energy stack SDK, see Chapter 3.
164 Porting from CC254x to CC2640 SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Chapter 12
SWRU393E – October 2010 – Revised March 2018
Sample Applications
The purpose of this section is to give an overview of the sample applications included in the TI Bluetooth
low energy stack software development kit. Some of these implementations are based on specifications
that have been adopted by the Bluetooth Special Interest Group (Bluetooth SIG), while others are based
on specifications that have not been finalized. Some applications are not based on any standardized
profile being developed by the Bluetooth SIG but are custom implementations developed by TI.
All projects contain an IAR and a CCS implementation. Except for the SimpleLink Bluetooth Smart
CC2650 SensorTag, TI intends most sample applications described in this section to run on the
SmartRF06 Evaluation Board using a CC26xx Evaluation Module. A few select projects have been ported
to the CC2650 LaunchPad.
12.1.1 Interface
This application has two button inputs.
SmarfRF Button Right— When disconnected, this button toggles advertising on and off. When
connected, this button increases the value of various measurements.
SmartRF Button Up— This button cycles through measurement formats.
12.1.2 Operation
The following steps detail how to use the Blood Pressure Sensor sample project:
1. Power up the device.
2. Press the right button to enable advertising.
3. Initiate a device discovery and connection procedure to discover and connect to the blood pressure
sensor from a blood pressure collector peer device.
NOTE: The peer device discovers the blood pressure service and configures it to enable indication
or notifications of the blood pressure measurement. The peer device may also discover the
device information service for more information such as the manufacturing and serial
number. When blood pressure measurements have been enabled, the application sends
data to the peer containing simulated measurement values.
4. Press the up button to cycle through different data formats in the following order:
• MMHG | TIMESTAMP | PULSE | USER | STATUS
• MMHG | TIMESTAMP
• MMHG
• KPA
• KPA | TIMESTAMP
12.2.1 Interface
When the left button of the SmartRF is disconnected, it toggles advertising on and off. When the up button
of the SmartRF is connected, it cycles through different heart rate sensor data formats. When in a
connection and the battery characteristic is enabled for notification, the battery level is periodically notified.
12.2.2 Operation
The following steps detail how to use the Heart Rate Sensor sample project:
1. Power up the device.
2. Press the left button to enable advertising.
3. Initiate a device discovery and connection procedure to discover and connect to the heart rate sensor
from a heart rate collector peer device.
NOTE: The peer device discovers the heart rate service and configure it to enable notifications of
the heart rate measurement. The peer device may also discover and configure the battery
service for battery level-state notifications. When heart rate measurement notifications have
been enabled the application sends data to the peer containing simulated measurement
values.
12.3.1 Interface
When the right button of the SmartRF is disconnected, it toggles advertising on and off. When the up
button of the SmartRF, it cycles through different cycling speed and cadence sensor data formats.
Pressing the select key initiates a soft reset. A soft reset includes the following.
• Terminating all current connections
• Clearing all bond data
• Clearing white list of all peer addresses
12.3.2 Operation
The following steps detail how to use the Cycling Speed and Cadence Sensor sample project:
1. Power up the device.
2. Press the right button to enable advertising.
3. Initiate a device discovery and connection procedure to discover and connect to the cycling sensor
from a CSC collector peer device.
NOTE: The peer device receives a slave security request and initiates a bond. When bonded, the
collector discovers the CSC service and configures it to enable CSC measurements. When
CSC measurement notifications have been enabled, the application sends data to the peer
containing simulated measurement values.
12.4.1 Interface
When the right button of the SmartRF is disconnected, it toggles advertising on and off. When the up
button of the SmartRF is connected, it cycles through different running speed and cadence sensor data
formats.
Pressing the select key initiates a soft reset. This reset includes the following.
• Terminating all current connections
• Clearing all bond data
• Clearing the white list of all peer addresses
12.4.2 Operation
The following steps detail how to use the Running Speed and Cadence Sensor sample project:
1. Power up the device.
2. Press the right button to enable advertising.
3. Initiate a device discovery and connection procedure to discover and connect to the cycling sensor
from an RSC collector peer device.
NOTE: The peer device receives a slave security request and initiates a bond. When bonded, the
collector discovers the RSC service and configures it to enable running speed and cadence
measurements. When RSC measurement notifications have been enabled, the application
sends data to the peer containing simulated measurement values.
12.5.1 Interface
The SmartRF buttons and display provide an interface for the application. The buttons are as follows.
• Up: If not connected, start or stop device discovery. If connected to a glucose sensor, request the
number of records that meet configured filter criteria.
• Left: Scroll through device discovery results. If connected to a glucose sensor, send a record access
abort message.
• Select: Connect or disconnect to or from the selected device.
• Right: If connected, request records that meet configured filter criteria.
• Down: If connected, clear records that meet configured filter criteria. If not connected, erase all bonds.
The LCD display displays the following information.
• BD address of the device
• Device discovery results
• Connection state
• Pairing and bonding status
• Number of records requested
• Sequence number, glucose concentration, and Hba1c value of received glucose measurement and
context notifications
12.6.1 Interface
When the right button is disconnected, it toggles advertising on and off. When the up button is connected,
it sends a glucose measurement and glucose context.
12.6.2 Operation
The following steps detail how to use the Glucose Sensor sample projects:
1. Power up the device.
2. Press the right button to enable advertising.
3. Initiate a device discovery and connection procedure to discover and connect to the glucose sensor
from a glucose collector peer device.
NOTE: The peer device discovers the glucose service and configures it to enable notifications of the
glucose measurement. the device may also enable notifications of the glucose measurement
context. When glucose measurement notifications have been enabled a simulated
measurement can be sent by pressing the up button. If the peer device has also enabled
notifications of the glucose measurement context then this is sent following the glucose
measurement. The peer device may also write commands to the record access control point
to retrieve or erase stored glucose measurement records. The sensor has four hardcoded
simulated records. If the peer device initiates pairing then the devices pair. Only just works
pairing is supported by the application (pairing without a passcode).
12.7.1 Interface
When the following are connected, they send the following key presses:
• The left button sends a left arrow key.
• The right button sends a right arrow key.
• The up button sends an up arrow key.
• The down button sends a down arrow key.
A secure connection must be established before key presses is sent to the peer device.
12.7.2 Operation
The following steps detail how to use the HID-Emulated Keyboard sample project:
1. Power up the device.
2. Initiate a device discovery and connection procedure to discover and connect to the HID device from a
HID Host peer device.
NOTE: The peer device discovers the HID service and recognizes the device as a keyboard. The
peer device may also discover and configure the battery service for battery level-state
notifications. By default, the HID device requires security and uses just works pairing. After a
secure connection is established and the HID host configures the HID service to enable
notifications, the HID device can send HID key presses to the HID host. A notification is sent
when a button is pressed and when a button is released. If there is no HID activity for a
period of time (20 seconds by default) the HID device disconnects. When the connection is
closed, the HID device advertises again.
12.9 KeyFob
The KeyFob application demonstrates the following:
• Report battery level
• Report 3-axis accelerometer readings
• Report proximity changes
• Report key press changes
The following GATT services are used:
• Device Information
• Link Loss
• Immediate Alert (for the Reporter role of the Proximity Profile and for the Target role of the Find Me
Profile)
• Tx Power (for the Report role of the Proximity Profile)
• Battery
• Accelerometer
• Simple Keys
The accelerometer and simple keys profiles are unaligned with official SIG profiles but are an example of
the implementation of the profile service. The device information service and proximity-related services are
based on adopted specifications.
12.9.1 Interface
This application uses two buttons for input and an LED and buzzer for output.
Right Button
When disconnected, this button toggles advertising on and off. When connected, this button registers a
key press that can be enabled to notify a peer device or may be read by a peer device.
Left Button
When connected, this button registers a key press that can be enabled to notify a peer device or may be
read by a peer device.
Buzzer
The buzzer activates if a Link Loss Alert is triggered.
12.9.4 Keys
The simple keys service on the SmartRF lets the device send notifications of key presses and releases to
a central device. The application registers with HAL to receive a callback in case HAL detects a key
change. The peer device can read the value of the keys by reading <SK_KEYPRESSED_UUID>. The
peer device can enable key press notifications by writing 01 to <GATT_CLIENT_CHAR_CFG_UUID>. A
value of 00 indicates that neither key is pressed. A value of 01 indicates that the left key is pressed. A
value of 02 indicates that the right key is pressed. A value of 03 indicates that both keys are pressed.
12.9.5 Proximity
One of the services of the Proximity Profile is the link loss service, which lets the proximity reporter begin
an alert if the connection drops. The link loss alert can be set by writing a value to
<PROXIMITY_ALERT_LEVEL_UUID>.
The default alert value setting is 00, which indicates no alert. To turn on the alert, write a 1-byte value of
01 (low alert) or 02 (high alert). By default, the link does not time out until 20 seconds have passed
without receiving a packet. This Supervision Timeout value can be changed in the Connection Services
tab. The time-out value must be set before the connection is established. After completing the write, move
the SmartRF device far enough away from the USB Dongle until disconnected. Alternatively, disconnect
the USB Dongle from the PC. When the time-out expires, the alarm is triggered. If a low alert is set, the
SmartRF makes a low-pitched beep. If a high alert is set, the SmartRF makes a high-pitched beep. In
either case, the SmartRF beeps 10 times and then stops. To stop the beeping, either connect with the
SmartRF or press the left button.
12.10 SensorTag
The SimpleLink Bluetooth low energy CC2650 SensorTag 2.0 is a Bluetooth low energy peripheral slave
device that runs on the CC2650 SensorTag reference hardware platform. The SimpleLink CC2650 is a
multistandard wireless MCU that supports Bluetooth low energy and other wireless protocols. Software
developed with the Bluetooth low energy stack is binary compatible with the CC2650. The SensorTag 2.0
includes multiple peripheral sensors with a complete software solution for sensor drivers interfaced to a
GATT server running on TI Bluetooth low energy protocol stack. The GATT server contains a primary
service for each sensor for configuration and data collection. For a description of the available sensors,
see http://www.ti.com/sensortag.
12.10.1 Operation
On start-up, the SensorTag advertises with a 100-ms interval. The connection is established by a central
device and the sensors can then be configured to provide measurement data. The central device could be
any Bluetooth low energy-compliant device and the main focus is on Bluetooth low energy-compliant
mobile phones, running either Android™ or iOS®. The central device operates as follows:
• Scans and discovers the SensorTag ( the scan response contains name SensorTag)
• Establishes connection based on user-defined connection parameters
• Performs service discovery (discovers characteristics by UUID)
• Operates as a GATT client (write to and read from Characteristic Value)
The central device initiates the connection and becomes the master. To obtain the data, first activate the
corresponding sensor through a Characteristic Value write to appropriate service.
The most power-efficient way to obtain measurements for a sensor is as follows:
1. Enable notifications.
2. Enable the sensor.
3. Disable the sensor (with notification on) when notifications with data are obtained on the master side.
Alternatively, to not use notifications at all do as follows:
1. Enable the sensor.
2. Read the data and verify.
3. Disable the sensor.
For the alternative, the sensor takes a varying amount of time to measure data. Depending on the
connection interval (approximately 10 to 4000 ms) set by the central device, the time to measure data
varies. The individual sensors require varying delays to complete measurements. TI recommends a
setting of 100 ms. For fast accelerometer and magnetometer data updates, a lower setting is required.
You can stop notifications and turn the sensors on or off.
12.10.2 Sensors
The following sensors support SensorTag:
• IR Temperature, both object and ambient temperature
• Accelerometer, 3-axis
• Humidity, both relative humidity and temperature
• Magnetometer, 3-axis
• Barometer, both pressure and temperature
• Gyroscope, 3-axis
12.11.1 Interface
The SmartRF buttons and display provide an interface for the application. The buttons are as follows:
• Up: If disconnected, start or stop device discovery. If connected to a simple_peripheral, alternate
sample read and write requests.
• Left: Scroll through device discovery results.
• Select: Connect or disconnect to or from the selected device.
• Right: If connected, send a parameter update request.
• Down: If connected, start or cancel RSSI polling.
The LCD display displays the following information:
• BD address of the device
• Device discovery results
• Connection state
• Pairing and bonding status
• Attribute read or write value after parameter update
12.15 TimeApp
This sample project implements time and alert-related profiles in a Bluetooth low energy peripheral device
to provide an example of how Bluetooth low energy profiles are used in a product like a watch. The project
is based on adopted profile specifications for Time, Alert Notification, and Phone Alert Status. All profiles
are implemented in the client role. The following Network Availability Profile, Network Monitor role has
been implemented, based on Network Availability Draft Specification d05r04 (UCRDD). This project has
been configured for the SmartRF06 board.
12.15.1 Interface
The interface for the application consists of the SmartRF06 buttons and display. The buttons are used as
follows:
• Up: Starts or stops advertising.
• Left: If connected, sends a command to the Alert Notification control point.
• Center: If connected, disconnects. If held down on power-up, erases all bonds.
• Right: If connected, initiates a Reference Time update.
• Down: If connected, initiates a Ringer Control Point update.
The LCD display shows the following information:
• BD address of the device
• Connection state
• Pairing and bonding status
• Passcode display
• Time and date
• Network availability
• Battery state of peer device
• Alert notification messages
• Unread message alerts
• Ringer status
12.15.2 Operation
The following steps detail how to use the Time App sample project.
1. Power up the application.
NOTE: When the application powers up it displays Time App, the BD address of the device, and a
default time and date of 00:00 Jan01 2000.
NOTE: The connection status displays. When the application tries to discover the following services
on the peer device:
• Current Time Service
• DST Change Service
• Reference Time Service
• Alert Notification Service
• Phone Alert Status Service
• Network Availability Service
• Battery Service
The discovery procedure caches handles of interest. When bonded to a peer device, the handles are
saved to avoid performing the procedure again. If a service is discovered certain service characteristics
are read and displayed. The network availability status and battery level is displayed and the current time
updates. The application also enables notification or indication for characteristics that support these
operations. The enabling of notification or indication allows the peer device to send notifications or
indications updating the time, network availability, or battery status. The peer device can also send alert
notification messages and unread message alerts. These updates and messages is displayed on the LCD.
The peer device may initiate pairing. If a passcode is required, the application generates and displays a
random passcode.
Enter this passcode on the peer device to proceed with pairing. The application advertises using either a
fast interval or a slow interval. When advertising is initiated by a button press or when a connection is
terminated due to link loss, the application starts advertising at the fast interval for 30 seconds followed by
the slow interval. When a connection is terminated for any other reason the application starts advertising
at the slow interval. The advertising intervals and durations are configurable in the timeapp.c file.
12.16 Thermometer
This sample project implements a Health Thermometer and Device Information Profile in a low-energy
peripheral device to provide an example health thermometer application using simulated measurement
data. The application implements the Sensor role of the Health Thermometer Profile. The project is based
on the adopted profile and service specifications for Health Thermometer. The project also includes the
Device Information Service. This project has been configured to run on the SmartRF06 board.
12.16.1 Interface
This application has two buttons inputs.
Right Button
When the button is disconnected and unconfigured to take measurements, it toggles advertising on and
off. When connected or configured to take measurements, pressing this button increases the temperature
by 1°C. After a 3°C increase in temperature, the interval is set to 30 seconds. This thermometer
application also sends an indication to the peer with this interval change if configured.
Up Button
This button cycles through different measurement formats.
12.16.2 Operation
The following steps detail how to use the Thermometer sample project:
1. Power up the device.
2. Press the right button to enable advertising.
3. Initiate a device discovery and connection procedure to discover and connect to the thermometer
sensor from a thermometer collector peer device.
NOTE: The peer device discovers the thermometer service and configures it to enable indication or
notifications of the thermometer measurement. The peer device may also discover the
device information service for more information such as manufacturing and serial number.
When thermometer measurements have been enabled, the application sends data to the
peer containing simulated measurement values.
GAP API
A.1 Commands
This section details the GAP commands from gap.h that the application uses. All other GAP commands
are abstracted through the GAPRole or the GAPBondMgr. The return values described in this section are
the return values from processing the command. If ICall is incorrectly configured or does not have enough
memory to allocate a message, the command is never processed by the Bluetooth low energy stack. In
this case, one of the ICall return values from Appendix I is returned.
A.3 Events
This section details the events relating to the GAP layer that can be returned to the application from the
Bluetooth low energy stack. Some of these events are passed directly to the application and some are
handled by the GAPRole or GAPBondMgr layers. The events are passed as a GAP_MSG_EVENT with
header:
typedef struct
{
osal_event_hdr_t hdr; //!< GAP_MSG_EVENT and status
uint8 opcode; //!< GAP type of command. Ref: @ref GAP_MSG_EVENT_DEFINES
} gapEventHder_t;
The following is a list of the possible hdr and the associated events. See gap.h for all other definitions
used in these events.
• GAP_DEVICE_INIT_DONE_EVENT: Sent when the Device Initialization is complete
typedef struct
{
osal_event_hdr_t hdr; //!< GAP_MSG_EVENT and status
uint8 opcode; //!< GAP_DEVICE_INIT_DONE_EVENT
uint8 devAddr[B_ADDR_LEN]; //!< Device's BD ADDR
uint16 dataPktLen; //!< HC_LE_Data_Packet_Length
uint8 numDataPkts; //!< HC_Total_Num_LE_Data_Packets
} gapDeviceInitDoneEvent_t;
• GAP_DEVICE_DISCOVERY_EVENT: Sent when the Device Discovery Process is complete
typedef struct
{
osal_event_hdr_t hdr; //!<GAP_MSG_EVENT and status
uint8 opcode; //!< GAP_DEVICE_DISCOVERY_EVENT
uint8 numDevs; //!< Number of devices found during scan
gapDevRec_t *pDevList; //!< array of device records
} gapDevDiscEvent_t;
• GAP_ADV_DATA_UPDATE_DONE_EVENT: Sent when the Advertising Data or SCAN_RSP Data has
been updated
typedef struct
{
osal_event_hdr_t hdr; //!< GAP_MSG_EVENT and status
uint8 opcode; //!< GAP_ADV_DATA_UPDATE_DONE_EVENT
uint8 adType; //!< TRUE if advertising data, FALSE if SCAN_RSP
} gapAdvDataUpdateEvent_t;
• GAP_MAKE_DISCOVERABLE_DONE_EVENT: Sent when the Make Discoverable Request is
complete
typedef struct
{
osal_event_hdr_t hdr; //!< GAP_MSG_EVENT and status
uint8 opcode; //!< GAP_MAKE_DISCOVERABLE_DONE_EVENT
} gapMakeDiscoverableRspEvent_t;
The return values described in this section are only the possible return values from processing the
command. If ICall is incorrectly configured or does not have enough memory to allocate a message, the
command is never processed by the Bluetooth low energy stack. In this case, one of the ICall return
values from Appendix I is returned.
B.1 Commands
SWRU393E – October 2010 – Revised March 2018 GAPRole Peripheral Role API 187
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Commands www.ti.com
bStatus_t GAPRole_TerminateConnection(void)
Terminates an existing connection.
188 GAPRole Peripheral Role API SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Configurable Parameters
Parameters pParamUpdateCB: pointer to param update callback. See Section B.3 for more
information.
SWRU393E – October 2010 – Revised March 2018 GAPRole Peripheral Role API 189
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Configurable Parameters www.ti.com
190 GAPRole Peripheral Role API SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Configurable Parameters
ParamID R/W Size Description
GAPROLE_MAX_CONN_INTE R/W uint16 Maximum connection interval to use when performing param update
RVAL through GAPROLE_PARAM_UPDATE_ENABLE or
GAPROLE_PARAM_UPDATE_REQ (n × 1.25 ms)
Possible values: GAPROLE_MIN_CONN_INTERVAL - 3200
Default value: 3200
GAPROLE_SLAVE_LATENCY R/W uint16 Slave latency to use when performing param update through
GAPROLE_PARAM_UPDATE_ENABLE or
GAPROLE_PARAM_UPDATE_REQ
Possible values: 0-499
Default value: 0
GAPROLE_TIMEOUT_MULTI R/W uint16 Supervision timeout to use when performing param update through
PLIER GAPROLE_PARAM_UPDATE_ENABLE or
GAPROLE_PARAM_UPDATE_REQ (n × 10 ms)
Possible values: 10-3200
Default value: 1000
GAPROLE_CONN_BD_ADDR R uint8[6] Address of connected device.
Possible values: 0x000000000000 – 0xFFFFFFFFFFFD
Default value: 0x000000000000
GAPROLE_CONN_INTERVAL R uint16 Current connection interval (n × 1.25 ms)
Possible values: 6 - 3200
Default value: 0
GAPROLE_CONN_LATENCY R uint16 Current slave latency
Possible values: 0 - 499
Default value: 0
GAPROLE_CONN_TIMEOUT R uint16 Current supervision timeout (n × 10 ms)
Possible values: 10 – 3200
Default value: 0
GAPROLE_PARAM_UPDATE W uint8 Used to send an asynchronous parameter update request.
_REQ
Possible values:
• 0x00: Doesn’t do anything
• 0x01: Sends parameter update request
GAPROLE_STATE R uint8 Current peripheral GAPRole state.
Possible values: See Section B.3.1
Default value: GAPROLE_INIT
GAPROLE_ADV_NONCONN_ R/W uint8 Enable or disable non-connectable advertising.
ENABLED
Possible values:
• 0x00: Disable non-connectable advertising
• 0x01: Enable non-connectable advertising.
GAPROLE_ADVERT_ENABLE must be set to 0x00.
Default value: 0x00
GAPROLE_BD_ADDR_TYPE R uint8 Address type of connected device
Possible values:
• ADDRTYPE_PUBLIC (0x00): Public Device Address
• ADDRTYPE_RANDOM (0x01): Random Device Address
• ADDRTYPE_PUBLIC_ID (0x02): Public Identity Address
(corresponds to peer's RPA)
• ADDRTYPE_RANDOM_ID (0x03): Random (static) Identity Address
(corresponds to peer's RPA)
Default value: ADDRTYPE_PUBLIC
SWRU393E – October 2010 – Revised March 2018 GAPRole Peripheral Role API 191
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Callbacks www.ti.com
B.3 Callbacks
Callback are functions whose pointers are passed from the application to the GAPRole so that the
GAPRole can return events to the application. They are passed as the following:
/**
* Callback structure - must be setup by the application and used when
* GAPRole_StartDevice() is called.
*/
typedef struct
{
gapRoleStateNotify_t pfnStateChange; //!< Whenever the device changes state
} gapRolesCBs_t;
/**
* Callback when the device has been started. Callback event to
* the Notify of a state change.
*/
typedef void (*gapRolesStateNotify_t)(gaprole_States_t newState);
192 GAPRole Peripheral Role API SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
The various GAPRole states (newState) are as follows:
• GAPROLE_INIT //!< Waiting to be started
• GAPROLE_STARTED //!< Started but not advertising
• GAPROLE_ADVERTISING //!< Currently advertising
• GAPROLE_ADVERTISING_NONCONN //!< Currently using non-connectable advertising
• GAPROLE_WAITING //!< Device is started and in a waiting period before advertising again
• GAPROLE_WAITING_AFTER_TIMEOUT //!< Device timed out from a connection but is not yet
advertising, the device is in waiting period before advertising again.
• GAPROLE_CONNECTED //!< In a connection
• GAPROLE_CONNECTED_ADV //!< In a connection + advertising
• GAPROLE_ERROR //!< Error occurred – invalid state
Appendix C
SWRU393E – October 2010 – Revised March 2018
The return values described in this section are only the possible return values from processing the
command. If ICall is incorrectly configured or does not have enough memory to allocate a message, the
command never gets processed by the Bluetooth low energy stack. In this case, one of the ICall return
values from Appendix I is returned.
C.1 Commands
SWRU393E – October 2010 – Revised March 2018 GAPRole Central Role API 193
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Commands www.ti.com
194 GAPRole Central Role API SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Commands
SWRU393E – October 2010 – Revised March 2018 GAPRole Central Role API 195
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Commands www.ti.com
bStatus_t GAPCentralRole_CancelDiscovery(void)
Cancel a device discovery scan.
Parameters None
196 GAPRole Central Role API SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Configurable Parameters
C.3 Callbacks
Callbacks are functions whose pointers are passed from the application to the GAPRole so that the
GAPRole can return events to the application. They are passed as follows.
typedef struct
{
pfnGapCentralRoleEventCB_t eventCB; //!< Event callback.
} gapCentralRolecB_t;
SWRU393E – October 2010 – Revised March 2018 GAPRole Central Role API 197
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Callbacks www.ti.com
If the message is successfully queued to the application for later processing, FALSE is returned because
the application deallocates it later. Consider the state change event as an example of this:
static void SimpleBLECentral_processAppMsg(sbcEvt_t *pMsg)
{
switch (pMsg->hdr.event)
{
case SBC_STATE_CHANGE_EVT:
SimpleBLECentral_processStackMsg((ICall_Hdr *)pMsg->pData);
If the message is not successfully queued to the application, TRUE is returned so that the GAPRole can
deallocate the message. If the heap has enough room, the message must always be successfully
enqueued. The possible GAP events that can be forward through this callback to the application are
defined in Section A.3.
198 GAPRole Central Role API SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Appendix D
SWRU393E – October 2010 – Revised March 2018
This section describes the API of the GATT and ATT layers. The two sections are combined because the
general procedure is to send GATT commands and receive ATT events as described in Section 5.3.3.1.
The return values for the commands referenced in this section are described in Section D.4.
The possible return values are similar for all of these commands so they are described in Section D.4. The
return values described in this section are only the possible return values from processing the command.
If ICall is incorrectly configured or does not have enough memory to allocate a message, the command
never gets processed by the Bluetooth low energy stack. In this case, one of the ICall return values from
Appendix I is returned.
Corresponding Events If the return status is SUCCESS, the application task specified by taskId receives a
GATT_MSG_EVENT message with type ATT_HANDLE_VALUE_CFM upon an
acknowledgment from the client. Only at this point is this subprocedure complete.
SWRU393E – October 2010 – Revised March 2018 GATT and ATT API 199
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Client Commands www.ti.com
bStatus_t GATT_InitClient(void)
Initialize the GATT client in the Bluetooth low energy stack.
NOTE: GATT clients must call this from the application init function.
NOTE: GATT clients must call this from the application initialization function.
NOTE: This function can only be called once during a connection. For more
information on the MTU, see Section 5.5.2.
Corresponding Events If the return status from this function is SUCCESS, the calling application task receives
an OSAL GATT_MSG_EVENT message. The type of the message is either
ATT_EXCHANGE_MTU_RSP (with SUCCESS or bleTimeout status) indicating a
SUCCESS or ATT_ERROR_RSP (with status SUCCESS) if an error occurred on the
server.
200 GATT and ATT API SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Client Commands
Corresponding Events: If the return status is SUCCESS, the calling application task receives multiple
GATT_MSG_EVENT messages with type ATT_READ_BY_GRP_TYPE_RSP or
ATT_ERROR_RSP (if an error occurred on the server). This subprocedure is complete
when either ATT_READ_BY_GRP_TYPE_RSP (with bleProcedureComplete or
bleTimeout status) or ATT_ERROR_RSP (with SUCCESS status) is received by the
calling application task.
Corresponding Events If the return status is SUCCESS, the calling application task receives multiple
GATT_MSG_EVENT messages with type ATT_FIND_BY_TYPE_VALUE_RSP or
ATT_ERROR_RSP (if an error occurred on the server). This subprocedure is complete
when either ATT_FIND_BY_TYPE_VALUE_RSP (with bleProcedureComplete or
bleTimeout status) or ATT_ERROR_RSP (with SUCCESS status) is received by the
calling application task.
Corresponding Events If the return status is SUCCESS, the calling application task receives multiple
GATT_MSG_EVENT messages with type ATT_READ_BY_TYPE_RSP or
ATT_ERROR_RSP (if an error occurred on the server). This subprocedure is complete
when either ATT_READ_BY_TYPE_RSP (with bleProcedureComplete or bleTimeout
SWRU393E – October 2010 – Revised March 2018 GATT and ATT API 201
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Client Commands www.ti.com
Corresponding Events: If the return status is SUCCESS, the calling application task receives multiple
GATT_MSG_EVENT messages with type ATT_READ_BY_TYPE_RSP or
ATT_ERROR_RSP (if an error occurred on the server). This subprocedure is complete
when either ATT_READ_BY_TYPE_RSP (with bleProcedureComplete or bleTimeout
status) or ATT_ERROR_RSP (with SUCCESS status) is received by the calling
application task.
Corresponding Events If the return status is SUCCESS, the calling application task receives multiple
GATT_MSG_EVENT messages with type ATT_READ_BY_TYPE_RSP or
ATT_ERROR_RSP (if an error occurred on the server). This subprocedure is complete
when either ATT_READ_BY_TYPE_RSP (with bleProcedureComplete or bleTimeout
status) or ATT_ERROR_RSP (with SUCCESS status) is received by the calling
application task.
202 GATT and ATT API SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Client Commands
Corresponding Events If the return status is SUCCESS, the calling application task receives multiple
GATT_MSG_EVENT messages with type ATT_FIND_INFO_RSP or ATT_ERROR_RSP
(if an error occurred on the server). This subprocedure is complete when either
ATT_FIND_INFO_RSP (with bleProcedureComplete or bleTimeout status) or
ATT_ERROR_RSP (with SUCCESS status) is received by the calling application task.
Corresponding Events If the return status is SUCCESS, the calling application task receives an OSAL
GATT_MSG_EVENT message with type ATT_READ_RSP or ATT_ERROR_RSP (if an
error occurred on the server). This subprocedure is complete when either
ATT_READ_RSP (with SUCCESS or bleTimeout status) or ATT_ERROR_RSP (with
SUCCESS status) is received by the calling application task.
Corresponding Events If the return status is SUCCESS, the calling application task receives an OSAL
GATT_MSG_EVENT message with type ATT_READ_BY_TYPE_RSP or
ATT_ERROR_RSP (if an error occurred on the server). This subprocedure is complete
when either ATT_READ_BY_TYPE_RSP (with SUCCESS or bleTimeout status) or
ATT_ERROR_RSP (with SUCCESS status) is received by the calling application task.
SWRU393E – October 2010 – Revised March 2018 GATT and ATT API 203
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Client Commands www.ti.com
Corresponding Events If the return status is SUCCESS, the calling application task receives multiple
GATT_MSG_EVENT messages with type ATT_READ_BLOB_RSP or
ATT_ERROR_RSP (if an error occurred on the server). This subprocedure is complete
when either ATT_READ_BLOB_RSP (with bleProcedureComplete or bleTimeout status)
or ATT_ERROR_RSP (with SUCCESS status) is received by the calling application task.
Corresponding Events If the return status from this function is SUCCESS, the calling application task receives
an OSAL GATT_MSG_EVENT message with type ATT_READ_MULTI_RSP or
ATT_ERROR_RSP (if an error occurred on the server). This subprocedure is complete
when either ATT_READ_MULTI_RSP (with SUCCESS or bleTimeout status) or
ATT_ERROR_RSP (with SUCCESS status) is received by the calling application task.
Corresponding Events No response are sent to the calling application task for this subprocedure. If the
Characteristic Value write request is the wrong size, or has an invalid value as defined
by the profile, then the write does not succeed and no error is generated by the server.
The payload must be dynamically allocated as described in Section 5.3.5.
204 GATT and ATT API SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Client Commands
Corresponding Events No response is sent to the calling application task for this subprocedure. If the
authenticated Characteristic Value that is written is the wrong size, or has an invalid
value as defined by the profile, or the signed value does not authenticate the client, then
the write does not succeed and no error is generated by the server. The payload must
be dynamically allocated as described in Section 5.3.5.
Corresponding Events If the return status from this function is SUCCESS, the calling application task receives
an OSAL GATT_MSG_EVENT message with type ATT_WRITE_RSP or
ATT_ERROR_RSP (if an error occurred on the server). This subprocedure is complete
when either ATT_WRITE_RSP (with SUCCESS or bleTimeout status) or
ATT_ERROR_RSP (with SUCCESS status) is received by the calling application task.
The payload must be dynamically allocated as described in Section 5.3.5.
Corresponding Events If the return status from this function is SUCCESS, the calling application task receives
an OSAL GATT_MSG_EVENT message with type ATT_PREPARE_WRITE_RSP,
ATT_EXECUTE_WRITE_RSP or ATT_ERROR_RSP (if an error occurred on the
SWRU393E – October 2010 – Revised March 2018 GATT and ATT API 205
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Client Commands www.ti.com
Corresponding Events If the return status is SUCCESS, the calling application task receives multiple
GATT_MSG_EVENT messages with type ATT_PREPARE_WRITE_RSP,
ATT_EXECUTE_WRITE_RSP or ATT_ERROR_RSP (if an error occurred on the
server). This subprocedure is complete when either ATT_PREPARE_WRITE_RSP (with
bleTimeout status), ATT_EXECUTE_WRITE_RSP (with SUCCESS or bleTimeout
status) or ATT_ERROR_RSP (with SUCCESS status) is received by the calling
application task. The payload must be dynamically allocated as described in
Section 5.3.5.
Corresponding Events If the return status from this function is SUCCESS, the calling application task receives
an OSAL GATT_MSG_EVENT message with type ATT_READ_RSP or
ATT_ERROR_RSP (if an error occurred on the server). This subprocedure completes
when either ATT_READ_RSP (with SUCCESS or bleTimeout status) or
ATT_ERROR_RSP (with SUCCESS status) is received by the calling application task.
206 GATT and ATT API SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Client Commands
Corresponding Events If the return status is SUCCESS, the calling application task receives multiple
GATT_MSG_EVENT messages with type ATT_READ_BLOB_RSP or
ATT_ERROR_RSP (if an error occurred on the server). This subprocedure is complete
when either ATT_READ_BLOB_RSP (with bleProcedureComplete or bleTimeout status)
or ATT_ERROR_RSP (with SUCCESS status) is received by the calling application task.
Corresponding Events If the return status is SUCCESS, the calling application task receives multiple
GATT_MSG_EVENT messages with type ATT_PREPARE_WRITE_RSP,
ATT_EXECUTE_WRITE_RSP or ATT_ERROR_RSP (if an error occurred on the
server). This subprocedure is complete when either ATT_PREPARE_WRITE_RSP (with
bleTimeout status), ATT_EXECUTE_WRITE_RSP (with SUCCESS or bleTimeout
status), or ATT_ERROR_RSP (with SUCCESS status) is received by the calling
application task. The payload must be dynamically allocated as described in
Section 5.3.5.
SWRU393E – October 2010 – Revised March 2018 GATT and ATT API 207
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Return Values www.ti.com
D.5 Events
Events are received from the Bluetooth low energy stack in the application as a GATT_MSG_EVENT
stack message sent through ICall. Events are received as the following structure where the method
signifies the ATT event and the message is a combination of all the various ATT events.
typedef struct
{
osal_event_hdr_t hdr; //!< GATT_MSG_EVENT and status
uint16 connHandle; //!< Connection message was received on
uint8 method; //!< Type of message
gattMsg_t msg; //!< Attribute protocol/profile message
} gattMsgEvent_t;
This section lists the various ATT events by their method and displays their structure that is used in the
message payload. These events are listed in the att.h file.
• ATT_ERROR_RSP (0x01)
typedef struct
{
uint8 reqOpcode; //!< Request that generated this error response
uint16 handle; //!< Attribute handle that generated error response
uint8 errCode; //!< Reason why the request has generated error response
} attErrorRsp_t;
attErrorRsp_t
• ATT_FIND_INFO_RSP (0x03)
typedef struct
{
uint16 numInfo; //!< Number of attribute handle-UUID pairs found
uint8 format; //!< Format of information data
uint8 *pInfo; //!< Information data whose format is determined by format field (4 to
ATT_MTU_SIZE-2)
} attFindInfoRsp_t;
208 GATT and ATT API SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
www.ti.com Events
• ATT_FIND_BY_TYPE_VALUE_RSP (0x07)
typedef struct
{
uint16 numInfo; //!< Number of handles information found
uint8 *pHandlesInfo;//!< List of 1 or more handles information (4 to ATT_MTU_SIZE-1)
} attFindByTypeValueRsp_t;
• ATT_READ_BY_TYPE_RSP (0x09)
typedef struct
{
uint16 numPairs; //!< Number of attribute handle-UUID pairs found
uint16 len; //!< Size of each attribute handle-value pair
uint8 *pDataList; //!< List of 1 or more attribute handle-value pairs (2 to ATT_MTU_SIZE-2)
uint16 dataLen; //!< Length of data written into pDataList. Not part of actual ATT Response
} attReadByTypeRsp_t;
• ATT_READ_RSP (0x0B)
typedef struct
{
uint16 len; //!< Length of value
uint8 *pValue; //!< Value of the attribute with the handle given (0 to ATT_MTU_SIZE-1)
} attReadRsp_t;
• ATT_READ_BLOB_RSP (0x0D)
typedef struct
{
uint16 len; //!< Length of value
uint8 *pValue; //!< Part of the value of the attribute with the handle given (0 to
ATT_MTU_SIZE-1)
} attReadBlobRsp_t;
• ATT_READ_MULTI_RSP (0x0F)
typedef struct
{
uint16 len; //!< Length of values
uint8 *pValue; //!< Set of two or more values (0 to ATT_MTU_SIZE-1)
} attReadMultiRsp_t;
• ATT_READ_BY_GRP_TYPE_RSP (0x11)
typedef struct
{
uint16 numGrps; //!< Number of attribute handle, end group handle and value sets found
uint16 len; //!< Length of each attribute handle, end group handle and value set
uint8 *pDataList; //!< List of 1 or more attribute handle, end group handle and value (4 to
ATT_MTU_SIZE-2)
} attReadByGrpTypeRsp)t;
• ATT_WRITE_RSP (0x13)
No data members
SWRU393E – October 2010 – Revised March 2018 GATT and ATT API 209
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Events www.ti.com
• ATT_PREPARE_WRITE_RSP (0x17)
typedef struct
{
uint16 handle; //!< Handle of the attribute that has been read
uint16 offset; //!< Offset of the first octet to be written
uint16 len; //!< Length of value
uint8 *pValue; //!< Part of the value of the attribute to be written (0 to ATT_MTU_SIZE-5)
} attPrepareWriteRsp_t;
• ATT_EXECUTE_WRITE_RSP (0x19)
No data members
• ATT_HANDLE_VALUE_NOTI (0x1B)
typedef struct
{
uint16 handle; //!< Handle of the attribute that has been changed (must be first field)
uint16 len; //!< Length of value
uint8 *pValue; //!< New value of the attribute (0 to ATT_MTU_SIZE-3)
} attHandleValueNoti_t;
• ATT_HANDLE_VALUE_IND (0x1D)
typedef struct
{
uint16 handle; //!< Handle of the attribute that has been changed (must be first field)
uint16 len; //!< Length of value
uint8 *pValue; //!< New value of the attribute (0 to ATT_MTU_SIZE-3)
} attHandleValueInd_t;
• ATT_HANDLE_VALUE_CFM (0x1E)
– o Empty msg field
• ATT_FLOW_CTRL_VIOLATED_EVENT (0x7E)
typedef struct
{
uint8 opcode; //!< opcode of message that caused flow control violation
uint8 pendingOpcode; //!< opcode of pending message
} attFlowCtrlViolatedEvt_t;
• ATT_MTU_UPDATED_EVENT (0x7F)
typedef struct
{
uint16 MTU; //!< new MTU size
} attMtuUpdatedEvt_t;
210 GATT and ATT API SWRU393E – October 2010 – Revised March 2018
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
D.6 GATT Commands and Corresponding ATT Events
The following table lists the possible commands that may have caused an event.
SWRU393E – October 2010 – Revised March 2018 GATT and ATT API 211
Submit Documentation Feedback
Copyright © 2010–2018, Texas Instruments Incorporated
Commands www.ti.com
Appendix E
SWRU393E – October 2010 – Revised March 2018
GATTServApp API
This section details the API of the GATTServApp defined in gattservapp_util.c. These API are only the
public commands that must be called by the profile and/or application.
The return values described in this section are only the possible return values from processing the
command. If ICall is incorrectly configured or does not have enough memory to allocate a message, the
command is never get processed by the Bluetooth low energy stack. In this case, one of the ICall return
values from Appendix I are returned.
E.1 Commands
GAPBondMgr API
This section details the API of the GAPBondMgr defined in gapbondmgr.c. Many of these commands are
called by the GAPRole or the Bluetooth low energy stack and do not need to be called from the
application. The return values described in this section are only the possible return values from processing
the command. If ICall is incorrectly configured or does not have enough memory to allocate a message,
the command is never processed by the Bluetooth low energy stack. In this case, one of the ICall return
values from Appendix I is returned.
F.1 Commands
Parameters connHandle – connection handle of the connected device or 0xFFFF for all devices in
database
setParam – TRUE to set the service change indication, FALSE to clear it
Parameters connectionHandle – connection handle of the connected device or 0xFFFF for all
devices in database
attrHandle – attribute handle
value – characteristic configuration value
Parameters connectionHandle – connection handle of the connected device or 0xFFFF for all
devices in database
status – SUCCESS if passcode is available, otherwise see
SMP_PAIRING_FAILED_DEFINES in gapbondmgr.h
passcode – integer value containing the passcode
NOTE: This is an advanced feature and must not be called unless the normal
GAP Bond Manager task ID registration is overridden.
Parameters id – NV ID
len – lengths in bytes of item
bStatus_t GAPBondMgr_syncResolvingList( void ) Add all device address and IRK pairs from bond
records to the controller.
F.3 Callbacks
These callbacks are functions whose pointers are passed from the application to the GAPBondMgr so that
it can return events to the application as required. They are passed as the following structure.
typedef struct
{
pfnPasscodeCB_t passcodeCB; //!< Passcode callback
pfnPairStateCB_t pairStateCB; //!< Pairing state callback
} gapBondCBs_t;
L2CAP API
G.1 Commands
This section describes the API related to setting up bidirectional communication between two Bluetooth
low energy devices using L2CAP connection orientated channels. The return values described in this
section are only the possible return values from processing the command. If ICall is incorrectly configured
or does not have enough memory to allocate a message, the command is never processed by the
Bluetooth low energy stack. In this case, one of the ICall return values from Appendix I is returned.
HCI API
This section describes the vendor specific HCI Extension API, the HCI LE API, and the HCI Support API.
An example is provided when more detail is required. The return values for these commands is always
SUCCESS unless otherwise specified. This return value does not indicate successful completion of the
command. These commands result in corresponding events that must be checked by the calling
application. If ICall is incorrectly configured or does not have enough memory to allocate a message, the
command is never processed by the Bluetooth low energy stack. In this case, one of the ICall return
values from Appendix I is returned.
Table H-2 maps the stack APIs with the function names from the TI HCI Vendor Specific API Guide.
NOTE: This command does not return any events but has a meaningful return
status and requires additional checks in the task function as described in
Section 4.3.2.1.
NOTE: This command does not return any events but it has a meaningful return
status and requires additional checks in the task function as described in
Section 4.3.2.1.
NOTE: If all the parameters are NULL, the command is assumed to have
originated from the transport layer. Otherwise, the command is assumed
to have originated from a direct call by the application and any non-NULL
pointer is used.
NOTE: The RF channel is specified, not the Bluetooth low energy frequency.
The RF channel can be obtained from the Bluetooth low energy
frequency as follows: RF channel = (Bluetooth low energy frequency –
2402) ÷ 2.
When the HCI_EXT_EndModemTest is issued to stop this test, a
controller reset occurs.
NOTE: The RF channel, not the Bluetooth low energy frequency, is specified by
txFreq. The RF channel can be obtained from the Bluetooth low energy
frequency as follows: RF channel = (Bluetooth low energy frequency –
2402) ÷ 2.
When the HCI_EXT_EndModemTest is issued to stop this test, a
controller reset occurs.
The device transmits at the default output power (0 dBm) unless changed
by HCI_EXT_SetTxPowerCmd.
NOTE: The counters are 16 bits. At the shortest connection interval, 16-bit
counters provide a little over 8 minutes of data.
#define LL_MAX_NUM_DATA_CHAN 37
// Packet Error Rate Information By Channel
typedef struct
{
uint16 numPkts[ LL_MAX_NUM_DATA_CHAN ];
uint16 numCrcErr[ LL_MAX_NUM_DATA_CHAN ];
} perByChan_t;
NOTE: The reset occurs after a 100-ms delay to allow the correspond event to
be returned to the application.
Only a hard reset is allowed. A soft reset causes the command to fail.
See Section 8.2.
Parameters bdAddr – A pointer to a buffer to hold the address of this device. An invalid address (that
is, all FFs) restores the address of this device to the address set at initialization.
NOTE: This command is only valid for a slave controller. When the host
transmits data, the controller (by default) ensures the packet is sent over
the link layer connection with minimal delay, even when the connection is
configured to use slave latency. That is, the transmit response time is at
or less than the connection interval (instead of waiting for the next
effective connection interval due to slave latency). This transmit time
results in lower power savings because the link layer may wake to
transmit during connection events that would have been skipped due to
slave latency. If saving power is more critical than fast transmit response
time, you can disable this feature using this command. When disabled,
the transmit response time is at or less than the effective connection
interval (slave latency + 1× the connection interval).
Parameters localFeatures – A pointer to the feature set where each bit where each bit corresponds
to a feature
0: Feature is not used
1: Feature can be used
NOTE: This command can be issued either before or after one or more
connections are formed. The local features set in this manner are only
effective if performed before a feature exchange procedure has been
initiated by the master. When this control procedure has been completed
for a particular connection, only the exchanged feature set for that
connection is used. Because the link layer may initiate the feature
exchange procedure autonomously, use this command before the
connection is formed. The features are initialized by the controller upon
start-up. You are unlikely to require this command. The defined symbols
for the feature values are in ll.h.
NOTE: The function applies only to devices acting in the slave role. The function
can be helpful when the slave application receives something that must
be handled without delay. The function does not change the slave latency
connection parameter; the device wakes up for each connection event.
Parameters txPower – transmit power of the device, one of the following corresponding events
ICall API
I.1 Commands
The ICall commands that are useful from the application task are defined in Section 4.2
Revision History
NOTE: Page numbers for previous revisions may differ from page numbers in the current version.
• Updated Document Title from CC2640 and CC2650 SimpleLink™ Bluetooth® low energy Software Stack 2.2.1 to CC26x0
SimpleLink™ Bluetooth® low energy Software Stack 2.2.x. ....................................................................... 11
• Updated link locations in References. ................................................................................................ 11
• Updated Bluetooth® low energy Software Stack 2.2.1 to Bluetooth® low energy Software Stack 2.2.x. ...................... 11
• Updated TI CC26xx Technical Reference Manual to TI CC26x0 Technical Reference Manual. ............................. 11
• Updated Measuring Bluetooth Smart Power Consumption Application Report to Measuring Bluetooth Low Energy Power
Consumption Application Report ...................................................................................................... 11
• Updated from Device Information Service (Bluetooth Specification), Version 1.0 (24-May-2011) to Adopted GATT Profile
and Service Specifications. ............................................................................................................. 11
• Removed Getting Started with Bluetooth LE Development section. .............................................................. 12
• Updated Note. ............................................................................................................................ 16
• Updated Installing the SDK section.................................................................................................... 22
• Updated Bluetooth low energy SDK version from 2.2.1 to 2.2.x. .................................................................. 22
• Updated IAR EW ARM IDE version from 7.70.2 to 'As Specified in Release Notes'. .......................................... 22
• Updated Code Composer Studio IDE version from 6.2 to 'As Specified in Release Notes'. .................................. 22
• Updated TI-RTOS version from 2_20_01_08 to 'As Specified in Release Notes'. .............................................. 22
• Updated XDC Tools version from 3_32_00_06_core to 'As Specified in Release Notes'. ..................................... 22
• Updated Sensor Controller Studio version from 1.3.1 to 'Latest (check release notes for compatibility)'. ................... 22
• Updated BTool PC Application version from 1.41.11 to 'As installed'. ............................................................ 22
• Updated SmartRF Flash Programmer 2 version from 1.7.4 to 'Latest'. .......................................................... 22
• Updated SmartRF Studio 7 version from 2.3.1 to 'Latest'. ......................................................................... 22
• Updated Configure CCS section. ...................................................................................................... 26
• Updated Board File section. .......................................................................................................... 132
• Updated POWER_SAVING Description in Application Preprocessor Symbols table. ........................................ 158
• Updated Note. .......................................................................................................................... 199
Revision History
• Updated Bluetooth® low energy Software Stack 2.2.0 to Bluetooth® low energy Software Stack 2.2.1. ...................... 11
• Updated link urls. ........................................................................................................................ 11
• Updated Bluetooth low energy SDK version from 2.2.0 to 2.2.1. ................................................................. 22
• Updated IAR EW ARM IDE version from 7.50.3 to 7.70.2. ........................................................................ 22
• Updated Code Composer Studio IDE version from 6.1.2 to 6.2. .................................................................. 22
• Updated TI-RTOS version from 2_18_00_03 to 2_20_01_08. .................................................................... 22
• Updated Sensor Controller Studio version from 1.2.1 to 1.3.1. .................................................................... 22
• Updated BTool PC Application version from 1.41.09 to 1.41.11................................................................... 22
• Updated SmartRF Flash Programmer 2 version from 1.7.3 to 1.7.4. ............................................................. 22
• Updated Installation Details image. ................................................................................................... 27
• Updated Import an Existing Project section. ......................................................................................... 28
• Updated Code example. ................................................................................................................ 49
• Updated Configuring the GAP Layer section. ........................................................................................ 72
• Added Queued Writes section. ........................................................................................................ 95
• Updated HCI section. .................................................................................................................. 121
• Added HCI_ERROR_CODE_REMOTE_USER_TERM_CONN value to Configurable Parameters table. ................. 192
• Added GAPBOND_SECURE_CONNECTION ParamID to Configurable Parameters table.................................. 220
Revision History
Revision History
Texas Instruments Incorporated (‘TI”) technical, application or other design advice, services or information, including, but not limited to,
reference designs and materials relating to evaluation modules, (collectively, “TI Resources”) are intended to assist designers who are
developing applications that incorporate TI products; by downloading, accessing or using any particular TI Resource in any way, you
(individually or, if you are acting on behalf of a company, your company) agree to use it solely for this purpose and subject to the terms of
this Notice.
TI’s provision of TI Resources does not expand or otherwise alter TI’s applicable published warranties or warranty disclaimers for TI
products, and no additional obligations or liabilities arise from TI providing such TI Resources. TI reserves the right to make corrections,
enhancements, improvements and other changes to its TI Resources.
You understand and agree that you remain responsible for using your independent analysis, evaluation and judgment in designing your
applications and that you have full and exclusive responsibility to assure the safety of your applications and compliance of your applications
(and of all TI products used in or for your applications) with all applicable regulations, laws and other applicable requirements. You
represent that, with respect to your applications, you have all the necessary expertise to create and implement safeguards that (1)
anticipate dangerous consequences of failures, (2) monitor failures and their consequences, and (3) lessen the likelihood of failures that
might cause harm and take appropriate actions. You agree that prior to using or distributing any applications that include TI products, you
will thoroughly test such applications and the functionality of such TI products as used in such applications. TI has not conducted any
testing other than that specifically described in the published documentation for a particular TI Resource.
You are authorized to use, copy and modify any individual TI Resource only in connection with the development of applications that include
the TI product(s) identified in such TI Resource. NO OTHER LICENSE, EXPRESS OR IMPLIED, BY ESTOPPEL OR OTHERWISE TO
ANY OTHER TI INTELLECTUAL PROPERTY RIGHT, AND NO LICENSE TO ANY TECHNOLOGY OR INTELLECTUAL PROPERTY
RIGHT OF TI OR ANY THIRD PARTY IS GRANTED HEREIN, including but not limited to any patent right, copyright, mask work right, or
other intellectual property right relating to any combination, machine, or process in which TI products or services are used. Information
regarding or referencing third-party products or services does not constitute a license to use such products or services, or a warranty or
endorsement thereof. Use of TI Resources may require a license from a third party under the patents or other intellectual property of the
third party, or a license from TI under the patents or other intellectual property of TI.
TI RESOURCES ARE PROVIDED “AS IS” AND WITH ALL FAULTS. TI DISCLAIMS ALL OTHER WARRANTIES OR
REPRESENTATIONS, EXPRESS OR IMPLIED, REGARDING TI RESOURCES OR USE THEREOF, INCLUDING BUT NOT LIMITED TO
ACCURACY OR COMPLETENESS, TITLE, ANY EPIDEMIC FAILURE WARRANTY AND ANY IMPLIED WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF ANY THIRD PARTY INTELLECTUAL
PROPERTY RIGHTS.
TI SHALL NOT BE LIABLE FOR AND SHALL NOT DEFEND OR INDEMNIFY YOU AGAINST ANY CLAIM, INCLUDING BUT NOT
LIMITED TO ANY INFRINGEMENT CLAIM THAT RELATES TO OR IS BASED ON ANY COMBINATION OF PRODUCTS EVEN IF
DESCRIBED IN TI RESOURCES OR OTHERWISE. IN NO EVENT SHALL TI BE LIABLE FOR ANY ACTUAL, DIRECT, SPECIAL,
COLLATERAL, INDIRECT, PUNITIVE, INCIDENTAL, CONSEQUENTIAL OR EXEMPLARY DAMAGES IN CONNECTION WITH OR
ARISING OUT OF TI RESOURCES OR USE THEREOF, AND REGARDLESS OF WHETHER TI HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
You agree to fully indemnify TI and its representatives against any damages, costs, losses, and/or liabilities arising out of your non-
compliance with the terms and provisions of this Notice.
This Notice applies to TI Resources. Additional terms apply to the use and purchase of certain types of materials, TI products and services.
These include; without limitation, TI’s standard terms for semiconductor products http://www.ti.com/sc/docs/stdterms.htm), evaluation
modules, and samples (http://www.ti.com/sc/docs/sampterms.htm).
Mailing Address: Texas Instruments, Post Office Box 655303, Dallas, Texas 75265
Copyright © 2018, Texas Instruments Incorporated