Bluetooth protocol Analysis (7) Technical analysis of _ble connection

Source: Internet
Author: User
Tags sca

Turn from: Http://www.wowotech.net/bluetooth/ble_connection.html#comments1. Objective

People who know about Bluetooth know that in classic Bluetooth, staying connected (Connection) is a fairly resource-intensive (power and bandwidth) process. In particular, when there is no data transfer, the resources consumed are completely wasted. Thus, for many Bluetooth devices (especially power-sensitive devices), it is hoped that it will be able to disconnect during countless passes. However, because of the frequency hopping (hopping) and the physical channels (physical channel), the speed of the classic Bluetooth connection is unbearable (for several seconds). For those bursts of data transmission, a few seconds of connection delay is simply a disaster.

Therefore, when the Bluetooth sig developed the BLE specification, fully consider this aspect of the requirements, greatly simplifying the connection of the establishment process, so that the connection speed can reach the millisecond level (the fastest 3.75ms can be done). At the same time, the strategy of frequency hopping is adjusted to save power. At this point, BLE's connection-oriented communication has little additional cost compared to broadcast communications.

In the "Bluetooth Protocol Analysis (5) _ble Broadcast Communication related Technical analysis", we have a more comprehensive understanding of BLE broadcast communication, this article will continue to analyze and connection-oriented communication technology, including connection establishment and disconnection, ble frequency hopping (hopping) technology, link Layer's response, retransmission, flow control, and so on.

2. What constitutes a connection?

Before we begin, we answer a question: how do we establish a connection for both sides of the communication?

In the literal sense, a connection is established, which means:

Between the two, a dedicated channel is established, they can communicate anytime and anywhere.

Of course, in Bluetooth this resource limited communication system, channel can not be exclusive, back and second, time-sharing is also okay. Therefore, the connection is established in BLE, which is defined as:

During the agreed time period, both parties communicate to a specified physical channel.

Among them, "agreed time period", is the concept of cent. And "to the specified physical channel" is the concept of frequency hopping. The following analysis will be carried out around these two concepts.

In addition, and "Bluetooth Protocol Analysis (5) _ble Broadcast Communication related technical analysis" similar, we will also from link layer, HCI, gap three levels, respectively.

3. Link Layer3.1 Definition of role

Like classic Bluetooth, the protocol is a connected BLE device that defines two link layer roles: Master and slave. Master is the initiator of the connection (initiator), which determines the parameters associated with the connection (which is important, which is described in more detail later). Slave is the recipient of the Connection (advertiser) and can request (or recommend) connection parameters, but cannot be determined.

Note 1: Between two BLE devices, only one connection can be established.

Definition of 3.2 PDU

Unlike broadcast communications, connection-oriented communication uses a specific PDU, called the data Channel PDU, in the following format (LSB---->MSB):

Header (BITS) Payload (Variable size) MIC (+ bits)

The format of the 16bits header is as follows:

Llid (2 bits) NESN (1bit) SN (1 bit) MD (1 bit) RFU (3 bits) Length (8 bits)

There are two types of PDUs that are transmitted by the data channel, one of which is, called the LL data PDU, and the other control information called the LL control PDU. Llid is used to differentiate the types of PDUs, as described in the following 3.2.1 and 3.2.2.

NESN (Next expected Sequence number) and SN (Sequence number) for the answer (acknowledgement) and flow control during data transfer (flow control), Refer to the following 3.7 for details.

MD (more Data), used to close (or maintain) the connection, refer to the following 3.5 for details.

RFU (Reserved for future use).

Length, valid data lengths (payload+mic), only 8-bits, so the maximum data that the link layer can transmit is 255 bytes (251bytes with MIC), and if l2cap needs to transmit more data, Need to be transferred after subcontracting (this is also one of the main functions of L2CAP, refer to "Bluetooth Protocol Analysis (3) _ Bluetooth Low Power (BLE) protocol stack Introduction").

The payload is a valid data (PDU for Sdu,l2cap), and the length of the header is found to be a valid range of 0~255.

3.2.1 LL Data PDU

There are two types of LL Data PDUs:

