simpleBLECentral.C簡單的翻譯一下,方便編程,特此記錄

版權聲明

博主:si_zhou_qun_84342712

聲明:喝水不忘挖井人,轉載請註明出處。

原文地址:http://write.blog.csdn.NET/postedit

聯繫方式:[email protected]

開源四軸羣:84342712

開源四軸(淘寶店):


/*BLE中的GAP和GATT

GATT通俗理解爲用於主從機之間的客戶端和服務器端的數據交互,以Attribute Table來體現。
//*GATT層:是一個服務框架定義了對ATT應用的子程序。GATT指定了profile的結構。
//*在BLE中,由profile或者是服務所使用的所有類型的數據都稱爲characteristic。發生於兩個設備間通過BLE連接進行交換的數據都需經過GATT子程序處理。因此,app和profile會直接使用GATT。

//*GAP:直接與profile和app進行接觸,解決設備的發現和連接相關的服務,此外GAP也會初始化安全相關的特色。
//*GAP Role Profile:在GAP劇本里所處的4個角色:廣播Advertise,主機central,從機Peripheral,觀察者Observer。
//*ATT協議允許一個設備去顯示一些數據,對於其他設備稱之爲“Attribute屬性”,在ATT中,那些顯示這些屬性的設備被稱爲server,同等的另一個設備稱爲client。LL層的狀態master和slave和ATT層的這兩個狀態無關。
*/
/*********************************************************************
 * 包含
 */ 
#include "bcomdef.h"
#include "OSAL.h"
#include "OSAL_PwrMgr.h"
#include "OnBoard.h"
#include "hal_led.h"
#include "hal_key.h"
#include "hal_lcd.h"
#include "gatt.h"
#include "ll.h"
#include "hci.h"
#include "gapgattserver.h"
#include "gattservapp.h"
#include "central.h"
#include "gapbondmgr.h"
#include "simpleGATTprofile.h"
#include "simpleBLECentral.h"

//包含串口程序
#include "SerialApp.h"

/*********************************************************************
 * 宏定義
 */

// 藍牙設備地址長度
#define B_ADDR_STR_LEN                        15

/*********************************************************************
 * 常量
 */

// 掃描從機最大值
#define DEFAULT_MAX_SCAN_RES                  8

//掃描持續時間(ms)
#define DEFAULT_SCAN_DURATION                 4000

// 發現模式 (有限制的, 常規, 全部)
#define DEFAULT_DISCOVERY_MODE                DEVDISC_MODE_ALL

// 開啓主動掃描
#define DEFAULT_DISCOVERY_ACTIVE_SCAN         TRUE

// 關閉掃描白名單
#define DEFAULT_DISCOVERY_WHITE_LIST          FALSE

// 連接時關閉高速掃描
#define DEFAULT_LINK_HIGH_DUTY_CYCLE          FALSE

// 連接時關閉白名單功能
#define DEFAULT_LINK_WHITE_LIST               FALSE

//輪詢RSSI信號週期(MS)
#define DEFAULT_RSSI_PERIOD                   1000

//當連接時是否允許自動升級
#define DEFAULT_ENABLE_UPDATE_REQUEST         FALSE

// 如果自動啓用參數更新請求,最小連接間隔(計算單位:每次1.25ms) 
#define DEFAULT_UPDATE_MIN_CONN_INTERVAL      20

//最大連接時間間隔(units of 1.25ms) 如果啓用了自動請求更新參數
#define DEFAULT_UPDATE_MAX_CONN_INTERVAL      20

// Slave latency to use if automatic parameter update request is enabled
#define DEFAULT_UPDATE_SLAVE_LATENCY          0

// 監督超時值(units of 10ms) 如果啓用了自動請求更新參數
#define DEFAULT_UPDATE_CONN_TIMEOUT           600

// 默認密碼
#define DEFAULT_PASSCODE                      19655

// 定義GAP模式
#define DEFAULT_PAIRING_MODE                  GAPBOND_PAIRING_MODE_WAIT_FOR_REQ

// 定義配對模式 (是否開啓配對時候需要配對碼)
#define DEFAULT_MITM_MODE                     FALSE

// 定義是否綁定模式
#define DEFAULT_BONDING_MODE                  TRUE

// Default GAP bonding I/O capabilities
#define DEFAULT_IO_CAPABILITIES               GAPBOND_IO_CAP_DISPLAY_ONLY

//定義搜索器延時(MS)
#define DEFAULT_SVC_DISCOVERY_DELAY           1000

//基於從機的UUID碼,如果真就過濾搜索結果
#define DEFAULT_DEV_DISC_BY_SVC_UUID          TRUE

//應用程序狀態
enum
{
  BLE_STATE_IDLE,
  BLE_STATE_CONNECTING,
  BLE_STATE_CONNECTED,
  BLE_STATE_DISCONNECTING
};

// 發現設備狀態
enum
{
  BLE_DISC_STATE_IDLE,                //  閒置的
  BLE_DISC_STATE_SVC,                 // 服務發現
  BLE_DISC_STATE_CHAR                 // 發現特有
};

/*********************************************************************
 * 類型定義
 */

/*********************************************************************
 * 全局變量
 */

/*********************************************************************
 * 外部變量
 */

