歡迎使用 小書匠(xiaoshujiang)編輯器,您能夠經過 設置 裏的修改模板來改變新建文章的內容。html
1.藍牙BLE常見問答
Q: SMART READY 和 SMART 以及傳統藍牙之間是什麼關係?
A:
1.Smart Ready 能夠和 Smart Ready、傳統藍牙,以及 Smart 之間相互鏈接和通訊。
2.傳統藍牙能夠和 Smart Ready、傳統藍牙之間鏈接和通訊
3.Smart 能夠和 Smart、 Smart Ready 之間鏈接和通訊android
Q: 雙模(DUAL-MODE)和單模(SINGLE-MODE)有什麼區別?
A: 都是藍牙芯片,雙模指的是同時支持1:BasicRate ( BR), 2:Bluetooth Low Energy ( BLE),如手機, PC 等採用的均是雙模的藍牙芯片。不少 android手機都代表支持藍牙 4.0,其實很大部分只支持 Smart Ready 裏的 BR。不是硬件的問題而是軟件裏還不支持LE。目前 Android4.3 系統纔開始全面支持 BLE。iOS 設備對藍牙 4.0 支持的最好,只要是 iPhone4S 和之後的設備均完美徹底支持藍牙 4.0。單模指的是隻支持Bluetooth Low Energy ( 縮寫:BLE或者LE),目前咱們在使用的如Cypress的PSoC和PRoC系列,TI的CC2640等都是單模芯片,只支持Smart。BLE最主要特色是低功耗和低速率,網上關於藍牙 4.0 一節鈕釦電池可以使用一年均是針對 BLE 而言。git
Q: THERE IS A CONFUSION BETWEEN SERVER-CLIENT VS MASTER-SLAVE VS CENTRAL-PERIPHERAL. I NEED A SIMPLIFIED EXPLANATION.
A: These are the different roles defined at different layers of the BLE protocol stack.
Link Layer roles:github
- Master - Initiates a connection
- Slave - Advertises and waits for a connection initiation
GATT roles:api
- Server - Has data
- Client - Wants data
GAP roles:app
- Central - The primary device in a connection
- Peripheral - The secondary device in a connection
The GAP Central is always a Link Layer Master, while the GAP Peripheral is always a Link Layer Slave.dom
Q: I AM NEW TO BLUETOOTH LOW ENERGY AND LOOKING FOR A QUICK BRINGUP. WHERE DO I START?
A: For a quick bringup with Bluetooth Low Energy, please refer to the following:編輯器
If you want to know about the technology, please refer to the videos available at BLE Developer Portal.ide
2.BLE協議棧介紹
2.1 ARCHITECTURE / CONFIGURATIONS
- Protocol stack consists of two main sections:
綠色 Controller
藍色 Host
- Controller Block Diagram
- Profiles and Application sit on top of the GAP and GATT layers of the host
- In a 「single-device solution」 (or 「single-chip solution」), the host, controller, profiles, and application are all implemented together on the same chip
- In a 「dual-device solution」, the BLE controller is implemented on one device, while the host,application, and profiles are implemented separately
- In a 「network processor」, the host and controller are implemented together, but the application and profiles sit on another device (such as a PC or external microcontroller)
2.2 PHYSICAL LAYER
- RF Specifications
- Operates in 2.4 GHz ISM band
- GFSK modulation
- 40 channels with 2 MHz spacing
- 3 fixed advertisting channels for broadcasting, which avoid 802.11 interferance
- 37 adaptively frequency hoppeddynamic data channels
- Physical layer can be combined with standard Bluetooth RF in a dual-mode device
- 2 MHz spacing allows for better adjacent channel rejection
2.3 BLE LINK LAYER
- **Channl :**3 Advertising Channels and 37 Data Channels
- Connection Initiation
Connection Request Packet Flow
-
Connection Parameters
- Channel Map- indicates which data channels are used during the connection
- Connection Interval- multiple of 1.25ms in range of 7.5ms and 4.0s
- Supervision Timeout- multiple of 10ms in the range of 100ms and 32.0s. Must be larger than: (1 + slaveLatency) * (ConnInterval)
- Slave Latency- any value between 0 and 499, though it cannot exceed:((supervisionTimeout / connInterval) – 1)
-
Connection Events
- All communications between two connected devices occur in 「connection events」
- Each event occurs on one data channel (channels 0-36), with the hop increment parameter determining the next channel for the next event
- During each connection event, the master transmits first, and the slave responds 150us later
- Master and slave can continue transmitting back and forth as many times as they want during a single connection event
- Connection events occur even when one (or both) sides have no data to send (the exception to this is when slave latency is enabled; more information on next slide). This allows both devices to acknowledge that the other is still there and keeps the connection active.
-
Slave Latency
-
Connection Parameters Tradeoffs
- Short connection interval:
- Higher power consumption for both devices
- Higher throughput in both directions
- Shorter wait for data to be sent in either direction
- Long connection interval:
- Lower power consumption for both devices
- Lower throughput in both directions
- Longer wait for data to be sent in either direction
- Low / Zero slave latency:
- Higher power consumption for peripheral
- Peripheral receives data sent from central device sooner
- High slave latency:
- Lower power consumption for peripheral during periods when it has no data to send
to central device
- Peripheral may not immediately receive data being sent from central device
-
Connection Update Request
If the slave does not like the connection parameters (interval, slave latency, or supervision timeout), it can send a connection update request to the master
-
Connection Termination
- A connection can be voluntarily terminated by either the master or the slave for any reason
- Connection can also be terminated as a result of a supervision timeout
-
Direct Test Mode
Allows a tester to directly control the device under test (DUT) in either Rx or Tx mode on any channel with any amount of data
2.4 HOST/CONTROLLER INTERFACE (HCI)
- Reused from standard Bluetooth specification,with new additional commands for low energy specific functions
- Thin layer; doesn‟t perform any processing
- In a dual-chip solution (with separate host and controller) allows for host to communicate with controller over a standard interface (UART,USB, SDIO, etc.)
- Used internally by the CC2540 BLE protocol stack for communication between higher and lower layers
- Also allows for custom 「vendor-specific commands」. In the CC2540, vendor-specific commands can be used by an external source to directly interface with the entire stack or application. This is called a 「Network Processor」
2.5 HOST -- LOGICAL LINK CONTROL AND ADAPTATION PROTOCOL (L2CAP)
- Permits upper level protocols and applications to transmit and receive upper layer data packets up to 23 bytes in length
- Provides channel management, allowing for logical channels between two endpoints,supported by the link layer
- Connection Parameter Updates
2.6 SECURITY MANAGER PROTOCOL (SMP)
- Performs authentication and key management
- Uses AES-128 as the encryption algorithm for security procedures
- Defines protocol to setup secure link
- Works with GAP to manage relationships between devices:
- Pairing – encryption between two devices once a connection has been established between them
- Authentication – verification that a peer device can be trusted, providing protection against 「Man-in-the-Middle」 attacks
- Bonding – long-term relationship between devices; security and identity information is saved for re-use next time the devices are connected
2.7 GENERIC ACCESS PROFILE (GAP)
- Overview
- Defines generic procedures for connection-related services:
- Device Discovery
- Link Establishment
- Link Management
- Link Termination
- Initiation of security features
- Many GAP functions correspond directly to the functions of the Link Layer in the controller
- Profile Roles
- The GAP layer works in one of four profile roles:
- Broadcaster – an advertiser that is non-connectable
- Observer – scans for advertisements, but cannot initiate connections.
- Peripheral – an advertiser that is connectable and can operate as a slave in a single link layer connection.
- Central – scans for advertisements and initiates connections; operates as a master in a single or multiple link layer connections.
- Profile Multi-Roles
- The BLE specification allows for a few different possible multiple-role configurations:
- Peripheral and Broadcaster
- Peripheral and Observer
- Central and Broadcaster
- Discoverable Modes
- GAP supports three different discoverable modes:
- Non-discoverable Mode – No advertisements
- Limited Discoverable Mode – Device advertises for a limited amount of time before returning to the standby state
- General Discoverable Mode – Devices advertises continuously
- Advertisement and Scan Response Data
- GAP manages the data that is sent out in advertisement and scan response packets
- Pairing
- Pairing can be initiated by either the central or peripheral device
- Based on the combination of the capabilities of the two devices, one of two methods of pairing will be used:
- Passkey entry – one device will display a randomly generator passkey, while the other will require the user to input the passkey. This allows for an authenticated link (MITM protection)
- 「Just Works」 – the pairing process completes without requiring a passkey to be entered. The link will not be authenticated, but is encrypted
- During the pairing process, each device states whether it wants authentication to the other device
- Each device also states it‟s input/output capabilities from among these options:
- DisplayOnly – no way user can input anything into device, but it can output data
- DisplayYesNo – user can input 「yes」 or 「no」 but nothing else; can also display data
- KeyboardOnly – user can input a password or PIN, but no display
- NoInputNoOutput – device has no means for user input, and has no display
- KeyboardDisplay – device has a means for display as well as for input
2.8 ATTRIBUTE PROTOCOL (ATT)
2.9 GENERIC ATTRIBUTE PROFILE (GATT)
GATT database:
- const CYBLE_GATTS_DB_T cyBle_gattDB[0x10u] = {
- { 0x0001u, 0x2800u
- { 0x0002u, 0x2803u
- { 0x0003u, 0x2A00u
- { 0x0004u, 0x2803u
- { 0x0005u, 0x2A01u
- { 0x0006u, 0x2803u
- { 0x0007u, 0x2A04u
- { 0x0008u, 0x2800u
- { 0x0009u, 0x2803u
- { 0x000Au, 0x2A05u
- { 0x000Bu, 0x2902u
- { 0x000Cu, 0x2800u
- { 0x000Du, 0x2803u
- { 0x000Eu, 0xCBB1u
- { 0x000Fu, 0x2901u
- { 0x0010u, 0x2902u
- };
Custom Uart Tx Service
Handle |
att Type |
Permission |
value |
0x000Cu |
0x2800(GATT Service UUID) |
read |
0xCBBBu(2bytes) |
0x000Du |
0x2803u (GATT Characteristic UUID) |
read,write,notify |
0xCBB1u(2bytes) |
0x000Eu |
0xCBB1u (Custom Buffer UUID) |
read,write,notify |
(200bytes) |
0x000Fu |
0x2901u (Custom Descriptor UUID) |
read |
(28bytes) |
0x0010u |
0x2902u (Client Characteristic Configuration UUID) |
read,write |
(2bytes) |
-
Client Commands
-
When two BLE devices are in the connected state, the GATT client device can perform several different sub-procedures to communicate with the GATT server device:
- Discover Characteristic by UUID – search the GATT server for all attributes with type that matches the specified UUID
- Read Characteristic Value – read the value of the characteristic at the specified handle
- Write Characteristic Value – write a new value to the characteristic at the specified handle
-
A GATT server device, when configured to do so, can send out messages to the GATT client device without being prompted:
- Notification – The value a characteristic is sent from the server to the client without receiving a read request, and does not need to be acknowledged
- Indication – The value a characteristic is sent from the server to the client without receiving a read request, but must be acknowledged before any further data can be sent
3. BLE應用實例
3.1 BLE轉串口透傳例程
由 BLE_Uart_Transmission_Collector01和BLE_UART_Transmission_Server組成一對主從機程序,實現串口透傳功能。
硬件組成:基於 CY8CKIT-042 BLE Pioneer Kit
3.2 程序介紹
3.2.1 程序流程
3.2.2 主機和從機的聯繫
|
主機 |
從機 |
profile |
customer profile |
customer profile |
profile role |
Client(GATT Client) |
server(GATT Server) |
GAP role |
Central |
Peripheral |
- 在主流程上主機和從機是相似的
- 主機在BLE使能後,執行的 scan
- case CYBLE_EVT_STACK_ON:
- printf("EVT_STACK_ON \r\n");
- goto start_scan;
-
- case CYBLE_EVT_GAP_DEVICE_DISCONNECTED:
- BleConnected = 0;
- printf("EVT_GAP_DEVICE_DISCONNECTED \r\n");
- goto start_scan;
-
- case CYBLE_EVT_TIMEOUT:
- printf("EVT_TIMEOUT \r\n");
- start_scan:
- if(BleConnected == 0)
- {
- StartScan(CYBLE_UUID_CUSTOMER_SERVICE);
-
- ble_state = BLE_SCAN_STATE;
- }
-
- break;
- 從機在BLE使能後,執行的是Advertisement
- case CYBLE_EVT_STACK_ON:
- printf("EVT_STACK_ON \r\n");
- goto start_advert;
- case CYBLE_EVT_GAP_DEVICE_DISCONNECTED:
-
- case CYBLE_EVT_TIMEOUT:
- start_advert:
-
- StartAdvertisement();
-
- ble_state = BLE_ADV_STATE;
- test_ptr=0;
- break;
- 下面是主機找到從機的關鍵函數,最終以 flag |= CONNECT; 爲出口,並在scan結束後CYBLE_EVT_GAPC_SCAN_START_STOP,發起鏈接CyBle_GapcConnectDevice(&peerAddr[deviceN]), peerAddr[deviceN]就是找到的從機的mac地址。
- void ScanProgressEventHandler(CYBLE_GAPC_ADV_REPORT_T* eventParam)
- {
- uint8 newDevice = 0u, device = 0u;
- uint8 i;
- uint8 adStructPtr = 0u;
- uint8 adTypePtr = 0u;
- uint8 nextPtr = 0u;
-
- printf("SCAN_PROGRESS_RESULT: peerAddrType - %d, ", eventParam->peerAddrType);
- printf("peerBdAddr - ");
- for(newDevice = 1u, i = 0u; i < advDevices; i++)
- {
- if((memcmp(peerAddr[i].bdAddr, eventParam->peerBdAddr, CYBLE_GAP_BD_ADDR_SIZE) == 0))
- {
- device = i;
- printf("%x: ", device);
- newDevice = 0u;
- break;
- }
- }
- if(newDevice != 0u)
- {
- if(advDevices < CYBLE_MAX_ADV_DEVICES)
- {
- memcpy(peerAddr[advDevices].bdAddr, eventParam->peerBdAddr, CYBLE_GAP_BD_ADDR_SIZE);
- peerAddr[advDevices].type = eventParam->peerAddrType;
- device = advDevices;
- advDevices++;
- printf("%x: ", device);
-
- }
- }
- for(i = CYBLE_GAP_BD_ADDR_SIZE; i > 0u; i--)
- {
- printf("%2.2x", eventParam->peerBdAddr[i-1]);
- }
- printf(", rssi - %d dBm, data - ", eventParam->rssi);
-
-
- adStructPtr = 0u;
- for(i = 0; i < eventParam->dataLen; i++)
- {
- printf("%2.2x ", eventParam->data[i]);
-
- if(i == adStructPtr)
- {
- adTypePtr = i + 1;
- adStructPtr += eventParam->data[i] + 1;
- nextPtr = 1;
- }
- else if(i == (adTypePtr + nextPtr))
- {
- switch(eventParam->data[adTypePtr])
- {
- case CYBLE_GAP_ADV_FLAGS:
- break;
-
- case CYBLE_GAP_ADV_INCOMPL_16UUID:
- case CYBLE_GAP_ADV_COMPL_16UUID:
- if(serviceUuid == CyBle_Get16ByPtr(&(eventParam->data[i])))
- {
- newDevice = 2;
- }
- else
- {
- nextPtr += 2;
- }
- break;
-
- default:
- break;
- }
- }
- }
- printf("newDevice = %d \r\n",newDevice);
-
- if(2 == newDevice)
- {
- deviceN = device;
- printf(" This device contains ");
- switch(serviceUuid)
- {
- case CYBLE_UUID_HEART_RATE_SERVICE:
- printf("Heart Rate Service \r\n");
- break;
-
- case CYBLE_UUID_GLUCOSE_SERVICE:
- printf("Glucose Service \r\n");
- break;
-
- case CYBLE_UUID_BLOOD_PRESSURE_SERVICE:
- printf("Blood Pressure Service \r\n");
- break;
- case CYBLE_UUID_HIDS_SERVICE:
- printf("HID Service \r\n");
- printf("Stop Scanning, waiting for Scanning event \r\n");
- flag |= CONNECT;
- CyBle_GapcStopScan();
-
- break;
-
- case 0x290A:
- printf("Stop Scanning, waiting for Scanning event \r\n");
- flag |= CONNECT;
- CyBle_GapcStopScan();
- break;
-
- case CYBLE_UUID_CUSTOMER_SERVICE:
- printf("Customer Service \r\n");
- printf("Stop Scanning, waiting for Scanning event \r\n");
- flag |= CONNECT;
- CyBle_GapcStopScan();
-
- break;
-
- default:
- printf("%x \r\n", serviceUuid);
- break;
- }
- }
- else
- {
- printf("\r\n");
- }
- }
3.2.3 初始化程序
以主機爲例
- int main()
- {
- CYBLE_API_RESULT_T apiResult;
-
- CYBLE_LP_MODE_T lpMode;
-
- CyGlobalIntEnable;
-
- CommInit();
- printf("BLE Uart Transmission Collector Example Project \r\n");
-
- Scanning_LED_Write(LED_OFF);
-
- apiResult = CyBle_Start(AppCallBack);
- if(apiResult != CYBLE_ERROR_OK)
- {
- printf("CyBle_Start API Error: %xd \r\n", apiResult);
- }
- else
- {
- printf("CyBle_Start API ok \r\n");
- }
-
-
- TC_CC_ISR_StartEx(InterruptHandler);
-
-
- Timer_Start();
3.2.4 主程序
以主機爲例
- while(1)
- {
- if(CyBle_GetState() != CYBLE_STATE_INITIALIZING)
- {
-
- lpMode = CyBle_EnterLPM(CYBLE_BLESS_DEEPSLEEP);
- if(lpMode == CYBLE_BLESS_DEEPSLEEP)
- {
-
-
-
-
-
-
-
-
-
- CySysPmSleep();
-
- HandleLEDs(ble_state);
- }
- HandleLEDs(ble_state);
- }
-
-
-
- if(CyBle_GetState() == CYBLE_STATE_CONNECTED)
- {
-
-
-
-
- CommMonitorUart();
- CommMonitorBLE();
-
-
- #if 0
- if(mainTimer != 0u)
- {
- mainTimer = 0u;
-
- if(storeBondingData == ENABLED)
- {
- cystatus retValue;
- retValue = CyBle_StoreBondingData(0u);
- printf("Store bonding data, status: %lx \r\n", retValue);
- storeBondingData = DISABLED;
- }
-
- }
- #endif
-
-
- }
-
-
-
-
-
- CyBle_ProcessEvents();
- }
-
-
-
-
-
-
- void CommMonitorBLE(void)
- {
- if(uCommState.Bit.BLERxFinshed == ENABLED)
- {
- uCommState.Bit.BLERxFinshed = DISABLED;
-
- CommUartTxByte();
-
- CommUartRxReady();
- BLE_LED_OFF;
-
-
- CommBLERxReady();
- }
- }
-
-
-
-
-
-
-
- void CommMonitorUart(void)
- {
- CYBLE_API_RESULT_T apiResult;
- CYBLE_GATT_HANDLE_VALUE_PAIR_T CustomNotificationhandle;
-
- if(uCommState.Bit.UartRxFinished == ENABLED)
- {
- uCommState.Bit.UartRxFinished = DISABLED;
-
- uCommState.Bit.BLERxRDY = DISABLED;
-
- CustomNotificationhandle.attrHandle = UART_TX_HANDLE;
- CustomNotificationhandle.value.val = &Buffer[1];
- CustomNotificationhandle.value.len = Buffer[0];
- CustomNotificationhandle.value.actualLen = Buffer[0];
- #if 0
-
-
- apiResult = CyBle_GattsNotification(cyBle_connHandle, &CustomNotificationhandle);
- #else
-
- apiResult = CyBle_GattcWriteWithoutResponse(cyBle_connHandle,&CustomNotificationhandle);
- #endif
-
- CyBle_GattsWriteAttributeValue(&CustomNotificationhandle,FALSE,&cyBle_connHandle,FALSE);
- #ifdef test
- if(apiResult != CYBLE_ERROR_OK)
- {
- printf("ble send Error: %x \r\n", apiResult);
- }
- else
- {
-
- printf("ble send ok len: %x \r\n", CustomNotificationhandle.value.len);
- }
- #endif
-
- CommUartRxReady();
- Uart_LED_OFF;
-
- CommBLERxReady();
- }
-
- }
藍牙的事件回調函數 接收藍牙數據,產生uCommState.Bit.BLERxFinshed
- void AppCallBack(uint32 event, void* eventParam)
- {
- ...
-
- case CYBLE_EVT_GATTC_HANDLE_VALUE_NTF:
- wrReqParam = (CYBLE_GATTS_WRITE_REQ_PARAM_T *) eventParam;
- if(wrReqParam->handleValPair.attrHandle == UART_TX_HANDLE)
- {
- len = wrReqParam->handleValPair.value.len;
- Buffer[0] = len;
- memcpy(&Buffer[1],wrReqParam->handleValPair.value.val,len);
- uCommState.Bit.BLERxFinshed = ENABLED;
-
- }
-
- ....
- }
串口中斷函數及定時器中斷函數 接收串口數據,產生uCommState.Bit.UartRxFinished
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- CY_ISR(Transport_RX_ISR)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- CY_ISR(Transport_Timer_ISR)
-
3.2.5 程序的調試
- * 1 AppCallBack :CYBLE_EVT_STACK_ON:StartAdvertisement()
-
- * 2 AppCallBack :CYBLE_EVT_GAPC_SCAN_START_STOP (SCAN_START)
-
- * 3&4 AppCallBack :CYBLE_EVT_GAP_DEVICE_CONNECTED 鏈接間隔 爲 7.5ms
-
- * 5 AppCallBack :CYBLE_EVT_GATTC_XCHNG_MTU_RSP 變動成功
- 這個透傳的程序目前咱們用於無線打印數據,配合下圖的虛擬示波器使用
3.3 其餘精彩例程
PSoC 4 BLE is an easy-to-use, ARM® Cortex™-M0 based, single-chip solution which integrates programmable analog front ends, programmable digital peripherals, CapSense® technology for touch-sensing, and a Bluetooth® LE (Low Energy) or Bluetooth Smart radio. http://www.cypress.com/psoc4ble/ — Edit
4. BLE語音遙控器
4.1 概述
- 利爾達BLE遙控器方案是基於藍牙4.1的多功能智能遙控器解決方案,能夠根據需求加入藍牙語音,多指觸控,體感控制等功能。本方案採樣了Cypress的PRco系列,該系列是Cypress公司專門針對低功耗藍牙設備推出的超低功耗,超高集成度的單芯片解決方案。
功能 |
性能 |
備註 |
BLE stack |
Bluetooth 4.2 single-mode device |
|
TX output power |
–18 dBm to +3 dBm |
|
RX sensitivity |
–89 dBm |
|
TX current |
15.6 mA at 0 dBm |
|
RX current |
16.4 mA |
|
CPU |
Cortex-M0 |
operating at up to 48 MHz |
flash memory |
128~256 KB |
|
SRAM memory |
16~32 KB |
|
Other feature |
1.3-µA Deep-Sleep mode |
|
|
CapSense® Touch Sensing |
|
|
Two-finger gestures |
|
|
12-bit, 1-Msps SAR ADC with internal reference |
|
|
OTA |
|
4.2 功能介紹
- LED & IR 硬件實現呼吸燈 和 紅外NEC編碼
4.3 BLE HID PROFILE
- Human Interface Device Service
- report map
HID設備描述符 其中咱們定義了兩個私有的描述符,這個是咱們用來傳輸語音的。由於BLE並不支持 A2DP(Advenced Audio Distribution Profile)藍牙立體聲協議,要傳語音數據咱們只能利用私有的通道。
- 在 android端提供相應的驅動來解析咱們的語音數據,最終提供標準的PCM數據給到android的中間層。