Header in llid=01b, continuation fragment of a L2CAP message, or an Empty PDU. This type of PDU is either an incomplete L2CAP message (longer than 255, unpacking, not the first at this time), or an empty package (length of 0 in the header).

When llid=01b in the header, Start of an L2CAP message or a complete L2CAP message with no fragmentation. This type of PDU is either the first packet of the L2CAP message, or the complete L2CAP message that does not require unpacking, in either case the length in the header cannot be 0.

3.2.2 LL Control PDU

The llid=11b in the header indicates that this packet is a ll control PDU for controlling and managing ll connections. The payload format of LL control PDU is as follows:

Opcode (1 octet) Ctrldata (0 ~ octets)

Where opcode indicates the type of control & management packet, including:

Ll_connection_update_req, update the connection parameters;
Update of Ll_channel_map_req,channel MAP;
Ll_terminate_ind, a notification that the connection is about to be closed (the reason for the closure can be notified);
Ll_enc_req, LL_ENC_RSP, Ll_start_enc_req, LL_START_ENC_RSP, encryption-related requests, etc., refer to "BLUETOOTH specification Version 4.2 [Vol 6 , part B] ".

3.3 Establishment of the connection

For BLE, the process of connection creation is simple, including:

1) in the connectable State Equipment (advertiser), according to a certain period of broadcast Adv_ind or Adv_direct_ind package (can refer to "Bluetooth Protocol analysis (5) _ble Broadcast Communication related Technical analysis").

2) The active connected device (initiator), after receiving the broadcast packet, responds to a CONNECT_REQ request carrying parameters that determine the subsequent "communication timing", such as at which point in time, which physical channel to send and receive data, etc. Details are described later.

3) initiator automatically transitions to the connection state after issuing the CONNECT_REQ packet, becoming the master role (note: This is "automatic" and does not need to wait for the other party to respond). Similarly, after receiving the CONNECT_REQ request, The Advertiser automatically transitions to the connection state and becomes the slave role.

4) Thereafter, the two sides in accordance with the Connect_req parameters given the agreement, timed to switch to a physical channel, according to Master->slave and then Slave->master order, send and receive data, until the connection disconnects.

Master needs to define and connect the relevant parameters in the payload of the Connect_req PDU when making connection requests. The payload format is as follows:

Inita (6 octets) Adva (6 octets) LL Data (octets)

Where Inita and Adva are the Bluetooth addresses of master and slave respectively, LL data contains all the connection parameters, including:

CRCINIT 
(3 octets)
(1 octet) WINOFFSET 
(2 octets
INTERVAL 
(2 align= width= "center" and "all" >latency
(2 octets)
TIMEOUT 
(2 octets)
CHM 
(5 octets)
(5 bits) SCA 
(3 bits)

AA,LL Connection's access Address, which needs to be unique between different device combinations and follows some principles, can be found in "BLUETOOTH specification Version 4.2 [Vol 6, part B]".

Crcinit, an initial value for the CRC calculation, generated randomly by the link layer.

Winsize and Winoffset, Transmitwindowsize and Transmitwindowoffset, are used to determine the time window in which the two parties send and receive data (the concept of cent mentioned in chapter 2nd). The following 3.4 subsections are described in detail.

Conninterval, the full name is Conninterval, connecting the two sides to send and receive data cycle. Since a master may establish a connection with more than one slave, the channel resources of Bluetooth cannot be monopolized by a ll connection, so there may be multiple connections to send and receive data during a transceiver cycle (a specific time window, determined by Transmitwindowoffset). The following 3.4 subsections are described in detail.

Latency and timeout, full name is connslavelatency and connsupervisiontimeout, and connection timeout, automatic disconnection, refer to the description of section 3.4.

The full name of the CHM is the channel map, which identifies the currently used and unused physical channel. Hop's full name is Hopincrement, which, together with the CHM, determines the frequency hopping algorithm in the data transfer process, with reference to the description of section 3.6.

SCA (Sleep clock accuracy), which defines the worst master sleep clock accuracy, can be found in "BLUETOOTH specification Version 4.2 [Vol 6, part B]", which is no longer described in detail.

3.4 Communication Process After the connection is established

The 3.3 section mentions, when the master sends the/slave receives the Connect_req, then automatically enters the connection state, that both sides in the time of sending and receiving data window how OK? Refer to Picture 1 and picture 2 below:

Picture 1 ble Connection timing---master view

Picture 2 ble Connection timing---slave view

1) from the master's point of view, when it emits connect_req, it will be between 1.25 Ms + Transmitwindowoffset to 1.25ms + Transmitwindowoffset + transmitwindowsize, Sends the first packet (m->s). Similarly, after receiving Connect_req, slave will also receive packet (M->S) in the corresponding time interval.

A) Transmitwindowoffset can control which period of time the LL connection uses to communicate, thus guaranteeing multiple connections between the same master and multiple slave, which can communicate with each other (time-division). The range of values for Transmitwindowoffset is 0 ms to Conninterval (Conninterval is described later).