/*********************************************************************
 * 外部函數 
 */

/*********************************************************************
 * 局部變量
 */
//內部的任務/ 事件處理的任務ID
static uint8 simpleBLETaskId;

// GAP GATT 屬性(BLE名稱)
static const uint8 simpleBLEDeviceName[GAP_DEVICE_NAME_LEN] = "Simple BLE Central";

// 掃描結果和掃描結果索引
static uint8 simpleBLEScanRes;
static uint8 simpleBLEScanIdx;

// 掃描結果列表
static gapDevRec_t simpleBLEDevList[DEFAULT_MAX_SCAN_RES];

// 掃描狀態
static uint8 simpleBLEScanning = FALSE;

// RSSI polling state
static uint8 simpleBLERssi = FALSE;

// Connection handle of current connection 
static uint16 simpleBLEConnHandle = GAP_CONNHANDLE_INIT;

// 應用狀態
static uint8 simpleBLEState = BLE_STATE_IDLE;

//探索狀態
static uint8 simpleBLEDiscState = BLE_DISC_STATE_IDLE;

//搜索開始與結束的句柄
static uint16 simpleBLESvcStartHdl = 0;
static uint16 simpleBLESvcEndHdl = 0;

//發現特有設備句柄
static uint16 simpleBLECharHdl = 0;

// Value to write寫的值
static uint8 simpleBLECharVal = 0;

// 讀取的值/寫切換
static bool simpleBLEDoWrite = FALSE;

// GATT讀/寫程序狀態
static bool simpleBLEProcedureInProgress = FALSE;

/*********************************************************************
 * 局部函數
 */
static void simpleBLECentralProcessGATTMsg( gattMsgEvent_t *pMsg );
static void simpleBLECentralRssiCB( uint16 connHandle, int8  rssi );
static void simpleBLECentralEventCB( gapCentralRoleEvent_t *pEvent );
static void simpleBLECentralPasscodeCB( uint8 *deviceAddr, uint16 connectionHandle,
                                        uint8 uiInputs, uint8 uiOutputs );
static void simpleBLECentralPairStateCB( uint16 connHandle, uint8 state, uint8 status );
static void simpleBLECentral_HandleKeys( uint8 shift, uint8 keys );
static void simpleBLECentral_ProcessOSALMsg( osal_event_hdr_t *pMsg );
static void simpleBLEGATTDiscoveryEvent( gattMsgEvent_t *pMsg );
static void simpleBLECentralStartDiscovery( void );
static bool simpleBLEFindSvcUuid( uint16 uuid, uint8 *pData, uint8 dataLen );
static void simpleBLEAddDeviceInfo( uint8 *pAddr, uint8 addrType );
char *bdAddr2Str ( uint8 *pAddr );

/*********************************************************************
 * 配置回調函數
 */

// GAP Role 回調函數
static const gapCentralRoleCB_t simpleBLERoleCB =
{
  simpleBLECentralRssiCB,       // RSSI信號回調
  simpleBLECentralEventCB       // 事件回調
};

// 綁定管理器的回調函數
static const gapBondCBs_t simpleBLEBondCB =
{
  simpleBLECentralPasscodeCB,
  simpleBLECentralPairStateCB
};

/*********************************************************************
 * 公共函數
 */

/*********************************************************************
 * 函數名:     SimpleBLECentral_Init
 *
 * 描敘:   初始化BLE主機,在任務初始化時候,被調用。
 *        
 * 參數:   任務ID
 *                    
 * 返回:  無
 */
void SimpleBLECentral_Init( uint8 task_id )
{
  simpleBLETaskId = task_id;
  //添加串口初始化,並傳遞任務id
  SerialApp_Init(simpleBLETaskId);

  SerialPrintString("SimpleBLECentral_SerialPrint Start init.\r\n");
  //設置主機配置參數
  {
    uint8 scanRes = DEFAULT_MAX_SCAN_RES;
    GAPCentralRole_SetParameter ( GAPCENTRALROLE_MAX_SCAN_RES, sizeof( uint8 ), &scanRes );
  }
  
  // 設置GAP
  GAP_SetParamValue( TGAP_GEN_DISC_SCAN, DEFAULT_SCAN_DURATION );
  GAP_SetParamValue( TGAP_LIM_DISC_SCAN, DEFAULT_SCAN_DURATION );
  GGS_SetParameter( GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, (uint8 *) simpleBLEDeviceName );

  //設置GAP的綁定管理器
  {
    uint32 passkey = DEFAULT_PASSCODE;
    uint8 pairMode = DEFAULT_PAIRING_MODE;
    uint8 mitm = DEFAULT_MITM_MODE;
    uint8 ioCap = DEFAULT_IO_CAPABILITIES;
    uint8 bonding = DEFAULT_BONDING_MODE;
    GAPBondMgr_SetParameter( GAPBOND_DEFAULT_PASSCODE, sizeof( uint32 ), &passkey );
    GAPBondMgr_SetParameter( GAPBOND_PAIRING_MODE, sizeof( uint8 ), &pairMode );
    GAPBondMgr_SetParameter( GAPBOND_MITM_PROTECTION, sizeof( uint8 ), &mitm );
    GAPBondMgr_SetParameter( GAPBOND_IO_CAPABILITIES, sizeof( uint8 ), &ioCap );
    GAPBondMgr_SetParameter( GAPBOND_BONDING_ENABLED, sizeof( uint8 ), &bonding );
  }  

  // 初始化GATT客戶端 
  VOID GATT_InitClient();

  //登記接受到的ATT標誌/通知
    GATT_RegisterForInd( simpleBLETaskId );

  //初始化GATT屬性
  GGS_AddService( GATT_ALL_SERVICES );         // GAP
  GATTServApp_AddService( GATT_ALL_SERVICES ); // GATT attributes

  // 註冊所有按鍵事件- 這個應用會處理所有按鍵事件
  RegisterForKeys( simpleBLETaskId );
  
  //關閉所有LED
  HalLedSet( (HAL_LED_1 | HAL_LED_2), HAL_LED_MODE_OFF );
  
  ////標誌SBP_START_DEVICE_EVT啓動對應ID事件
  osal_set_event( simpleBLETaskId, START_DEVICE_EVT );
  
  SerialPrintString("Ready to Starting\r\n");
}

