Ti_ble low-power Bluetooth

Source: Internet
Author: User

Introduction to Ti low-power Bluetooth (BLE)

This document is translated and modified from reference materials: cc2540bluetooth low energy software developer's Guide (rev. B). Some images are directly referenced in this document. First draft to be modified.

I. Overview

1. Ble Bluetooth protocol stack structure

Figure 6 ble Bluetooth protocol stack structure

There are two parts: controller and host. For Bluetooth prior to 4.0, the two parts are separated. All profiles (or scripts used to define the role of a device or component) and applications are built on the gap or GATT. The following describes the underlying components of the structure chart.

· PHY layer,Workshop, 1 Mbps adaptive frequency-hopping gfsk (Gaussian Frequency Shift Keying), running at 2.4 GHz without certificate

· The ll layer is the RF controller,Control RoomThe control device is in either of the following statuses: Preparation, broadcast, monitoring/scanning, initialization, and connection. Five status switches are described as follows: when no connection is established, the device broadcasts information ("I am coming" to the neighbors "), another device keeps listening or scanning as needed (check if there are any neighbors who can chat and say "Ha, you're here "), the connection between the two devices is initialized (several chairs are moved to the yard), and the devices are connected (chatting ). The device that initiates the chat is the master device. The device that receives the chat is the slave device. Only one opinion leader can be found in the same chat, that is, the master device and the slave device cannot be switched.

· HCI Layer: Interface Layer,Ministry of CommunicationsTo provide software application interfaces (APIS) for the host and external hardware control interfaces, which can be controlled by serial ports, SPI, and USB.

· L2CAP layer,Logistics Department, Luggage Packing Box unpacking, providing data encapsulation Service

· SM layer,Security DepartmentProvides pairing and Key Distribution for secure connections and data exchange.

· ATT layer,WarehouseResponsible for data retrieval

· GATT layer,Cashier/warehouse front-endThe cashier is responsible for handling up and dealing with applications, while the warehouse front-end is responsible for handing down the retrieval task sub-process to the ATT warehouse. The key task is to provide a proper profile structure for the retrieval work, profile is composed of retrieval keywords (characteristics.

· Gap layer,SecretariatProvides application interfaces to superiors, and manages all levels of functional departments at lower levels, especially instruct the ll-layer control room to switch among the five States.

TI's device can implement all the components of the ble Bluetooth protocol stack structure, including applications, on a single chip.

2. Task Scheduling-osal Operating System Abstraction Layer

Just as a company has established multiple offices and factories to achieve capacity expansion and product diversification, Bluetooth has also enabled function expansion to connect to multiple devices or achieve multiple functions, this leads to scheduling issues. Although the software and protocol stack can be expanded, there is only one execution department at the bottom.

To achieve multi-event and multi-task switching, We need to package the corresponding applications of events and tasks, as well as their related support services such as "office" and "Factory, and an osal abstraction layer, similarSubsidiaries.

3. device transformation-HAL Hardware Abstraction Layer

If the software and hardware are low-coupling, the software can be applied to another hardware without modification or few changes, which facilitates hardware transformation, upgrade, and migration. The HAL Hardware Abstraction Layer is used to abstract various hardware resources and inform the software. This function is similar to the H header file that defines hardware resources for embedded system device drivers. Its role is similar to that of modern factories.Device Management Department.

4. Ble low-power Bluetooth system architecture

Figure 7 ble low-power Bluetooth system architecture diagram. The task in the figure is described by the 6ble Bluetooth protocol stack diagram.

Ble low-power Bluetooth Software has two main components: the osal Operating System Abstraction Layer and the HAL Hardware Abstraction Layer. Multiple Task tasks and events work under the osal management, each task and event has three components: BLE protocol stack, profiles, and applications.

Figure 7 can also be compared with the modern factory model, as shown in figure 8.

Figure 8 ble low-power Bluetooth Software consists of five main components used in the modern factory architecture for analogy.

With the introduction above, I will give a brief introduction to osal, Hal, and ble.

Ii. osal Operating System Abstraction Layer

1. software functions are implemented by events managed by osal

As the scheduling core, osal is implemented by ble protocol stack, profile definition, and all applications. Osal is not a traditional operating system, but a loop that allows software to establish and execute events.

Software functions are implemented by task events. To create a task event, you need:

· Create a task identifier task id;

· Write the task initialization routine process and add it to the osal initialization process. This means that the function cannot be dynamically added after the system is started;

· Compile a task processing program;

· Provide message service if necessary.

Each layer of the ble protocol stack is implemented by using an osal task. Because the time requirement of the ll control room is the most urgent, the task has the highest priority. To implement task management, osal is implemented through messageprocess, storage management, Timer timing, and other additional services.

2. System Startup Process

To use osal, start a process named osal_start_system at the end of the main function. This process calls the osalinittasks (to start the System), which is determined by a specific application ). Osalinittasks calls the startup processes at each layer of the ble protocol stack one by one to initialize the protocol stack. Then, set the 8bit task ID of a task, jump into the loop and wait for the task to be executed, and the system starts successfully.

3. Task events and event handling

Process Priority and task id

· The task priority is determined by the task id. The smaller the task id, the higher the priority.

· The task priorities at each layer of the ble protocol stack are higher than those of applications

· After the Protocol Stack is initialized, the sooner the task is called in, the higher the task id and the lower the priority. That is, the system tends to process new tasks.

Event variables and flag

Each event task is identified by the corresponding 16bit event variable, and the event status is identified by the flag. If the event handler has been completed, but the flag is not removed, osal will think that the event has not been completed and will not return in the program. For example, in the simplebleperipheral instance project, when the event start_device_evt occurs, its processing function simplebleperipheral_processevent runs. After the event is completed, 16bit event variables are returned and the flag sbp_start_device_evt is cleared.

Event Processing Form

Each time an osal event detects a task event, its corresponding processing process is added to the event processing form consisting of processing process pointers. The form is called taskarr (taskarray ). The order of event processes in taskarr corresponds to the order of task IDs in the osalinittasks initialization function.

Event Scheduling Method

There are two methods. The simplest method is to use the osal_set_event function (the function prototype is in osal. in this function, you can set the task id and event flag like defining function parameters. The second method is to use the osal_start_timerex function (the function prototype is in the osal_timers.h file, the third parameter, osal_start_timerex, in milliseconds indicates that the event must be processed by a timer within the specified time.

4. Storage Management

Similar to the LINUX embedded system memory allocation C function mem_alloc, osal uses osal_mem_alloc to provide basic storage management, but osal_mem_alloc only has one parameter for defining the number of bytes. The corresponding memory release function is osal_mem_free.

5. inter-process communication-implemented through message mechanism

Different subsystems communicate through the osal message mechanism. The message is data, and the data type and length are not limited.

The message sending and receiving process is described as follows:

Receive information. Call the osal_msg_allocate function to create the memory occupied by messages (including the osal_mem_alloc function). Specify the space size for the function. The function returns the memory space address pointer, the pointer can be used to copy the required data to the space.

To send data, call the function osal_msg_send. You must specify the target task to send data to the function. osal notifies the target task by the flag sys_event_msg. The processing function of the target task calls osal_msg_receive to receive the data sent. We recommend that each osal task have a message processing function. Each time a task receives a message, it determines the type of the message to be processed by this task. After receiving and processing the message, call the osal_msg_deallocate function to release the memory (the osal_mem_free function is already included ).

Iii. Hardware Abstraction Layer HAL

After the new hardware platform is ready, you only need to modify Hal without modifying other components and applications of the protocol stack on Hal.

Iv. Ble low-power Bluetooth protocol stack

1. Ble Library File

The Ti Bluetooth protocol stack is provided by a single library file without source code, so it is not described in detail. For TI's ble instance applications, this separate library file is enough to list all the library files.

Figure 9 ble library files

Since the gap and GATT interact directly with the user program, the following describes the gap and GATT in the library files.

2. Gap Secretariat

2.1 role (Service, function)

Gap runs in one of the following four roles:

· Broadcaster-I am here, but I can only stay at a distance and cannot be connected.

· Observer-to see who is there, but I am only watching and not connecting.

· Peripheral peripherals (slave machine)-I am here, and whoever wants me to go with, protocol stack single-layer connection.

· Central core (host)-to see who is there and who is willing to walk with me, I will take her/him, protocol stack single-layer or multi-layer connections, currently supports up to three simultaneous connections.

Although the indicator shows that ble can assume multiple roles at the same time, only peripheral roles are supported by default in the ble instance application provided by TI. Each role is defined by a roleprofile.

2.2 connection

Master-slave connection process

A typical low-power Bluetooth system includes both peripherals and the core (host). The connection process is as follows:

The peripheral role sends its own information (device address, name, etc.) to the external device. After receiving the broadcast information, the host sends a scan request to the peripheral device to respond to the host's request, the connection is established.

Connection Parameters

The main features include connectioninterval, slavelatency, and supervisiontimeout.

· Communication gap-Bluetooth communication is intermittent and frequency hopping. Different sub-bands may be selected for each connection. The advantage of frequency hopping is to avoid channel congestion. The advantage of intermittent connection is to save power consumption. The communication gap refers to the time interval between two connections. The interval is a basic unit of 3200 Ms. The minimum unit is 6 and the maximum unit is. The smaller the gap, the more timely the communication is, the lower the power consumption is.

· Peripheral contempt-after the peripherals establish a connection with the host, the host will always send greetings to the peripherals on a regular basis when nothing happens. The peripherals are too lazy to handle the issue, and the information sent by these hosts will float like a cloud. The number of Connection events that can be ignored ranges from 0 to 499, up to 32 seconds. Valid connection Gap = connection gap x (1 + peripherals despise ).

· Maximum patient wait time-This refers to the maximum waiting time allowed by the host to create a connection, during which connection is continuously attempted. The range is 10 ~ 3200 basic communication gap units (1.25 mS ).

The advantages and disadvantages of the above three parameter size settings are obvious, and they also float here. For connection parameter settings, see section 5.1gap peripherals.

Connection exception handling

For example, the connection is abnormal. For example, if the host uses a parameter that is not comfortable with the slave machine to request a connection, the master and slave machine are already connected, but the slave machine has an idea. Modify the parameter treaty. The "connectionparameter update request" is used to solve the problem, which is handled by the L2CAP "Logistics Department of the receiving room. The connection parameters are described above and will not be described.

Encryption Processing

Implement pairing and use keys to encrypt authorized connections. A typical process is that the peripherals request a passkey to the host for pairing. After the host sends the correct password, the connection communication is verified by switching the password between the master and slave hosts. Because Bluetooth communication is intermittent communication, if an application needs to communicate frequently, and each communication requires a new connection request, it will be laborious. For this reason, the gap security guard (SM, security profile) A long-term visa (long-termset of keys) is provided, called bonding, which makes the process of establishing a connection and customs clearance easy and quick.

3. Cashier GATT

GATT is responsible for data interaction between two devices. There are two roles: the Cashier (gattclient) and the Bank (gattserver). The bank provides funds and the cashier withdraws money from the bank. Banks can face multiple cashiers at the same time. These two roles are irrelevant to those of the Master/Slave machine.

The GATT splits the work into several parts for implementation: The read keyword (characteristicvalue) and the descriptor (characteristicdescriptor), used to search for and extract data from the warehouse. Write read keywords and descriptors.

The Service Department (API) of GATT Bank (gattserver) mainly provides two main functions: one is the service function, registering or destroying the Service (serviceattribute), and serves as the callback function (callbackfunction ); the second is the management function, which adds or deletes GATT banking services.

A role-defined script can define multiple roles at the same time. Each role's service, keyword, key value, Descriptor (Service, characteristic, characteristic value and descriptors) are all handled (attributes) format is saved on the service provided by the role. All services are an array of the gattattribute_t type, which is defined in the GATT. H. File.

4. General process of calling gap and GATT

· API call

· Protocol Stack response and return

· The protocol stack sends an osal message (data) to call corresponding task events

· Call a task to receive and process messages

· Message clearing

Taking the device initialization as the gap peripheral role as an example, the peripheral role is determined by its script (gapperipheral role profile), and the instance program is in the file peripheral. C.

· Call the API function gap_deviceinit.

· Gap checked and said, well, it can be initialized. the return value is success (0x00) and ble is notified to work.

· The ble protocol stack sends an osal message to the peripheral role script (peripheral roleprofile). The message content includes the eventvalue: gap_msg_event and the metric (opcodevalue, parameter ).

· The service task of the role script receives the event request sys_event_msg, indicating that a message is sent.

· The role script receives the message and disconnects it to the actual situation. Then, it converts the message data into a specific task and completes the corresponding work (here it is the gap deviceinitdoneevent_t ).

· The role script clears the message and returns it.

Another example: the GATT client device wants to read data from the GATT server, that is, the GATT cashier wants to get some money from the GATT bank.

· The application calls the GATT sub-process API function gatt_readcharvalue. The passed parameters are the connection handle, keyword handle, and the ID of its own task.

· GATT agreed to this request and returned value: Success (0x00). It tells ble that there is a job.

· The ble protocol stack sends a money withdrawal instruction to the bank next time it establishes a Bluetooth connection. When the bank says yes, we just have a clerk who has nothing to do with nail cutting, so he handed the money out to ble.

· Ble then converts the obtained wallet into an osal message and returns it to the application through the cashier GATT. The message contains the gatt_msg_event and modified att_read_rsp.

· The application receives the sys_event_msg event from osal, indicating that the money may arrive

· Applications receive messages, unpack and check, and take away the required money.

· In the end, the application destroys the packaging bags and returns the result.

5. Gap role script profiles

TI's ble instance application provides three gap role scripts, guard roles, and several GATT Cashier/Warehouse Management sample program service roles.

5.1 gap peripherals

Its API functions are defined in peripheral. H, including:

· Gaprole_advert_enabled-broadcast enabling.

· Gaprole_advert_data-information contained in the broadcast.

· Gaprole_scan_rsp_data-peripherals are used to reply to host scan requests.

· Gaprole_advert_off_time-indicates the duration for the peripheral to disable broadcast. If the value is zero, the broadcast is disabled indefinitely until the next broadcast enable signal arrives.

· Gaprole_param_update_enable-enable to automatically update the connection parameters, so that the connection parameters can be automatically adjusted when the peripheral connection fails to be reconnected.

· Gaprole_min_conn_interval-sets the minimum connection gap. The default value is 80 units (1.25 mS per unit ).

· Gaprole_min_conn_interval-sets the maximum connection gap. The default value is 3200 units.

· Gaprole_slave_latency-peripheral contempt parameter. The default value is zero.

· Gaprole_timeout_multiplier-maximum patient wait time. The default value is 1000.

The gaprole_startdevice function is used to initialize the gap peripheral role. Its unique parameter is gaprolescbs_t. this parameter is a struct containing two function pointers. The two functions are pfnstatechange and pfnrssiread, which indicate the status, the latter indicates that the request has been read.

More than 5.2 roles play simultaneously

In the previous article 5.1, the device is configured as a peripherals. Here, the devices are both peripherals and broadcasters. Methods: remove the definition scripts peripheral. C and peripheral. h from the previous documents, add new scripts peripheralbroadcaster. C and peripheralbroadcaster. H, and define the processor value (preprocessorvalue) plus_broadcaster.

5.3 gap host script

Similar to a peripheral script, the API functions of the host script are defined in central. H, including the GAP centralrole_getparameter, the gap centralrole_setparameter, and others. For example, the gap role_param_update_enable connection parameter automatically updates the enabling function, which is the same as that of the peripheral role.

The gapcentralrole_startdevice function is used to initialize the gap host role. Its unique parameter is gapcentralrolescbs_t. this parameter is a struct containing two function pointers. These two functions are eventcb and rssicb, which occur at each gap time, the former will be called, and the latter will indicate that the received data has been read.

5.4 gap binding manager script

Used to maintain long-term connections. Both peripheral configuration and host configuration are supported. After a pair connection is established, if it is bound to the Enable, the binding manager maintains the connection. Main Parameters include: gapbond_pairing_mode, gapbond_mitm_protection, gapbond_io_capabilities, gapbond_io_cap_display_only, and gapbond_bonding_enabled.

The gapbondmgr_register function is used to initialize the gap host role. Its unique parameter is gapbondcbs_t. this parameter is a struct containing two function pointers. The two functions are pairstatecb and passcodecb. The former returns the status, the latter is used to generate a 6-digit passcode during pairing ).

5.5 how to write a script to create (define) New roles (functions and services)

The script name is simplegatt profile, which contains simplegattprofile. C and simplegattprofile. h. It includes the following main API functions:

· Simpleprofile_addservice-the initialization process. It is used to add serviceattributes to the attributetable, and read and write back registers.

· Simpleprofile_setparameter-set the profile keyword (characteristics)

· Simpleprofile_getparameter-obtain the keyword of the configured script

· Simpleprofile_registerappcb

· Simpleprofile_readattrcb

· Simpleprofile_writeattrcb

· Simpleprofile_handleconnstatuscb

The script for this instance has five keywords:

· Simpleprofile_char1

·...

· Simpleprofile_char5

[End, to be modified]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.