b) from the master issued Connect_req, to slave received connect_req, there is a certain time delay, it takes a certain time window (transmitwindowsize), To ensure that the first packet can be sent and received correctly. Transmitwindowsize must be a multiple of 1.25ms, the minimum value is 1.25 MS, the maximum value is (connInterval-1.25 ms), but not more than 10ms.

c) Under normal circumstances, all "m->s" packets should not be sent more than transmitwindowsize, in order to set aside S->m time. But the first packet exception (see picture 1 above).

2) After Master has issued the first packet, it will be the starting point (called the anchor points), with Conninterval as the period, followed by the subsequent packet (m->s), and Slave (packet) received S->m , refer to Picture 1 above.

A) such a conninterval-cycle (M->s), receive (S->M) combination (possibly multiple), called the connection Event. So the basis of BLE for connection-oriented communication is the connection Event.

b) The size of the conninterval determines the period of data transmission. For a connection, each cycle can only have one time to send and receive, so the choice of conninterval directly determines the speed of data transmission. The BLE protocol stipulates that the Conninterval must be a multiple of 1.25ms, and the range is 7.5ms~4s.

3) Slave If you do not receive the first packet (m->s), you will start with 1.25 ms + Transmitwindowoffset, wait for Conninterval, and try to receive it again until you receive it. After the slave receives the packet, the point in time to receive the packet is the starting point (anchor points), the conninterval is the period, then the subsequent packet (M->s) is received, and the packet is sent to master (S- >m), refer to Picture 2 above.

Note 2, about the rate of data transfer:
By the above communication process, the BLE connection-oriented communication rate is determined by conninterval and the amount of data transmitted in each connection event.
From the above 3.2 description, LL Data PDU payload can not exceed 255 (251) bytes, but considering the efficiency of a transmission, error handling and other factors, the specific link layer will not use such a large packet. Correspondingly, in order to improve the transmission speed, it is common to transfer multiple packet in a connection event. For iOS, for example, it may transmit 6 packets in a connection event, with a length of 20bytes per packet.
In addition, many platforms in order to ensure that their own performance as master, will limit the minimum value of Conninterval, iOS, for example, the minimum value is 30ms. Therefore, it can be estimated that the corresponding transfer rate of 20B * 6/30ms = 32kbps, is quite slow.

Note 3:ble connection-oriented communication is the use of frequency hopping technology, that is, each connection Event, will use different physical channel to send and receive data, the specific frequency hopping mechanism, can refer to the introduction of 3.6 subsections.

3.5 Control and management of the connection

After the connection is established, master or slave can use the link Layer control Protocol (LLCP) to manage the connection through the LL control PDU, including:

Connection update Procedure, connection parameters (including conninterval,connslavelatency,connsupervisiontimeout) updated notifications. Can only be initiated by master.

Channel Map update Procedure, updating channel map. Can only be initiated by master.

Encryption Procedure, the connection is encrypted and can be initiated by master or slave.

Termination Procedure, disconnect.

Connection Parameters Request Procedure, requested to update the connection parameters (Conninterval,connslavelatency,connsupervisiontimeout), Slave or master can be initiated, and connection Update procedure different is that this is a negotiation process, not necessarily be able to succeed.

LE Ping Procedure, similar to the ping operation in the network protocol.

Wait a minute. No further details are available, refer to "BLUETOOTH specification Version 4.2 [Vol 6, part B]".