/*********************************************************************
 * 函數名稱   SimpleBLECentral_ProcessEvent
 *
 * 描述     BLE事件處理函數. 調用該函數處理所有BLE事件( 時間, 消息,用戶定義事件)
 *
 * 參數:   任務ID 
 * 參數:   事件 - 要處理的事件(可包含多個事件).
 *
 * 返回:   失敗:返回未處理的事件
            成功: 0
 */
uint16 SimpleBLECentral_ProcessEvent( uint8 task_id, uint16 events )
{
  
  VOID task_id; // OSAL required parameter that isn't used in this function
  
  if ( events & SYS_EVENT_MSG )
  {
    uint8 *pMsg;

    if ( (pMsg = osal_msg_receive( simpleBLETaskId )) != NULL )
    {
      simpleBLECentral_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );

      // 釋放處理消息
      VOID osal_msg_deallocate( pMsg );
    }

    // 返回未處理的事件
    return (events ^ SYS_EVENT_MSG);
  }

  if ( events & START_DEVICE_EVT )
  {
    //啓動設備
    VOID GAPCentralRole_StartDevice( (gapCentralRoleCB_t *) &simpleBLERoleCB );

    // 啓動後,註冊綁定管理器
    GAPBondMgr_Register( (gapBondCBs_t *) &simpleBLEBondCB );
    
    SerialPrintString("BLE Stack is running\r\n");
    return ( events ^ START_DEVICE_EVT );
  }

  if ( events & START_DISCOVERY_EVT )
  {
    simpleBLECentralStartDiscovery( );
    
    return ( events ^ START_DISCOVERY_EVT );
  }
  
  return 0;
}

/*********************************************************************
 * 函數名稱      simpleBLECentral_ProcessOSALMsg
 *
 * 描述:   處理傳進來的事件消息
 *
 * 參數:   pMsg - 要處理的消息
 *
 * @return  無
 */
static void simpleBLECentral_ProcessOSALMsg( osal_event_hdr_t *pMsg )
{
  switch ( pMsg->event )
  {
    case KEY_CHANGE:
      simpleBLECentral_HandleKeys( ((keyChange_t *)pMsg)->state, ((keyChange_t *)pMsg)->keys );
      break;

    case GATT_MSG_EVENT:
      simpleBLECentralProcessGATTMsg( (gattMsgEvent_t *) pMsg );
      break;
  }
}

/*********************************************************************
 * 函數名稱:    simpleBLECentral_HandleKeys
 *
 * 描述:   處理所有按鍵事件
 *
 * 參數:   shift - true if in shift/alt.
 * 參數:   keys - bit field for key events. Valid entries:
 *                 HAL_KEY_SW_2
 *                 HAL_KEY_SW_1
 *
 * 返回值:  無
 */
uint8 gStatus;
static void simpleBLECentral_HandleKeys( uint8 shift, uint8 keys )
{
  (void)shift;  

  if ( keys & HAL_KEY_UP )
  {
    // Start or stop discovery
    SerialPrintString("  [KEY UP pressed!]\r\n");
    if ( simpleBLEState != BLE_STATE_CONNECTED )
    {
      if ( !simpleBLEScanning )
      {
        simpleBLEScanning = TRUE;
        simpleBLEScanRes = 0;
        
        LCD_WRITE_STRING( "Discovering...", HAL_LCD_LINE_1 );
        SerialPrintString("Discovering...\r\n");
        LCD_WRITE_STRING( "", HAL_LCD_LINE_2 );
        
        GAPCentralRole_StartDiscovery( DEFAULT_DISCOVERY_MODE,
                                       DEFAULT_DISCOVERY_ACTIVE_SCAN,
                                       DEFAULT_DISCOVERY_WHITE_LIST );      
      }
      else
      {
        GAPCentralRole_CancelDiscovery();
      }
    }
    else if ( simpleBLEState == BLE_STATE_CONNECTED &&
              simpleBLECharHdl != 0 &&
              simpleBLEProcedureInProgress == FALSE )
    {
      uint8 status;
      
      //做一個讀或寫,只要沒有其他正在進行讀/寫程序
      if ( simpleBLEDoWrite )
      {
        // 寫
        attWriteReq_t req;
        
        req.handle = simpleBLECharHdl;
        req.len = 1;
        req.value[0] = simpleBLECharVal;
        req.sig = 0;
        req.cmd = 0;
        status = GATT_WriteCharValue( simpleBLEConnHandle, &req, simpleBLETaskId );         
      }
      else
      {
        // 讀
        attReadReq_t req;
        
        req.handle = simpleBLECharHdl;
        status = GATT_ReadCharValue( simpleBLEConnHandle, &req, simpleBLETaskId );
      }
      
      if ( status == SUCCESS )
      {
        simpleBLEProcedureInProgress = TRUE;
        simpleBLEDoWrite = !simpleBLEDoWrite;
      }
    }    
  }

  if ( keys & HAL_KEY_LEFT )
  {
    SerialPrintString("  [KEY LEFT pressed!]\r\n");
    //顯示發現結果
    if ( !simpleBLEScanning && simpleBLEScanRes > 0 )
    {
        //增加目前結果(with wraparound)
        simpleBLEScanIdx++;
        if ( simpleBLEScanIdx >= simpleBLEScanRes )
        {
          simpleBLEScanIdx = 0;
        }
        
        LCD_WRITE_STRING_VALUE( "Device", simpleBLEScanIdx + 1,
                                10, HAL_LCD_LINE_1 );
        SerialPrintValue( "Device", simpleBLEScanIdx + 1, 10);
        LCD_WRITE_STRING( bdAddr2Str( simpleBLEDevList[simpleBLEScanIdx].addr ),
                          HAL_LCD_LINE_2 );
        SerialPrintString((uint8*) bdAddr2Str( simpleBLEDevList[simpleBLEScanIdx].addr ));SerialPrintString("\r\n");
    }
  }

  if ( keys & HAL_KEY_RIGHT )
  {
    SerialPrintString("  [KEY RIGHT pressed!]\r\n");
    //連接更新
    if ( simpleBLEState == BLE_STATE_CONNECTED )
    {
      GAPCentralRole_UpdateLink( simpleBLEConnHandle,
                                 DEFAULT_UPDATE_MIN_CONN_INTERVAL,
                                 DEFAULT_UPDATE_MAX_CONN_INTERVAL,
                                 DEFAULT_UPDATE_SLAVE_LATENCY,
                                 DEFAULT_UPDATE_CONN_TIMEOUT );
    }
  }
  
  if ( keys & HAL_KEY_CENTER )
  {
    uint8 addrType;
    uint8 *peerAddr;
    SerialPrintString("  [KEY CENTER pressed!]\r\n");
    //連接或斷開連接
    if ( simpleBLEState == BLE_STATE_IDLE )
    {
      //如果有掃描的結果
      if ( simpleBLEScanRes > 0 )
      {
        //連接到當前設備掃描結果
        peerAddr = simpleBLEDevList[simpleBLEScanIdx].addr;
        addrType = simpleBLEDevList[simpleBLEScanIdx].addrType;
      
        simpleBLEState = BLE_STATE_CONNECTING;
        
        GAPCentralRole_EstablishLink( DEFAULT_LINK_HIGH_DUTY_CYCLE,
                                      DEFAULT_LINK_WHITE_LIST,
                                      addrType, peerAddr );
  
        LCD_WRITE_STRING( "Connecting", HAL_LCD_LINE_1 );
        SerialPrintString("Connecting:");
        LCD_WRITE_STRING( bdAddr2Str( peerAddr ), HAL_LCD_LINE_2 ); 
        SerialPrintString((uint8*)bdAddr2Str( peerAddr));SerialPrintString("\r\n");
      }
    }
    else if ( simpleBLEState == BLE_STATE_CONNECTING ||
              simpleBLEState == BLE_STATE_CONNECTED )
    {
      //斷開
      simpleBLEState = BLE_STATE_DISCONNECTING;

      gStatus = GAPCentralRole_TerminateLink( simpleBLEConnHandle );
      
      LCD_WRITE_STRING( "Disconnecting", HAL_LCD_LINE_1 ); 
      SerialPrintString("Disconnecting\r\n");
    }
  }
  
  if ( keys & HAL_KEY_DOWN )
  {
    SerialPrintString("  [KEY DOWN pressed!]\r\n");
    // 開始/取消RSSI信號輪詢
    if ( simpleBLEState == BLE_STATE_CONNECTED )
    {
      if ( !simpleBLERssi )
      {
        simpleBLERssi = TRUE;
        GAPCentralRole_StartRssi( simpleBLEConnHandle, DEFAULT_RSSI_PERIOD );
      }
      else
      {
        simpleBLERssi = FALSE;
        GAPCentralRole_CancelRssi( simpleBLEConnHandle );
        
        LCD_WRITE_STRING( "RSSI Cancelled", HAL_LCD_LINE_1 );
        SerialPrintString("RSSI Cancelled\r\n");
      }
    }
  }
}

/*********************************************************************
 * 函數名稱:  simpleBLECentralProcessGATTMsg
 *
 * 描述:   處理GATT消息
 *
 * 返回值  無
 */