3.6 Connection Timeout and disconnection

There are two reasons for BLE connection disconnection: One is expected, the active disconnection, at this time will walk 3.4 section refers to the termination procedure process, the second is some unexpected reasons caused by the time-out disconnection, such as distance exceeded, suffered serious interference, sudden power loss and so on.

For the first kind, it is the normal process within the agreement, there is nothing to say. For the second, you need some timeout mechanism to detect this write exception, as follows.

1) The link Layer of master and slave will start a timer named Tllconnsupervision, which resets every time a valid packet is received.

2) The connection establishment process, if the tllconnsupervision more than 6 * Conninterval (not received the first packet), it is considered that the connectivity establishment failed.

3) After the connection is successful, if tllconnsupervision exceeds connsupervisiontimeout, the link loss is executed and the execution time-out is broken. Connsupervisiontimeout is a configurable parameter with a range of 100ms~32s and cannot be greater than (1 + connslavelatency) * Conninterval * 2.

4) The BLE protocol allows slave to ignore the "connslavelatency" Connection Event, during which time the slave does not need to send and receive packets, nor does it increase tllconnsupervision, thus causing a time-out break. Connslavelatency is an integer, and the valid range should be between 0 to ((Connsupervisiontimeout/(CONNINTERVAL*2))-1) and not greater than 500.

Note 4:connslavelatency is a very useful parameter that allows slave to ignore some connection Event when data communication is infrequent, and then sleeps longer and saves power.

3.7 Frequency hopping (hopping) strategy

BLE frequency hopping strategy is very simple, that is: Every connection Event, replace the physical Channel, of course, master and slave need to follow the same convention to replace, otherwise it will not be able to communicate. The agreement is as follows:

Figure 3 ble frequency hopping strategy

1) First, use a basic algorithm, using Lastunmappedchannel and hopincrement, to calculate the Unmappedchannel.

A) Lastunmappedchannel the value at the beginning of the connection is 0, and each time connection event calculates a new Unmappedchannel, the Lastunmappedchannel is updated.

b) The hopincrement is randomly assigned by master when the connection is established, ranging from 5 to 16 (refer to hop in 3.3).

c) the algorithm for determining unmappedchannel is: Unmappedchannel = (lastunmappedchannel + hopincrement) mod 37, which is essentially every "hopincrement" A channel to take once, quite straightforward and simple.

2) After calculating the Unmappedchannel, find the current channel map and check whether the channel represented by Unmappedchannel is used channel. If it is, congratulations, find it.

Channel map is also specified by master, when the connection is established, or later when the channel map is update.

3) If not, will all used channel in ascending way see a table, the length of the table is Numusedchannels, with Unmappedchannel and numusedchannels do modulo operation, get an index, from the index , remove the corresponding channel from the table.

3.8 Response (acknowledgement) and streaming control (flow control)

From the description of Section 3.2, the LL Data PDU header, there are NESN (Next expected Sequence number) and SN (Sequence number) two tags, using them, can be easily in the link Layer realizes the mechanism of reply, retransmission, flow control and so on.

To implement these functions, the link layer creates two variables for each connection, Transmitseqnum and Nextexpectedseqnum (for the SN/NESN bit of the packet, we simply call them SN and NESN), And when the connection is established, they are initialized to 0.

The SN is used to identify the packets sent out by the local device (Link Layer).

NESN is the peer device (Link Layer) that is used to answer the packet sent by the local device, or to request a local device to resend the packet.

When you send and receive packet, the Link layer follows the following principles (which can be combined with the following image 4):

Note 5: The following picture 4 is a screenshot from "BLUETOOTH specification Version 4.2 [Vol 6, part B]", but there is a problem with the spec, and I corrected it with a red font. In addition, this picture is very ambiguous, difficult to understand, I will explain below.

1) either Master or slave, when sending packet, the current SN and NESN are copied to the SN and NESN bits of packet.

2) either Master or slave, when a packet is received, the NESN bit of the packet is compared to the local SN: If the same, the packet is a NAK packet sent to the end device (Request re-send), You need to resend the old packet, and if it is different, the ACK packet sent to the end device (the data is properly received), you need to add the local SN plus 1, and then send the new packet.