static void simpleBLECentralProcessGATTMsg( gattMsgEvent_t *pMsg )
{
  if ( simpleBLEState != BLE_STATE_CONNECTED )
  {
    //掉線時候,萬一有GATT消息到來
    // 忽視該消息
    return;
  }
  static int dataCount=0;
  if ( pMsg->method == ATT_HANDLE_VALUE_NOTI ||
       pMsg->method == ATT_HANDLE_VALUE_IND )
  {
    
     attHandleValueNoti_t noti;
    
     dataCount = dataCount+ 1;
      
     LCD_WRITE_STRING_VALUE( "Data Cnt: ", dataCount, 10, HAL_LCD_LINE_5 );
     
     noti.handle = pMsg->msg.handleValueNoti.handle;
     noti.len = pMsg->msg.handleValueNoti.len;
     
     osal_memcpy(&noti.value, &pMsg->msg.handleValueNoti.value,noti.len);
    // osal_memcpy(&noti.value, &pMsg->msg.handleValueNoti.value,pMsg->msg.handleValueNoti.len);
     
     sbpSerialAppWrite(noti.value,noti.len);
    
  }
  
  if ( ( pMsg->method == ATT_READ_RSP ) ||
       ( ( pMsg->method == ATT_ERROR_RSP ) &&
         ( pMsg->msg.errorRsp.reqOpcode == ATT_READ_REQ ) ) )
  {
    if ( pMsg->method == ATT_ERROR_RSP )
    {
      uint8 status = pMsg->msg.errorRsp.errCode;
      
      LCD_WRITE_STRING_VALUE( "Read Error", status, 10, HAL_LCD_LINE_1 );
      SerialPrintValue("Read Error", status, 10);SerialPrintString("\r\n");
    }
    else
    {
      //成功讀取後,顯示讀取值。
      uint8 valueRead = pMsg->msg.readRsp.value[0];

      LCD_WRITE_STRING_VALUE( "Read rsp:", valueRead, 10, HAL_LCD_LINE_1 );
      SerialPrintValue("Read rsp:", valueRead, 10);SerialPrintString("\r\n");
    }
    
    simpleBLEProcedureInProgress = FALSE;
  }
  else if ( ( pMsg->method == ATT_WRITE_RSP ) ||
       ( ( pMsg->method == ATT_ERROR_RSP ) &&
         ( pMsg->msg.errorRsp.reqOpcode == ATT_WRITE_REQ ) ) )
  {
    
    if ( pMsg->method == ATT_ERROR_RSP == ATT_ERROR_RSP )
    {
      uint8 status = pMsg->msg.errorRsp.errCode;
      
      LCD_WRITE_STRING_VALUE( "Write Error", status, 10, HAL_LCD_LINE_1 );
      SerialPrintValue( "Write Error", status, 10);SerialPrintString("\r\n");
    }
    else
    {
      // After a succesful write, display the value that was written and increment value
      uint8 temp=simpleBLECharVal;
      //LCD_WRITE_STRING_VALUE( "Write sent:", simpleBLECharVal, 10, HAL_LCD_LINE_1 );     
      //SerialPrintValue( "Write sent:", temp, 10);SerialPrintString("\r\n");
    }
    
    simpleBLEProcedureInProgress = FALSE;    

  }
 
  else if ( ( pMsg->method == ATT_PREPARE_WRITE_RSP ) || ( pMsg->method == ATT_EXECUTE_WRITE_RSP ) || 
       ( ( pMsg->method == ATT_ERROR_RSP ) &&
         ( pMsg->msg.errorRsp.reqOpcode == ATT_EXECUTE_WRITE_REQ ) ) )
  {
    static uint8 message_times = 0;
      //LCD_WRITE_STRING_VALUE( "Message_Times", ++message_times, 10, HAL_LCD_LINE_2 );
    
    //if ( pMsg->method == ATT_ERROR_RSP == ATT_ERROR_RSP )
    if ( pMsg->method == ATT_ERROR_RSP)    
    {
      uint8 status = pMsg->msg.errorRsp.errCode;
      //LCD_WRITE_STRING_VALUE( "Write LC Error", status, 10, HAL_LCD_LINE_1 );
    }
    else if( pMsg->method == ATT_PREPARE_WRITE_RSP )            //bleTimeout status
    {
      //HalLcdWriteString("Write LC Tout!",HAL_LCD_LINE_1);
    }
    else
    {
        
      // After a succesful write, display the value that was written and increment value
        //HalLcdWriteString("Write LC Success!",HAL_LCD_LINE_1);
          //LCD_WRITE_STRING_VALUE( "Message_Times", ++message_times, 10, HAL_LCD_LINE_2 );
    }

    simpleBLEProcedureInProgress = FALSE;    //重要
  }
  else if ( simpleBLEDiscState != BLE_DISC_STATE_IDLE )
  {
    simpleBLEGATTDiscoveryEvent( pMsg );
  }
  
}

/*********************************************************************
 * 函數名稱   simpleBLECentralRssiCB
 *
 * 描述     RSSI信號回調函數
 *
 * 參數   connHandle - 連接句柄
 * 參數   rssi - RSSI信號值
 *
 * 返回   無
 */
static void simpleBLECentralRssiCB( uint16 connHandle, int8 rssi )
{
    LCD_WRITE_STRING_VALUE( "RSSI -dB:", (uint8) (-rssi), 10, HAL_LCD_LINE_1 );
    SerialPrintValue("RSSI -dB:", (uint8) (-rssi), 10);SerialPrintString("\r\n");
}

/*********************************************************************
 * 函數名稱      simpleBLECentralEventCB
 *
 * 描述      主機事件回調函數
 *
 * 參數      pEvent - 事件結構指針
 *
 * 返回值    無
 */
static void simpleBLECentralEventCB( gapCentralRoleEvent_t *pEvent )
{
  switch ( pEvent->gap.opcode )
  {
    case GAP_DEVICE_INIT_DONE_EVENT:  
      {
        LCD_WRITE_STRING( "BLE Central", HAL_LCD_LINE_1 );
        SerialPrintString("BLE Central: ");
        LCD_WRITE_STRING( bdAddr2Str( pEvent->initDone.devAddr ),  HAL_LCD_LINE_2 );
        SerialPrintString((uint8*)bdAddr2Str( pEvent->initDone.devAddr ));SerialPrintString("\r\n");
      }
      break;

    case GAP_DEVICE_INFO_EVENT:
      {
        //如果過濾器發現有搜索結果(基於服務UUID碼)
        if ( DEFAULT_DEV_DISC_BY_SVC_UUID == TRUE )
        {
          if ( simpleBLEFindSvcUuid( SIMPLEPROFILE_SERV_UUID,
                                     pEvent->deviceInfo.pEvtData,
                                     pEvent->deviceInfo.dataLen ) )
          {
            simpleBLEAddDeviceInfo( pEvent->deviceInfo.addr, pEvent->deviceInfo.addrType );
          }
        }
      }
      break;
      
    case GAP_DEVICE_DISCOVERY_EVENT:
      {
        // 收索完成
        simpleBLEScanning = FALSE;

        // 如果過濾器沒有發現搜索結果(基於服務UUID碼)
        if ( DEFAULT_DEV_DISC_BY_SVC_UUID == FALSE )
        {
          //複製結果
          simpleBLEScanRes = pEvent->discCmpl.numDevs;
          osal_memcpy( simpleBLEDevList, pEvent->discCmpl.pDevList,
                       (sizeof( gapDevRec_t ) * pEvent->discCmpl.numDevs) );
        }
        
        LCD_WRITE_STRING_VALUE( "Devices Found", simpleBLEScanRes,
                                10, HAL_LCD_LINE_1 );
        SerialPrintValue("Devices Found", simpleBLEScanRes,10);
        SerialPrintString("\r\n");
        
        if ( simpleBLEScanRes > 0 )
        {
          LCD_WRITE_STRING( "<- To Select", HAL_LCD_LINE_2 );
          SerialPrintString("<- To Select\r\n");
        }

        //初始化索引掃描設備
        simpleBLEScanIdx = simpleBLEScanRes;

      }
      break;

    case GAP_LINK_ESTABLISHED_EVENT:
      {
        if ( pEvent->gap.hdr.status == SUCCESS )
        {          
          simpleBLEState = BLE_STATE_CONNECTED;
          simpleBLEConnHandle = pEvent->linkCmpl.connectionHandle;
          simpleBLEProcedureInProgress = TRUE;    

          //如果搜索器沒有初始化
          if ( simpleBLECharHdl == 0 )
          {
            osal_start_timerEx( simpleBLETaskId, START_DISCOVERY_EVT, DEFAULT_SVC_DISCOVERY_DELAY );
          }
                    
          LCD_WRITE_STRING( "Connected", HAL_LCD_LINE_1 );
          SerialPrintString("Connected: ");
          LCD_WRITE_STRING( bdAddr2Str( pEvent->linkCmpl.devAddr ), HAL_LCD_LINE_2 );   
          SerialPrintString((uint8*) bdAddr2Str( pEvent->linkCmpl.devAddr ));SerialPrintString("\r\n");
          
        }
        else
        {
          simpleBLEState = BLE_STATE_IDLE;
          simpleBLEConnHandle = GAP_CONNHANDLE_INIT;
          simpleBLERssi = FALSE;
          simpleBLEDiscState = BLE_DISC_STATE_IDLE;
          
          LCD_WRITE_STRING( "Connect Failed", HAL_LCD_LINE_1 );
          SerialPrintString("Connect Failed: ");
          LCD_WRITE_STRING_VALUE( "Reason:", pEvent->gap.hdr.status, 10, HAL_LCD_LINE_2 );
          SerialPrintValue("Reason:",  pEvent->gap.hdr.status,10);
        }
      }
      break;

    case GAP_LINK_TERMINATED_EVENT:
      {
        simpleBLEState = BLE_STATE_IDLE;
        simpleBLEConnHandle = GAP_CONNHANDLE_INIT;
        simpleBLERssi = FALSE;
        simpleBLEDiscState = BLE_DISC_STATE_IDLE;
        simpleBLECharHdl = 0;
        simpleBLEProcedureInProgress = FALSE;
          
        LCD_WRITE_STRING( "Disconnected", HAL_LCD_LINE_1 );
        SerialPrintString("Disconnected: ");
        LCD_WRITE_STRING_VALUE( "Reason:", pEvent->linkTerminate.reason,
                                10, HAL_LCD_LINE_2 );
        SerialPrintValue("Reason:",  pEvent->linkTerminate.reason,10);
      }
      break;

    case GAP_LINK_PARAM_UPDATE_EVENT:
      {
        LCD_WRITE_STRING( "Param Update", HAL_LCD_LINE_1 );
        SerialPrintString("Param Update\r\n");
      }
      break;
      
    default:
      break;
  }
}