A) The above procedure can refer to the left part of picture 4 below.

b) The local SN, which represents the packet that the local device has sent out, and the NESN bit in packet, represents the packet that the peer device expects the local device to send. If the two are the same, the other side expects to send the next packet, and we have sent the same packet, so it is a nak signal, requesting a resend. If they are different, the other device expects to send a new packet, which means that the last packet we sent has been successfully received, so we can add 1 to the local SN.

3) either Master or slave, when a packet is received, the SN bit of the packet is compared with the local NESN: If the same, the description is a new packet, receive, while the local NESN plus 1; It is an old packet, and nothing needs to be dealt with.

A) The above procedure can refer to the right part of picture 4 below.

b) The SN bit in the packet, which represents the packet that the peer device is sending, and the NESN of the local device, which represents the packet that the local device expects to send to the end device. If the two are the same, then it is a desired packet (new), you can accept the packet and add the expected value by 1 (NESN plus 1). If they are different, it is not the packet that the local device expects, nothing is done.

4) above 2) and 3) Two steps are independent of each other, so a NAK packet may also carry new data, and vice versa.

5) When a device cannot receive a new packet (for example, RX buffer is full), it can take no additional NESN way to send Nak packet. After the peer device receives the type of packet, the old packet (the "TX old data, SN" branch in the left part of Picture 4) is sent. When the device receives such an old packet, it does not do any processing (the "Ignore RX data" branch in the right part of picture 4). This is the flow control mechanism of the link layer (flow control)

Figure 4 ble response and flow control mechanism

4. HCI

The functionality of the HCI (Host Control Interface) is much simpler, which is to encapsulate the functionality provided by the link layer, including two classes.

1) connection establishment, shutdown, parameter setting, management, etc., this kind is through HCI command/event (its format can refer to "Bluetooth Protocol analysis (5) _ble Broadcast Communication related technical analysis" in the introduction) completed, including:

LE Create Connection command, which establishes the connection commands, needs to provide connection-related parameters, including Conninterval (Conn_interval_min and Conn_interval_max), Connslavelatency (conn_latency) and Connsupervisiontimeout (Supervision_timeout).

LE Create Connection Cancel Command, cancels or disconnects the connection.

LE Connection Update Command, updating the connection parameters, including Conninterval (Conn_interval_min and Conn_interval_max), Connslavelatency (conn_ Latency) and Connsupervisiontimeout (Supervision_timeout).

LE Set Host Channel classification Command, configure Channel map.

LE Read Channel map Command, read channel map.

Wait a minute.

For specific descriptions of these commands, refer to "BLUETOOTH specification Version 4.2 [Vol 2, part E] Host Controller Interface functional Specification".

2) The encapsulation and forwarding of ACL data is no longer explained in detail.

6. GAP

The main function of GAP (Generic Access profile) is to define the capabilities of the BLE device to enable interoperability.

For Bel connection-based communication, GAP defines 4 connection-related patterns (different product patterns, which can be selected to support these modes, specifically refer to "BLUETOOTH specification Version 4.2 [Vol 3, part C] 9.3 CONNECTION MODES and Procedures "):

Non-connectable mode, cannot be connected.

Directed connectable mode, can be "directly connected" (in the case of the other Bluetooth address to know the fast connection).

undirected connectable mode, can be "blind connect" (do not know the other side of the Bluetooth address).

Auto Connection Establishment procedure, can be automatically connected (no host intervention required).

Accordingly, Gap defines 5 and the processes associated with these patterns (different product patterns, which can be chosen to support these processes):

General Connection establishment procedure, the common connection establishment process, search, discovery, connection, all need host participation.

Selective connection establishment procedure, there is a choice of connection building process, host needs to tell Controller that he only wants to establish a connection to a particular device.

Direct Connection Establishment Procedure, connect directly to a known device (the other side knows us).

Connection Parameter Update Procedure, the process of updating the connection parameters.

Terminate Connection Procedure, disconnect.

These mode and procedure specific descriptions, can refer to Bluetooth spec[1].

7. Reference documentation

[1] Core_v4.2.pdf

Bluetooth protocol Analysis (7) Technical analysis of _ble connection

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.