/*********************************************************************
 * 函數名稱     pairStateCB
 *
 * 參數    配對狀態回調函數
 *
 * 返回值  無
 */
static void simpleBLECentralPairStateCB( uint16 connHandle, uint8 state, uint8 status )
{
  if ( state == GAPBOND_PAIRING_STATE_STARTED )
  {
    LCD_WRITE_STRING( "Pairing started", HAL_LCD_LINE_1 );
  }
  else if ( state == GAPBOND_PAIRING_STATE_COMPLETE )
  {
    if ( status == SUCCESS )
    {
      LCD_WRITE_STRING( "Pairing success", HAL_LCD_LINE_1 );
    }
    else
    {
      LCD_WRITE_STRING_VALUE( "Pairing fail", status, 10, HAL_LCD_LINE_1 );
    }
  }
  else if ( state == GAPBOND_PAIRING_STATE_BONDED )
  {
    if ( status == SUCCESS )
    {
      LCD_WRITE_STRING( "Bonding success", HAL_LCD_LINE_1 );
    }
  }
}

/*********************************************************************
 * 函數名稱      simpleBLECentralPasscodeCB
 *
 * 參數   密碼回調函數
 *
 * 返回值  無
 */
static void simpleBLECentralPasscodeCB( uint8 *deviceAddr, uint16 connectionHandle,
                                        uint8 uiInputs, uint8 uiOutputs )
{
#if (HAL_LCD == TRUE)

  uint32  passcode;
  uint8   str[7];

  //創建隨機密碼
  LL_Rand( ((uint8 *) &passcode), sizeof( uint32 ));
  passcode %= 1000000;
  
  //顯示密碼的用戶
  if ( uiOutputs != 0 )
  {
    LCD_WRITE_STRING( "Passcode:",  HAL_LCD_LINE_1 );
    LCD_WRITE_STRING( (char *) _ltoa(passcode, str, 10),  HAL_LCD_LINE_2 );
  }
  
  //發送密碼響應
  GAPBondMgr_PasscodeRsp( connectionHandle, SUCCESS, passcode );
#endif
}

/*********************************************************************
 * 函數名稱      simpleBLECentralStartDiscovery
 *
 * 參數   開始搜索從設備.
 *
 * 返回值 無
 */
static void simpleBLECentralStartDiscovery( void )
{
  uint8 uuid[ATT_BT_UUID_SIZE] = { LO_UINT16(SIMPLEPROFILE_SERV_UUID),
                                   HI_UINT16(SIMPLEPROFILE_SERV_UUID) };
  
  //初始化緩存處理
  simpleBLESvcStartHdl = simpleBLESvcEndHdl = simpleBLECharHdl = 0;

  simpleBLEDiscState = BLE_DISC_STATE_SVC;
  
  //發現BLE服務器
  GATT_DiscPrimaryServiceByUUID( simpleBLEConnHandle,
                                 uuid,
                                 ATT_BT_UUID_SIZE,
                                 simpleBLETaskId );
}

/*********************************************************************
 * 函數名稱      simpleBLEGATTDiscoveryEvent
 *
 * 描述   處理GATT收索事件
 *
 *返回值  無
 */
static void simpleBLEGATTDiscoveryEvent( gattMsgEvent_t *pMsg )
{
  attReadByTypeReq_t req;
  
  if ( simpleBLEDiscState == BLE_DISC_STATE_SVC )
  {
    // 服務發現, 存儲處理
    if ( pMsg->method == ATT_FIND_BY_TYPE_VALUE_RSP &&
         pMsg->msg.findByTypeValueRsp.numInfo > 0 )
    {
      simpleBLESvcStartHdl = pMsg->msg.findByTypeValueRsp.handlesInfo[0].handle;
      simpleBLESvcEndHdl = pMsg->msg.findByTypeValueRsp.handlesInfo[0].grpEndHandle;
    }
    
    // 如果程序完成
    if ( ( pMsg->method == ATT_FIND_BY_TYPE_VALUE_RSP  && 
           pMsg->hdr.status == bleProcedureComplete ) ||
         ( pMsg->method == ATT_ERROR_RSP ) )
    {
      if ( simpleBLESvcStartHdl != 0 )
      {
        //發現特有設備
        simpleBLEDiscState = BLE_DISC_STATE_CHAR;
        
        req.startHandle = simpleBLESvcStartHdl;
        req.endHandle = simpleBLESvcEndHdl;
        req.type.len = ATT_BT_UUID_SIZE;
        req.type.uuid[0] = LO_UINT16(SIMPLEPROFILE_CHAR1_UUID);
        req.type.uuid[1] = HI_UINT16(SIMPLEPROFILE_CHAR1_UUID);

        GATT_ReadUsingCharUUID( simpleBLEConnHandle, &req, simpleBLETaskId );
      }
    }
  }
  else if ( simpleBLEDiscState == BLE_DISC_STATE_CHAR )
  {
    // 發現特有設備,存儲處理
    if ( pMsg->method == ATT_READ_BY_TYPE_RSP && 
         pMsg->msg.readByTypeRsp.numPairs > 0 )
    {
      simpleBLECharHdl = BUILD_UINT16( pMsg->msg.readByTypeRsp.dataList[0],
                                       pMsg->msg.readByTypeRsp.dataList[1] );
      
      LCD_WRITE_STRING( "Simple Svc Found", HAL_LCD_LINE_1 );
      SerialPrintString("Simple Svc Found\r\n");
      simpleBLEProcedureInProgress = FALSE;
    }
    
    simpleBLEDiscState = BLE_DISC_STATE_IDLE;

    
  }    
}


/*********************************************************************
 * 函數名稱      simpleBLEFindSvcUuid
 *
 * 描述   在廣播的從機UUID列表中,發現賦予特有的UUID設備
 *
 * 返回值  TRUE(成功發現) 
 */
static bool simpleBLEFindSvcUuid( uint16 uuid, uint8 *pData, uint8 dataLen )
{
  uint8 adLen;
  uint8 adType;
  uint8 *pEnd;
  
  pEnd = pData + dataLen - 1;
  
  //一直輪詢到底部
  while ( pData < pEnd )
  {
    //取得列表長度
    adLen = *pData++;
    if ( adLen > 0 )
    {
      adType = *pData;
      
      // If AD type is for 16-bit service UUID
      if ( adType == GAP_ADTYPE_16BIT_MORE || adType == GAP_ADTYPE_16BIT_COMPLETE )
      {
        pData++;
        adLen--;
        
        // 輪詢每個UUID
        while ( adLen >= 2 && pData < pEnd )
        {
          //檢查匹配
          if ( pData[0] == LO_UINT16(uuid) && pData[1] == HI_UINT16(uuid) )
          {
            // 發現配對設備
            return TRUE;
          }
          
          // 進行下一項目
          pData += 2;
          adLen -= 2;
        }
        
        // 處理可能錯誤的額外字節UUID列表中
        if ( adLen == 1 )
        {
          pData++;
        }
      }
      else
      {
        //進行下一項目
        pData += adLen;
      }
    }
  }
  
  //沒有找到匹配
  return FALSE;
}

/*********************************************************************
 * 參數名稱      simpleBLEAddDeviceInfo
 *
 * 描述     將設備添加到發現結果列表
 *
 * 返回值  無
 */
static void simpleBLEAddDeviceInfo( uint8 *pAddr, uint8 addrType )
{
  uint8 i;
  
  //如果結果數不是最大值
  if ( simpleBLEScanRes < DEFAULT_MAX_SCAN_RES )
  {
    //檢查設備是否已經在掃描結果
    for ( i = 0; i < simpleBLEScanRes; i++ )
    {
      if ( osal_memcmp( pAddr, simpleBLEDevList[i].addr , B_ADDR_LEN ) )
      {
        return;
      }
    }
    
    //添加地址到掃描結果列表
    osal_memcpy( simpleBLEDevList[simpleBLEScanRes].addr, pAddr, B_ADDR_LEN );
    simpleBLEDevList[simpleBLEScanRes].addrType = addrType;
    
    //增量掃描結果統計
    simpleBLEScanRes++;
  }
}

/*********************************************************************
 * 函數名稱      bdAddr2Str
 *
 * 參數   藍牙地址轉換爲字符串
 *
 * 返回值  無
 */
char *bdAddr2Str( uint8 *pAddr )
{
  uint8       i;
  char        hex[] = "0123456789ABCDEF";
  static char str[B_ADDR_STR_LEN];
  char        *pStr = str;
  
  *pStr++ = '0';
  *pStr++ = 'x';
  
  //從地址尾部開始
  pAddr += B_ADDR_LEN;
  
  for ( i = B_ADDR_LEN; i > 0; i-- )
  {
    *pStr++ = hex[*--pAddr >> 4];
    *pStr++ = hex[*pAddr & 0x0F];
  }
  
  *pStr = 0;
  
  return str;
}

uint8 sbpGattWriteString(uint8 *pBuffer, uint16 length)
{
    uint8 status;
    uint8 len;
    if(length > 20)
        len = 20;
    else
    len = length;
    attWriteReq_t req;
    req.handle = simpleBLECharHdl;
    req.len = len;
    req.sig = 0;//必須要填
    req.cmd = 0;//必須要填
    osal_memcpy(req.value,pBuffer,len);
    status = GATT_WriteCharValue( simpleBLEConnHandle, &req, simpleBLETaskId );

    return status;
}

uint8 str2hex(uint8 *hex);
uint8 str2hex(uint8 *str)
{
  uint8 hex[] = "0123456789ABCDEF";
  uint8 i=0,h,l;
  for(i=0;i<16;i++){
    if(hex[i]==str[0])
      h=i;
    if(hex[i]==str[1])
      l=i;
  }
  return (h*16+l);
}
uint8 str_cmp(uint8 *p1,uint8 *p2,uint8 len);
uint8 str_cmp(uint8 *p1,uint8 *p2,uint8 len)
{
  uint8 i=0;
  while(i<len){
    if(p1[i]!=p2[i])
      return 1;
    i++;
  }
  return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章