示例#1
0
/*********************************************************************
 * @fn      gapRole_init
 *
 * @brief   Initialization function for the GAP Role Task.
 *
 * @param   none
 *
 * @return  none
 */
static void gapRole_init(void)
{ 
  // Register the current thread as an ICall dispatcher application
  // so that the application can send and receive messages.
  ICall_registerApp(&selfEntity, &sem);
  
  // Get link DB maximum number of connections
  linkDBNumConns = linkDB_NumConns();

  // Setup timers as one-shot timers
  Util_constructClock(&startAdvClock, gapRole_clockHandler, 
                      0, 0, false, START_ADVERTISING_EVT);
  Util_constructClock(&updateTimeoutClock, gapRole_clockHandler,
                      0, 0, false, CONN_PARAM_TIMEOUT_EVT);
  
  // Initialize the Profile Advertising and Connection Parameters
  gapRole_profileRole = GAP_PROFILE_PERIPHERAL | GAP_PROFILE_CENTRAL;
  VOID memset(gapRole_IRK, 0, KEYLEN);
  VOID memset(gapRole_SRK, 0, KEYLEN);
  gapRole_signCounter = 0;
  gapRole_AdvEventType = GAP_ADTYPE_ADV_IND;
  gapRole_AdvDirectType = ADDRTYPE_PUBLIC;
  gapRole_AdvChanMap = GAP_ADVCHAN_ALL;
  gapRole_AdvFilterPolicy = GAP_FILTER_POLICY_ALL;

  // Restore Items from NV
  VOID osal_snv_read(BLE_NVID_IRK, KEYLEN, gapRole_IRK);
  VOID osal_snv_read(BLE_NVID_CSRK, KEYLEN, gapRole_SRK);
  VOID osal_snv_read(BLE_NVID_SIGNCOUNTER, sizeof(uint32_t), 
                     &gapRole_signCounter);
}
示例#2
0
/*********************************************************************
 * @brief   Task Initialization function.
 *
 * Internal function defined in peripheral.h.
 */
void GAPRole_Init( uint8 task_id )
{
  gapRole_TaskID = task_id;

  gapRole_state = GAPROLE_INIT;
  gapRole_ConnectionHandle = INVALID_CONNHANDLE;

  GAP_RegisterForHCIMsgs( gapRole_TaskID );

  // Initialize the Profile Advertising and Connection Parameters
  gapRole_profileRole = GAP_PROFILE_PERIPHERAL;
  VOID osal_memset( gapRole_IRK, 0, KEYLEN );
  VOID osal_memset( gapRole_SRK, 0, KEYLEN );
  gapRole_signCounter = 0;
  /* ***wkxboot***
  gapRole_AdvEventType =GAP_ADTYPE_ADV_IND;// GAP_ADTYPE_ADV_IND;
 
  gapRole_AdvDirectAddr[0]=0x39;
    gapRole_AdvDirectAddr[1]=0xce;
      gapRole_AdvDirectAddr[2]=0x8c;
        gapRole_AdvDirectAddr[3]=0x73;
          gapRole_AdvDirectAddr[4]=0x14;
            gapRole_AdvDirectAddr[5]=0x54;
  
  gapRole_AdvDirectType = ADDRTYPE_PUBLIC;
  gapRole_AdvChanMap = GAP_ADVCHAN_ALL;
  gapRole_AdvFilterPolicy = GAP_FILTER_POLICY_ALL;
*/
  // Restore Items from NV
  VOID osal_snv_read( BLE_NVID_IRK, KEYLEN, gapRole_IRK );
  VOID osal_snv_read( BLE_NVID_CSRK, KEYLEN, gapRole_SRK );
  VOID osal_snv_read( BLE_NVID_SIGNCOUNTER, sizeof( uint32 ), &gapRole_signCounter );
}
/**
 * @brief   Central Profile Task initialization function.
 *
 * @param   taskId - Task ID.
 *
 * @return  void
 */
void GAPCentralRole_Init( uint8 taskId )
{
  uint8 i;

  gapCentralRoleTaskId = taskId;
  gapRole_TaskID = taskId;

  // Initialize internal data
  for ( i = 0; i < GAPCENTRALROLE_NUM_RSSI_LINKS; i++ )
  {
    gapCentralRoleRssi[i].connHandle = GAP_CONNHANDLE_ALL;
    gapCentralRoleRssi[i].timerId = INVALID_TIMER_ID;
  }

  // Initialize parameters

  // Retore items from NV
  VOID osal_snv_read( BLE_NVID_IRK, KEYLEN, gapCentralRoleIRK );
  VOID osal_snv_read( BLE_NVID_CSRK, KEYLEN, gapCentralRoleSRK );
  VOID osal_snv_read( BLE_NVID_SIGNCOUNTER, sizeof( uint32 ), &gapCentralRoleSignCounter );

  // Register for HCI messages (for RSSI)
  GAP_RegisterForHCIMsgs( taskId );
  
  gapRole_AdvEventType = GAP_ADTYPE_ADV_NONCONN_IND;
  gapRole_AdvDirectType = ADDRTYPE_PUBLIC;
  gapRole_AdvChanMap = GAP_ADVCHAN_ALL;
  gapRole_AdvFilterPolicy = GAP_FILTER_POLICY_ALL;  
}
/*********************************************************************
* @brief   Task Initialization function.
*
* Internal function defined in peripheral.h.
*/
void GAPRole_Init( uint8 task_id )
{
  gapRole_TaskID = task_id;
  
  gapRole_state = GAPROLE_INIT;
  gapRole_ConnectionHandle = INVALID_CONNHANDLE;
  
  GAP_RegisterForHCIMsgs( gapRole_TaskID );
  
  // Initialize the Profile Advertising and Connection Parameters
  gapRole_profileRole = GAP_PROFILE_PERIPHERAL | GAP_PROFILE_OBSERVER;
  VOID osal_memset( gapRole_IRK, 0, KEYLEN );
  VOID osal_memset( gapRole_SRK, 0, KEYLEN );
  gapRole_signCounter = 0;
  gapRole_AdvEventType = GAP_ADTYPE_ADV_IND;
  gapRole_AdvDirectType = ADDRTYPE_PUBLIC;
  gapRole_AdvChanMap = GAP_ADVCHAN_ALL;
  gapRole_AdvFilterPolicy = GAP_FILTER_POLICY_ALL;
  
  // Restore Items from NV
  VOID osal_snv_read( BLE_NVID_IRK, KEYLEN, gapRole_IRK );
  VOID osal_snv_read( BLE_NVID_CSRK, KEYLEN, gapRole_SRK );
  VOID osal_snv_read( BLE_NVID_SIGNCOUNTER, sizeof( uint32 ), &gapRole_signCounter );
  
  // Register for HCI messages (for RSSI)
  //GAP_RegisterForHCIMsgs( task_id );
}
/*********************************************************************
 * @fn      gapBondMgrChangeState
 *
 * @brief   Change a state flag in the stateFlags field of the bond record.
 *
 * @param   idx - Bond NV index
 * @param   state - state flag to set or clear
 * @param   set - TRUE to set the flag, FALSE to clear the flag
 *
 * @return  TRUE if NV Record exists, FALSE if NV Record is empty
 */
static uint8 gapBondMgrChangeState( uint8 idx, uint16 state, uint8 set )
{
  gapBondRec_t bondRec;   // Space to read a Bond record from NV
  
  // Look for public address that is used (not all 0xFF's)
  if ( (osal_snv_read( mainRecordNvID(idx), sizeof ( gapBondRec_t ), &bondRec ) == SUCCESS) 
      && (osal_isbufset( bondRec.publicAddr, 0xFF, B_ADDR_LEN ) == FALSE) )
  {
    // Update the state of the bonded device.
    uint8 stateFlags = bondRec.stateFlags;
    if ( set )
    {
      stateFlags |= state;
    }
    else
    {
      stateFlags &= ~(state);
    }
    
    if ( stateFlags != bondRec.stateFlags )
    {
      bondRec.stateFlags = stateFlags;
      VOID osal_snv_write( mainRecordNvID(idx), sizeof ( gapBondRec_t ), &bondRec );
    }
    return ( TRUE );
  }
  return ( FALSE );
}
void Init_Para(void)
{
    int8 ret8 = osal_snv_read(0x80, sizeof(SYS_CONFIG), &sys_config);
    // 如果该段内存未曾写入过数据, 直接读,会返回 NV_OPER_FAILED ,
    // 我们利用这个特点作为第一次烧录后的运行, 从而设置参数的出厂设置
    if(NV_OPER_FAILED == ret8)
    {
        // 未初始化
        osal_memset(&sys_config, 0, sizeof(SYS_CONFIG));

        sys_config.update_time_ms = TEMP_DEFAULT_UPDATE_TIME_MS;
        sprintf((char*)sys_config.name, DEFAULT_DEVICE_NAME);  // 默认设备名称

        // 最高温度报警
        sys_config.tempeature_hight = DEFAULT_TEMP_HIGHT_ALERT;

        // 最低温度报警
        sys_config.tempeature_low = DEFAULT_TEMP_LOW_ALERT;

        // 4路 pwm 设置, 相对于0xFF 的占空比
        sys_config.pwm[0] = 0;
        sys_config.pwm[1] = 0;
        sys_config.pwm[2] = 255;
        sys_config.pwm[3] = 0;

        g_initFlag = FALSE;
        
        osal_snv_write(0x80, sizeof(SYS_CONFIG), &sys_config);    // 写所有参数
    }
    else
    {
        g_initFlag = TRUE;
    }
}
/**
 * @brief   Central Profile Task initialization function.
 *
 * @param   none
 *
 * @return  none
 */
static void gapCentralRole_init(void)
{
  // Register the current thread as an ICall dispatcher application
  // so that the application can send and receive messages.
  ICall_registerApp(&selfEntity, &sem);

  // Get link DB maximum number of connections
  linkDBNumConns = linkDB_NumConns();

  // Initialize parameters

  // Restore items from NV
  VOID osal_snv_read(BLE_NVID_IRK, KEYLEN, gapCentralRoleIRK);
  VOID osal_snv_read(BLE_NVID_CSRK, KEYLEN, gapCentralRoleSRK);
  VOID osal_snv_read(BLE_NVID_SIGNCOUNTER, sizeof(uint32_t), 
                     &gapCentralRoleSignCounter);
}
/*********************************************************************
 * @fn      gapBondMgrGetStateFlags
 *
 * @brief   Gets the state flags field of a bond record in NV
 *
 * @param   idx
 *
 * @return  stateFlags field
 */
static uint8 gapBondMgrGetStateFlags( uint8 idx )
{
  gapBondRec_t bondRec;
  
  VOID osal_snv_read( mainRecordNvID(idx), sizeof ( gapBondRec_t ), &bondRec );
  
  return ( bondRec.stateFlags );
  
}
示例#9
0
/***************************************************************************************************
 * @fn      isPaired
 *
 * @brief   is paired
 *
 * @param   None
 *
 * @return  True:paired;Flase:not
 ***************************************************************************************************/
bool isPaired()
{
  uint8 ret8;
  
  //read sys config from snv
  osal_memset(&sys_config, 0, sizeof(sys_config));
  ret8 = osal_snv_read(BLE_NVID_SYS_CONF, sizeof(SYS_CONFIG), &sys_config);   
  if(ret8 != SUCCESS)
  {
    //read err;
  }
  
  osal_snv_read(BLE_NVID_PAR, sizeof(BLE_PARAMETER), &ble_parameter);
  
  if(sys_config.parity == false)
  {
      return false;   
  } else
  {
      return true;
  }
}
示例#10
0
文件: central.c 项目: AubrCool/BLE
/**
 * @brief   Central Profile Task initialization function.
 *
 * @param   taskId - Task ID.
 *
 * @return  void
 */
void GAPCentralRole_Init( uint8 taskId )
{
  uint8 i;

  gapCentralRoleTaskId = taskId;

  // Initialize internal data
  for ( i = 0; i < GAPCENTRALROLE_NUM_RSSI_LINKS; i++ )
  {
    gapCentralRoleRssi[i].connHandle = GAP_CONNHANDLE_ALL;
    gapCentralRoleRssi[i].timerId = INVALID_TIMER_ID;
  }

  // Initialize parameters

  // Retore items from NV
  VOID osal_snv_read( BLE_NVID_IRK, KEYLEN, gapCentralRoleIRK );
  VOID osal_snv_read( BLE_NVID_CSRK, KEYLEN, gapCentralRoleSRK );
  VOID osal_snv_read( BLE_NVID_SIGNCOUNTER, sizeof( uint32 ), &gapCentralRoleSignCounter );

  // Register for HCI messages (for RSSI)
  GAP_RegisterForHCIMsgs( taskId );
}
/*********************************************************************
 * @fn      gapBondMgrFindEmpty
 *
 * @brief   Look through the bonding NV entries to find an empty.
 *
 * @param   none
 *
 * @return  index to empty bonding (0 - (GAP_BONDINGS_MAX-1),
 *          GAP_BONDINGS_MAX if no empty entries
 */
static uint8 gapBondMgrFindEmpty( void )
{
  // Item doesn't exist, so create all the items
  for ( uint8 idx = 0; idx < GAP_BONDINGS_MAX; idx++ )
  {
    gapBondRec_t bondRec; // Bond record work place
    
    // Look for public address of all 0xFF's
    if ( (osal_snv_read( mainRecordNvID(idx), sizeof ( gapBondRec_t ), &bondRec ) == SUCCESS) 
        && (osal_isbufset( bondRec.publicAddr, 0xFF, B_ADDR_LEN )) )
    {
      return ( idx ); // Found one
    }
  }
  
  return ( GAP_BONDINGS_MAX );
}
/*********************************************************************
 * @fn      gapBondMgrFindAddr
 *
 * @brief   Look through the bonding NV entries to find an address.
 *
 * @param   pDevAddr - device address to look for
 *
 * @return  index to empty bonding (0 - (GAP_BONDINGS_MAX-1),
 *          GAP_BONDINGS_MAX if no empty entries
 */
static uint8 gapBondMgrFindAddr( uint8 *pDevAddr )
{
  // Item doesn't exist, so create all the items
  for ( uint8 idx = 0; idx < GAP_BONDINGS_MAX; idx++ )
  {
    gapBondRec_t bondRec; // Bond record work place
    
    // Read in NV Main Bond Record and compare public address
    if ( (osal_snv_read( mainRecordNvID(idx), sizeof ( gapBondRec_t ), &bondRec ) == SUCCESS) 
        && (osal_memcmp( bondRec.publicAddr, pDevAddr, B_ADDR_LEN )) )
    {
      return ( idx ); // Found it
    }
  }
  
  return ( GAP_BONDINGS_MAX );
}
/*********************************************************************
 * @fn      gapBondMgrBondTotal
 *
 * @brief   Look through the bonding NV entries calculate the number
 *          entries.
 *
 * @param   none
 *
 * @return  total number of bonds found
 */
static uint8 gapBondMgrBondTotal( void )
{
  uint8 bonds = 0;
  
  // Item doesn't exist, so create all the items
  for ( uint8 idx = 0; idx < GAP_BONDINGS_MAX; idx++ )
  {
    gapBondRec_t bondRec; // Bond record work place
    
    // Look for public address that are not 0xFF's
    if ( (osal_snv_read( mainRecordNvID(idx), sizeof ( gapBondRec_t ), &bondRec ) == SUCCESS) 
        && (osal_isbufset( bondRec.publicAddr, 0xFF, B_ADDR_LEN ) == FALSE) )
    {
      bonds++; // Found one
    }
  }
  
  return ( bonds );
}
/*********************************************************************
 * @brief   Task Initialization function.
 *
 * Internal function defined in gapperiphbondmgr.h.
 */
void GAPBondMgr_Init( uint8 task_id )
{
  gapBondRec_t bondRec;         // Work space for Bond Record
  gapBondMgr_TaskID = task_id;  // Save task ID
  
  // Initialize the NV needed for bonding
  if ( osal_snv_read( mainRecordNvID(0), sizeof ( gapBondRec_t ), &bondRec ) != SUCCESS )
  {
    // Can't read the first entry, assume that NV doesn't exist and erase all
    // Bond NV entries (initialize)
    VOID gapBondMgrEraseAllBondings();
  }
  
  // Take over the processing of Authentication messages
  VOID GAP_SetParamValue( TGAP_AUTH_TASK_ID, gapBondMgr_TaskID );
  
  // Check the total number of bonds
  gapBondSetupPrivFlag();
}
示例#15
0
/**************************************************************************************************
 * @fn      HalMotionConfig
 *
 * @brief   Configure the Motion Sensor serivce
 *
 * @param   measCback - pointer to the motion sensor results data callback function
 *
 * @return  None
 **************************************************************************************************/
void HalMotionConfig( halMotionCBack_t measCback )
{
  uint8 snvStatus;

  /* Register the callback fucntion */
  pHalMotionProcessFunction = measCback;

  /* Set up data used by Movea's motion processing library */
  HalMotionMouseGainTableIndex = HAL_MOTION_DEFAULT_GAIN_TABLE_INDEX;
  snvStatus = osal_snv_read( HAL_MOTION_NV_ITEM_GYRO_OFFSETS_ID,
                             sizeof( HalMotionGyroOffsets ),
                             (uint8 *)&HalMotionGyroOffsets );
  if (snvStatus != SUCCESS)
  {
    /* read failed, so use settings that indicate no bias is present */
    HalMotionGyroOffsets.x = 0;
    HalMotionGyroOffsets.y = 0;
    HalMotionGyroOffsets.z = 0;
  }
}
/*********************************************************************
 * @fn      gapBondMgrGetPublicAddr
 *
 * @brief   Copy the public Address from a bonding record
 *
 * @param   idx - Bond record index
 * @param   pAddr - a place to put the public address from NV
 *
 * @return  SUCCESS if successful.
 *          Otherwise failure.
 */
static bStatus_t gapBondMgrGetPublicAddr( uint8 idx, uint8 *pAddr )
{
  bStatus_t stat;         // return value
  gapBondRec_t bondRec;   // Work space for main bond record

  // Check parameters  
  if ( (idx >= GAP_BONDINGS_MAX) || (pAddr == NULL) )
  {
    return ( INVALIDPARAMETER );
  }
  
  stat = osal_snv_read( mainRecordNvID(idx), sizeof ( gapBondRec_t ), &bondRec );
  
  if ( stat == SUCCESS ) 
  {
    VOID osal_memcpy( pAddr, bondRec.publicAddr, KEYLEN );
  }
  
  return ( stat );
}
示例#17
0
/*********************************************************************
 * @fn      SimpleBLEPeripheral_Init
 *
 * @brief   Initialization function for the Simple BLE Peripheral App Task.
 *          This is called during initialization and should contain
 *          any application specific initialization (ie. hardware
 *          initialization/setup, table initialization, power up
 *          notificaiton ... ).
 *
 * @param   task_id - the ID assigned by OSAL.  This ID should be
 *                    used to send messages and set timers.
 *
 * @return  none
 */
void SimpleBLEPeripheral_Init( uint8 task_id )
{
  simpleBLEPeripheral_TaskID = task_id;

  // Setup the GAP
  VOID GAP_SetParamValue( TGAP_CONN_PAUSE_PERIPHERAL, DEFAULT_CONN_PAUSE_PERIPHERAL );
  
  // Setup the GAP Peripheral Role Profile
  {
    #if defined( CC2540_MINIDK )
      // For the CC2540DK-MINI keyfob, device doesn't start advertising until button is pressed
      uint8 initial_advertising_enable = FALSE;
    #else
      // For other hardware platforms, device starts advertising upon initialization
      uint8 initial_advertising_enable = TRUE;
    #endif

    // By setting this to zero, the device will go into the waiting state after
    // being discoverable for 30.72 second, and will not being advertising again
    // until the enabler is set back to TRUE
    uint16 gapRole_AdvertOffTime = 0;

    uint8 enable_update_request = DEFAULT_ENABLE_UPDATE_REQUEST;
    uint16 desired_min_interval = DEFAULT_DESIRED_MIN_CONN_INTERVAL;
    uint16 desired_max_interval = DEFAULT_DESIRED_MAX_CONN_INTERVAL;
    uint16 desired_slave_latency = DEFAULT_DESIRED_SLAVE_LATENCY;
    uint16 desired_conn_timeout = DEFAULT_DESIRED_CONN_TIMEOUT;

    // Set the GAP Role Parameters
    GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &initial_advertising_enable );
    GAPRole_SetParameter( GAPROLE_ADVERT_OFF_TIME, sizeof( uint16 ), &gapRole_AdvertOffTime );

    GAPRole_SetParameter( GAPROLE_SCAN_RSP_DATA, sizeof ( scanRspData ), scanRspData );
    GAPRole_SetParameter( GAPROLE_ADVERT_DATA, sizeof( advertData ), advertData );

    GAPRole_SetParameter( GAPROLE_PARAM_UPDATE_ENABLE, sizeof( uint8 ), &enable_update_request );
    GAPRole_SetParameter( GAPROLE_MIN_CONN_INTERVAL, sizeof( uint16 ), &desired_min_interval );
    GAPRole_SetParameter( GAPROLE_MAX_CONN_INTERVAL, sizeof( uint16 ), &desired_max_interval );
    GAPRole_SetParameter( GAPROLE_SLAVE_LATENCY, sizeof( uint16 ), &desired_slave_latency );
    GAPRole_SetParameter( GAPROLE_TIMEOUT_MULTIPLIER, sizeof( uint16 ), &desired_conn_timeout );
    
    //ÉèÖÃRSSI »ñÈ¡ËÙÂÊ
    uint16 rssi_rate = RSSI_RATE;
    GAPRole_SetParameter(GAPROLE_RSSI_READ_RATE,sizeof(uint16),&rssi_rate);
  }

  // Set the GAP Characteristics
  GGS_SetParameter( GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, attDeviceName );

  // Set advertising interval
  {
    uint16 advInt = DEFAULT_ADVERTISING_INTERVAL;

    GAP_SetParamValue( TGAP_LIM_DISC_ADV_INT_MIN, advInt );
    GAP_SetParamValue( TGAP_LIM_DISC_ADV_INT_MAX, advInt );
    GAP_SetParamValue( TGAP_GEN_DISC_ADV_INT_MIN, advInt );
    GAP_SetParamValue( TGAP_GEN_DISC_ADV_INT_MAX, advInt );
  }

  // Setup the GAP Bond Manager
  {
    uint32 passkey = 0; // passkey "000000"
    uint8 pairMode = GAPBOND_PAIRING_MODE_WAIT_FOR_REQ;
    uint8 mitm = TRUE;
    uint8 ioCap = GAPBOND_IO_CAP_DISPLAY_ONLY;
    uint8 bonding = TRUE;
    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 );
  }

  // Initialize GATT attributes Ìí¼ÓÁË4¸öService ·þÎñ
  GGS_AddService( GATT_ALL_SERVICES );            // GAP
  GATTServApp_AddService( GATT_ALL_SERVICES );    // GATT attributes
  DevInfo_AddService();                           // Device Information Service
  SimpleProfile_AddService( GATT_ALL_SERVICES );  // Simple GATT Profile ankiÐèÒªÐ޸ĵķþÎñ
#if defined FEATURE_OAD
  VOID OADTarget_AddService();                    // OAD Profile
#endif

  // Setup the SimpleProfile Characteristic Values
  {
    //³õʼ»¯±àÒë½øÈ¥µÄµÆ¹âÑÕÉ«
    uint8 charValue1[20] = {0, 1,255,100,100,255,255,255,   20,1,1,255,1,200,    20,100,100,20,100,10};
    uint8 charValue2[20] = {20,1,1,20,1,1,20,1,250,20,1,250,20,1,250,20,1,250,1};
    uint8 charValue3 = 3;
    uint8 charValue4 = 4;
    uint8 charValue5[SIMPLEPROFILE_CHAR5_LEN] = { 1, 2, 3, 4, 5 };
    
     #if (defined HAL_LCD) && (HAL_LCD == TRUE)
      //´ÓÎļþÖжÁÈ¡
      uint8 wirteTag = osal_snv_read(0x80,20,charValue1);
      osal_snv_read(0x95,20,charValue2);
      if( wirteTag == SUCCESS){
          HalLcdWriteStringValue("read Ok",(uint16)wirteTag,10, HAL_LCD_LINE_6 );
      }else{
        HalLcdWriteStringValue("read failed",(uint16)wirteTag,10, HAL_LCD_LINE_6 );
           //½øÐгõʼ»¯
         wirteTag = osal_snv_write(0x80,20,charValue1);
         osal_snv_write(0x95,20,charValue1);
         if(wirteTag == SUCCESS){
            HalLcdWriteStringValue( "init", (uint16)wirteTag, 10,  HAL_LCD_LINE_7 );
         }else{
            HalLcdWriteStringValue("init failed", (uint16)wirteTag,10, HAL_LCD_LINE_7 );
         }
      }
     #else 
      if( osal_snv_read(0x80,20,charValue1) != SUCCESS){
           //½øÐгõʼ»¯
         //osal_snv_write(0x80,20,charValue1);
         //HalLcdWriteStringValue( "rece:", osal_snv_write(0x80,20,charValue1), 10,  HAL_LCD_LINE_8 );
         osal_snv_write(0x95,20,charValue2);
      }
     #endif // (defined HAL_LCD) && (HAL_LCD == TRUE)
    
    
    SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR1, 20, &charValue1 );
    SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR2, 20, &charValue2 );
    SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR3, sizeof ( uint8 ), &charValue3 );
    //Ç°Ãæ3¾äÖ»ÊǶԶÔÏóÖµµÄÉèÖã¬Õâ¾ä´úÂë ½øÐÐÁË£¬ServiceµÄcharacteristicÉèÖã¬Process Client Characteristis Configuration Change
    SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR4, sizeof ( uint8 ), &charValue4 ); 
    SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR5, SIMPLEPROFILE_CHAR5_LEN, charValue5 );
  }


#if defined( CC2540_MINIDK )

  SK_AddService( GATT_ALL_SERVICES ); // Simple Keys Profile

  // Register for all key events - This app will handle all key events¡£ ×¢²á°´Å¥Ê¼þ£¬OSAL´¦Àí°´Å¥Ê¼þ
  RegisterForKeys( simpleBLEPeripheral_TaskID );

  // makes sure LEDs are off
  HalLedSet( (HAL_LED_1 | HAL_LED_2), HAL_LED_MODE_OFF );



#endif // #if defined( CC2540_MINIDK )

#if (defined HAL_LCD) && (HAL_LCD == TRUE)

#if defined FEATURE_OAD
  #if defined (HAL_IMAGE_A)
    HalLcdWriteStringValue( "BLE Peri-A", OAD_VER_NUM( _imgHdr.ver ), 16, HAL_LCD_LINE_1 );
  #else
    HalLcdWriteStringValue( "BLE Peri-B", OAD_VER_NUM( _imgHdr.ver ), 16, HAL_LCD_LINE_1 );
  #endif // HAL_IMAGE_A
#else
  HalLcdWriteString( "BLE Peripheral", HAL_LCD_LINE_1 );
#endif // FEATURE_OAD

#endif // (defined HAL_LCD) && (HAL_LCD == TRUE)

  // Register callback with SimpleGATTprofile
  // ¸Ã»Øµ÷±» simpleProfile_WriteAttrCB ·½·¨´¥·¢£¬simpleProfileCBs °üº¬´Ë·½·¨£¬ÔÚSimpleProfile_AddService µÄʱºò×¢²áµ½GATTЭÒéÕ»·þÎñÖÐ
  //Öµ¸Ä±äÖ®ºó£¬Í¨Öª PROFILES--->SimpleProfileCBs.simpleProfile_WriteAttrCB  È»ºóÔÙ֪ͨAPP--->simpleBLEPeripheral_SimpleProfileCBs
  VOID SimpleProfile_RegisterAppCBs( &simpleBLEPeripheral_SimpleProfileCBs );

  // Enable clock divide on halt
  // This reduces active current while radio is active and CC254x MCU
  // is halted
  //²»É¾³ý  PWM²»Îȶ¨
  //HCI_EXT_ClkDivOnHaltCmd( HCI_EXT_ENABLE_CLK_DIVIDE_ON_HALT );

#if defined ( DC_DC_P0_7 )

  // Enable stack to toggle bypass control on TPS62730 (DC/DC converter)
  HCI_EXT_MapPmIoPortCmd( HCI_EXT_PM_IO_PORT_P0, HCI_EXT_PM_IO_PORT_PIN7 );

#endif // defined ( DC_DC_P0_7 )

  // Setup a delayed profile startup  ·¢ÆðBLEÁ¬½Ó³õʼ»¯Ïà¹Ø·þÎñ¡£ÏÂÃæ·½·¨¶Ô SBP_START_DEVICE_EVT ʼþ½øÐд¦Àí
  osal_set_event( simpleBLEPeripheral_TaskID, SBP_START_DEVICE_EVT );

}
示例#18
0
/*********************************************************************
* @fn      HidKbdMouse_Init
*
* @brief   Initialization function for the HidKbdMouse App Task.
*          This is called during initialization and should contain
*          any application specific initialization (ie. hardware
*          initialization/setup, table initialization, power up
*          notificaiton ... ).
*
* @param   task_id - the ID assigned by OSAL.  This ID should be
*                    used to send messages and set timers.
*
* @return  none
*/
void HidKbdMouse_Init( uint8 task_id )
{
  setupUART();
  GenerateCRCTable();
  //printf("%x\n",default_name_crc);
  device_name = osal_mem_alloc(20);
  device_name_length = osal_mem_alloc(1);
  device_name_crc = osal_mem_alloc(1);
  
  hidKbdMouseTaskId = task_id;
  
  // Setup the GAP
  VOID GAP_SetParamValue( TGAP_CONN_PAUSE_PERIPHERAL, DEFAULT_CONN_PAUSE_PERIPHERAL );
  
  // Setup the GAP Peripheral Role Profile
  {
    uint8 initial_advertising_enable = TRUE; //previously FALSE
    
    // By setting this to zero, the device will go into the waiting state after
    // being discoverable for 30.72 second, and will not being advertising again
    // until the enabler is set back to TRUE
    uint16 gapRole_AdvertOffTime = 0;
    
    uint8 enable_update_request = DEFAULT_ENABLE_UPDATE_REQUEST;
    uint16 desired_min_interval = DEFAULT_DESIRED_MIN_CONN_INTERVAL;
    uint16 desired_max_interval = DEFAULT_DESIRED_MAX_CONN_INTERVAL;
    uint16 desired_slave_latency = DEFAULT_DESIRED_SLAVE_LATENCY;
    uint16 desired_conn_timeout = DEFAULT_DESIRED_CONN_TIMEOUT;
    
    // Set the GAP Role Parameters
    GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &initial_advertising_enable );
    GAPRole_SetParameter( GAPROLE_ADVERT_OFF_TIME, sizeof( uint16 ), &gapRole_AdvertOffTime );
    
    GAPRole_SetParameter( GAPROLE_ADVERT_DATA, sizeof( advData ), advData );
    
    //name change - 21/12/2014
    osal_snv_read(SNV_ID_DEVICE_NAME_CRC, 1, device_name_crc);
    osal_snv_read(SNV_ID_DEVICE_NAME_LENGTH, 1, device_name_length);
    osal_snv_read(SNV_ID_DEVICE_NAME, 20, device_name);
    
    if(*device_name_crc != getCRC(device_name, *device_name_length)) {
      printf("Using default scan response name\r\n");
      GAPRole_SetParameter( GAPROLE_SCAN_RSP_DATA, sizeof ( default_scanData ), default_scanData );
    } else {      
      //make changes directly to the default_scanData. Since this variable is set at start-up, it should not matter
      uint8 len = *device_name_length;
      //uint8 default_name_length = default_scanData[0];
      default_scanData[0] = len + 1;
      uint8 i;
      for(i = 0; i < len; i++) {
        default_scanData[i+2] = device_name[i];
      }      
      GAPRole_SetParameter( GAPROLE_SCAN_RSP_DATA, sizeof ( default_scanData ), default_scanData );
    }
    
    GAPRole_SetParameter( GAPROLE_PARAM_UPDATE_ENABLE, sizeof( uint8 ), &enable_update_request );
    GAPRole_SetParameter( GAPROLE_MIN_CONN_INTERVAL, sizeof( uint16 ), &desired_min_interval );
    GAPRole_SetParameter( GAPROLE_MAX_CONN_INTERVAL, sizeof( uint16 ), &desired_max_interval );
    GAPRole_SetParameter( GAPROLE_SLAVE_LATENCY, sizeof( uint16 ), &desired_slave_latency );
    GAPRole_SetParameter( GAPROLE_TIMEOUT_MULTIPLIER, sizeof( uint16 ), &desired_conn_timeout );
  }
  
  // Set the GAP Characteristics
  if(*device_name_crc != getCRC(device_name, *device_name_length)) {
    //    printf("Using default device name");
    GGS_SetParameter( GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, (void *) attDeviceName );
  } else {
    //    printf("Using stored device name");
    //    printf("%s\r\n", device_name);
    GGS_SetParameter( GGS_DEVICE_NAME_ATT, *device_name_length + 1, (void *) device_name );
  }
  //Allow device to change name
  uint8 devNamePermission = GATT_PERMIT_READ|GATT_PERMIT_WRITE; 
  GGS_SetParameter( GGS_W_PERMIT_DEVICE_NAME_ATT, sizeof ( uint8 ), &devNamePermission );
  
  // Setup the GAP Bond Manager
  {
    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 );
  }
  
  // Setup Battery Characteristic Values
  {
    uint8 critical = DEFAULT_BATT_CRITICAL_LEVEL;
    Batt_SetParameter( BATT_PARAM_CRITICAL_LEVEL, sizeof (uint8), &critical );
  }
  
  // Set up HID keyboard service
  HidKbM_AddService( );
  
  // Register for HID Dev callback
  HidDev_Register( &hidKbdMouseCfg, &hidKbdMouseHidCBs );
  
  // Register for all key events - This app will handle all key events
  RegisterForKeys( hidKbdMouseTaskId );
  
#if defined( CC2540_MINIDK )
  // makes sure LEDs are off
  HalLedSet( (HAL_LED_1 | HAL_LED_2), HAL_LED_MODE_OFF );
  
  // For keyfob board set GPIO pins into a power-optimized state
  // Note that there is still some leakage current from the buzzer,
  // accelerometer, LEDs, and buttons on the PCB.
  
  P0SEL = 0; // Configure Port 0 as GPIO
  P1SEL = 0; // Configure Port 1 as GPIO
  P2SEL = 0; // Configure Port 2 as GPIO
  
  P0DIR = 0xFC; // Port 0 pins P0.0 and P0.1 as input (buttons),
  // all others (P0.2-P0.7) as output
  P1DIR = 0xFF; // All port 1 pins (P1.0-P1.7) as output
  P2DIR = 0x1F; // All port 1 pins (P2.0-P2.4) as output
  
  P0 = 0x03; // All pins on port 0 to low except for P0.0 and P0.1 (buttons)
  P1 = 0;   // All pins on port 1 to low
  P2 = 0;   // All pins on port 2 to low
  
#endif // #if defined( CC2540_MINIDK )
  
  //init keyboard report manager
  KBD_Report_Init();
  
  // Setup a delayed profile startup
  osal_set_event( hidKbdMouseTaskId, START_DEVICE_EVT );
}
/*********************************************************************
 * @brief   Notify the Bond Manager that a connection has been made.
 *
 * Public function defined in gapperiphbondmgr.h.
 */
bStatus_t GAPBondMgr_LinkEst( uint8 addrType, uint8 *pDevAddr, uint16 connHandle )
{
  uint8 idx;                          // NV Index
  uint8 publicAddr[B_ADDR_LEN]        // Place to put the public address
      = {0, 0, 0, 0, 0, 0};
  
  idx = GAPBondMgr_ResolveAddr( addrType, pDevAddr, publicAddr );
  if ( idx < GAP_BONDINGS_MAX )
  {
    // Bonding found
    uint8 stateFlags;             // Bond state flags
    smSecurityInfo_t localLTK;    // LTK information
    smSigningInfo_t signingInfo;  // Signature information
    
    // Initialize the NV structures
    osal_memset( &localLTK, 0, sizeof ( smSecurityInfo_t ) );
    osal_memset( &signingInfo, 0, sizeof ( smSigningInfo_t ) );
    
    // Check if key is valid, then load the key
    stateFlags = gapBondMgrGetStateFlags( idx );
    if ( osal_snv_read( localLTKNvID(idx), sizeof ( smSecurityInfo_t ), &localLTK ) == SUCCESS )
    {
      if ( (localLTK.keySize >= MIN_ENC_KEYSIZE) && (localLTK.keySize <= MAX_ENC_KEYSIZE) )
      {
        // Load the key information for the bonding
        VOID GAP_Bond( connHandle, 
                      ((stateFlags & GAP_BONDED_STATE_AUTHENTICATED) ? TRUE : FALSE),
                      &localLTK );
      }
    }
    
    // Load the Signing Key
    if ( osal_snv_read( devCSRKNvID(idx), KEYLEN, signingInfo.srk ) == SUCCESS )
    {
      if ( osal_isbufset( signingInfo.srk, 0xFF, KEYLEN ) == FALSE )
      {
        // Load the signing information for this connection
        VOID osal_snv_read( devSignCounterNvID(idx), sizeof ( uint32 ), &(signingInfo.signCounter) );
        VOID GAP_Signable( connHandle, 
                          ((stateFlags & GAP_BONDED_STATE_AUTHENTICATED) ? TRUE : FALSE),
                          &signingInfo );
      }
    }
    
    // Has there been a service change?
    if ( stateFlags & GAP_BONDED_STATE_SERVICE_CHANGED )
    {
      VOID GATT_ServiceChangedInd( connHandle, gapBondMgr_TaskID );
    }
  }
  else
  {
    // Not bound
    if ( gapBond_PairingMode == GAPBOND_PAIRING_MODE_INITIATE )
    {
      // Could add code to setup a timeout to initiate security
      // with a Slave Security Request.
    }
  }
  
  return ( SUCCESS );
}
示例#20
0
/*********************************************************************
 * @fn      SimpleBLEPeripheral_Init
 *
 * @brief   Initialization function for the Simple BLE Peripheral App Task.
 *          This is called during initialization and should contain
 *          any application specific initialization (ie. hardware
 *          initialization/setup, table initialization, power up
 *          notificaiton ... ).
 *
 * @param   task_id - the ID assigned by OSAL.  This ID should be
 *                    used to send messages and set timers.
 *
 * @return  none
 */
void SimpleBLEPeripheral_Init( uint8 task_id )
{
  uint8 read_tmp[6] = {0};
  uint8 ret8;
   
  simpleBLEPeripheral_TaskID = task_id;
  
  if(osal_snv_read(0xfe,1,&gMP)!=NV_OPER_FAILED){
	  advertData[29]=gMP;
  }
  
  // 如果该段内存未曾写入过数据, 直接读,会返回 NV_OPER_FAILED ,
  // 我们利用这个特点作为第一次烧录后的运行, 从而设置参数的出厂设置
  ret8 = osal_snv_read(admin_flash_start_addr , sizeof(read_tmp), read_tmp);//admin pwd
  if(NV_OPER_FAILED == ret8)
  {
    osal_memset(read_tmp, '0', sizeof(read_tmp));
    ret8 = osal_snv_write(admin_flash_start_addr, sizeof(read_tmp), read_tmp);
    if(ret8 == NV_OPER_FAILED)
      return;
    
    ret8 = osal_snv_read(admin_flash_start_addr , sizeof(read_tmp), read_tmp);
    if(ret8 == NV_OPER_FAILED)
      return;
  }
  
  ret8 = osal_snv_read(user_flash_start_addr , sizeof(read_tmp), read_tmp);//user pwd
  if(NV_OPER_FAILED == ret8)
  {
    osal_memset(read_tmp, '1', sizeof(read_tmp));
    ret8 = osal_snv_write(user_flash_start_addr, sizeof(read_tmp), read_tmp);
    if(ret8 == NV_OPER_FAILED)
      return;
    
    ret8 = osal_snv_read(user_flash_start_addr , sizeof(read_tmp), read_tmp);
    if(ret8 == NV_OPER_FAILED)
      return;
  }
  
  ret8 = osal_snv_read(ssid_flash_start_addr , sizeof(read_tmp), read_tmp);//ssid 
  if(NV_OPER_FAILED == ret8)
  {
    osal_memcpy(read_tmp,  ssid,  6);
    ret8 = osal_snv_write(ssid_flash_start_addr, sizeof(read_tmp), read_tmp);
    if(ret8 == NV_OPER_FAILED)
      return;
   
    ret8 = osal_snv_read(ssid_flash_start_addr , sizeof(read_tmp), read_tmp);
    if(ret8 == NV_OPER_FAILED)
      return;
  }
  else//update ssid from flash
  {
    ret8 = osal_snv_read(ssid_flash_start_addr , sizeof(read_tmp), read_tmp);
    if(ret8 != NV_OPER_FAILED)
    {
      osal_memcpy(scanRspData + 2, read_tmp, 6);
      osal_memcpy(attDeviceName, read_tmp, 6);
      GAP_UpdateAdvertisingData( simpleBLEPeripheral_TaskID, FALSE, sizeof( scanRspData ), scanRspData );
      GGS_SetParameter( GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, attDeviceName );
    }
  }
  
  ret8 = osal_snv_read(dead_date_flash_start_addr , sizeof(read_tmp), read_tmp);//dead date
  if(NV_OPER_FAILED == ret8)
  {
    osal_memset(read_tmp, '0', sizeof(read_tmp));
    ret8 = osal_snv_write(dead_date_flash_start_addr, sizeof(read_tmp), read_tmp);
    if(ret8 == NV_OPER_FAILED)
      return;
    
    ret8 = osal_snv_read(dead_date_flash_start_addr , sizeof(read_tmp), read_tmp);
    if(ret8 == NV_OPER_FAILED)
      return;
  }
  
  ret8 = osal_snv_read(carlock_id_flash_start_addr , sizeof(read_tmp), read_tmp);//lock id
  if(NV_OPER_FAILED == ret8)
  {
    osal_memset(read_tmp, '0', sizeof(read_tmp));
    ret8 = osal_snv_write(carlock_id_flash_start_addr, sizeof(read_tmp), read_tmp);
    if(ret8 == NV_OPER_FAILED)
      return;
    
    ret8 = osal_snv_read(carlock_id_flash_start_addr , sizeof(read_tmp), read_tmp);
    if(ret8 == NV_OPER_FAILED)
      return;
  }
  
  uint8 use_lock_times[2] = {0};
  ret8 = osal_snv_read(use_lock_times_start_addr , sizeof(use_lock_times), use_lock_times);//use times
  if(NV_OPER_FAILED == ret8)
  {
    osal_memset(use_lock_times, 0, sizeof(use_lock_times));
    ret8 = osal_snv_write(use_lock_times_start_addr, sizeof(use_lock_times), use_lock_times);
    if(ret8 == NV_OPER_FAILED)
      return;
    
    ret8 = osal_snv_read(use_lock_times_start_addr , sizeof(use_lock_times), use_lock_times);
    if(ret8 == NV_OPER_FAILED)
      return;
  }
  
  // Setup the GAP
  VOID GAP_SetParamValue( TGAP_CONN_PAUSE_PERIPHERAL, DEFAULT_CONN_PAUSE_PERIPHERAL );
  
  // Setup the GAP Peripheral Role Profile
  {
    #if defined( CC2540_MINIDK )
      // For the CC2540DK-MINI keyfob, device doesn't start advertising until button is pressed
      uint8 initial_advertising_enable = FALSE;
    #else
      // For other hardware platforms, device starts advertising upon initialization
      uint8 initial_advertising_enable = TRUE;
    #endif

    // By setting this to zero, the device will go into the waiting state after
    // being discoverable for 30.72 second, and will not being advertising again
    // until the enabler is set back to TRUE
    uint16 gapRole_AdvertOffTime = 0;

    uint8 enable_update_request = DEFAULT_ENABLE_UPDATE_REQUEST;
    uint16 desired_min_interval = DEFAULT_DESIRED_MIN_CONN_INTERVAL;
    uint16 desired_max_interval = DEFAULT_DESIRED_MAX_CONN_INTERVAL;
    uint16 desired_slave_latency = DEFAULT_DESIRED_SLAVE_LATENCY;
    uint16 desired_conn_timeout = DEFAULT_DESIRED_CONN_TIMEOUT;

    // Set the GAP Role Parameters      
    GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &initial_advertising_enable );
    GAPRole_SetParameter( GAPROLE_ADVERT_OFF_TIME, sizeof( uint16 ), &gapRole_AdvertOffTime );

    GAPRole_SetParameter( GAPROLE_SCAN_RSP_DATA, sizeof ( scanRspData ), scanRspData );
    GAPRole_SetParameter( GAPROLE_ADVERT_DATA, sizeof( advertData ), advertData );

    GAPRole_SetParameter( GAPROLE_PARAM_UPDATE_ENABLE, sizeof( uint8 ), &enable_update_request );
    GAPRole_SetParameter( GAPROLE_MIN_CONN_INTERVAL, sizeof( uint16 ), &desired_min_interval );
    GAPRole_SetParameter( GAPROLE_MAX_CONN_INTERVAL, sizeof( uint16 ), &desired_max_interval );
    GAPRole_SetParameter( GAPROLE_SLAVE_LATENCY, sizeof( uint16 ), &desired_slave_latency );
    GAPRole_SetParameter( GAPROLE_TIMEOUT_MULTIPLIER, sizeof( uint16 ), &desired_conn_timeout );
  }

  // Set the GAP Characteristics
  GGS_SetParameter( GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, attDeviceName );

  // Set advertising interval
  {
    uint16 advInt = DEFAULT_ADVERTISING_INTERVAL;

    GAP_SetParamValue( TGAP_LIM_DISC_ADV_INT_MIN, advInt );
    GAP_SetParamValue( TGAP_LIM_DISC_ADV_INT_MAX, advInt );
    GAP_SetParamValue( TGAP_GEN_DISC_ADV_INT_MIN, advInt );
    GAP_SetParamValue( TGAP_GEN_DISC_ADV_INT_MAX, advInt );
	
  }

  // Setup the GAP Bond Manager   //设定绑定的管理员
  {
    uint32 passkey = 0; // passkey "000000"     //配对密码
    uint8 pairMode = GAPBOND_PAIRING_MODE_WAIT_FOR_REQ;
    //uint8 pairMode = GAPBOND_PAIRING_MODE_INITIATE; //需要将 pairMode 设置为 GAPBOND_PAIRING_MODE_INITIATE,
                                                    //才能在连接的时候产生配对请求 
    uint8 mitm = TRUE;
    uint8 ioCap = GAPBOND_IO_CAP_DISPLAY_ONLY;      //只有显示密码的能力
    uint8 bonding = TRUE;
    GAPBondMgr_SetParameter( GAPBOND_DEFAULT_PASSCODE, sizeof ( uint32 ), &passkey );//把passkey的地址里面的值拷贝到 gapBond_Passcode变量
    GAPBondMgr_SetParameter( GAPBOND_PAIRING_MODE, sizeof ( uint8 ), &pairMode );//同理把pairMode地址里面的值拷贝到gapBond_PairingMode
    GAPBondMgr_SetParameter( GAPBOND_MITM_PROTECTION, sizeof ( uint8 ), &mitm );//同理
    GAPBondMgr_SetParameter( GAPBOND_IO_CAPABILITIES, sizeof ( uint8 ), &ioCap );//同理
    GAPBondMgr_SetParameter( GAPBOND_BONDING_ENABLED, sizeof ( uint8 ), &bonding ); //同理
  }

  // Initialize GATT attributes
  GGS_AddService( GATT_ALL_SERVICES );            // GAP
  GATTServApp_AddService( GATT_ALL_SERVICES );    // GATT attributes
  DevInfo_AddService();                           // Device Information Service
  SimpleProfile_AddService( GATT_ALL_SERVICES );  // Simple GATT Profile
#if defined FEATURE_OAD
  VOID OADTarget_AddService();                    // OAD Profile
#endif

  // Setup the SimpleProfile Characteristic Values
  {
    uint8 charValue1[SIMPLEPROFILE_CHAR1_LEN] = {0};
    uint8 charValue2[SIMPLEPROFILE_CHAR2_LEN] = {0};
    uint8 charValue3[SIMPLEPROFILE_CHAR3_LEN] = {0};
    uint8 charValue4[SIMPLEPROFILE_CHAR4_LEN] = {0};
    uint8 charValue5[SIMPLEPROFILE_CHAR5_LEN] = {0};
    uint8 charValue6[SIMPLEPROFILE_CHAR6_LEN] = {0};
 
    SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR1, SIMPLEPROFILE_CHAR1_LEN, charValue1 );
    SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR2, SIMPLEPROFILE_CHAR2_LEN, charValue2 );
    SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR3, SIMPLEPROFILE_CHAR3_LEN, charValue3 );
    SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR4, SIMPLEPROFILE_CHAR4_LEN, charValue4 );
    SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR5, SIMPLEPROFILE_CHAR5_LEN, charValue5 );
    SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR6, SIMPLEPROFILE_CHAR6_LEN, charValue6 );
  }

  
// Register callback with SimpleGATTprofile
VOID SimpleProfile_RegisterAppCBs( &simpleBLEPeripheral_SimpleProfileCBs );

// Enable clock divide on halt
// This reduces active current while radio is active and CC254x MCU
// is halted
HCI_EXT_ClkDivOnHaltCmd( HCI_EXT_ENABLE_CLK_DIVIDE_ON_HALT );

#if defined ( DC_DC_P0_7 )

  // Enable stack to toggle bypass control on TPS62730 (DC/DC converter)
  HCI_EXT_MapPmIoPortCmd( HCI_EXT_PM_IO_PORT_P0, HCI_EXT_PM_IO_PORT_PIN7 );

#endif // defined ( DC_DC_P0_7 )
  
//  P2INP |=  0x03;    // Configure Port 0 ,1,as pull-down 20K
//  P0INP &= ~0x03;    // Configure Port 0 ,1,as pull-down 20K
  P0INP |=  0xC0;    // Configure Port 6 ,7,as 3-state
  P0SEL &= ~0x3C;    // Configure Port 0 as GPIO
  P0DIR |=  0x3C;    // Port 0 pins P0.0 , P0.1 , P0.6 , P0.7 
                     // as  input (AD0, AD1 ,X1,X2) 
                     // all others (P0.4-P0.7) as output
	P1SEL |=  0xE0;    // P1_5, P1_6, and P1_7 are peripherals
	P1SEL &= ~0x10;    // P1_4 is GPIO (SSN)
	P1DIR |=  0x13;    // SPI  
                     // all others (P1.0-P1.5) as output
  P2SEL = 0X00;         // Configure Port 2 as GPIO
  P2DIR = 0x01;      // All port 1 pins (P2.0) as output

  P0 &= ~0x24;       // All pins on port 0 to low except for P0.0 and P0.1 (buttons)
  P1 &= ~0x03;       // All pins on port 1 to low
  P2 |=  0x07;       // All pins on port 2 to low 

  //init batter check
  batter_control(1);

  //init Hmc5883
  Hmc5883_Init(HMC5883_ADDR);  
  Hmc5883_WriteReg(0x00, HMC5883_CTROL_REG, 3); 

  Hmc5883InitGetVector();  //init the vector sum for power up
  
  //show battery 
  show_bat_by_leds();
  //rf470m  init
  LSD_RF_Init(frefunction1);

  //Setup a delayed profile startup
  osal_set_event( simpleBLEPeripheral_TaskID, SBP_START_DEVICE_EVT );
  
  //启动看门狗, 定是1000ms, 1000ms内需要喂狗, 否则就重启了
 // HAL_SYSTEM_WATCH_DOG_1000MS(); 
}
/*********************************************************************
 * @fn      SimpleBLEPeripheral_Init
 *
 * @brief   Initialization function for the Simple BLE Peripheral App Task.
 *          This is called during initialization and should contain
 *          any application specific initialization (ie. hardware
 *          initialization/setup, table initialization, power up
 *          notificaiton ... ).
 *
 * @param   task_id - the ID assigned by OSAL.  This ID should be
 *                    used to send messages and set timers.
 *
 * @return  none
 */
void SimpleBLEPeripheral_Init( uint8 task_id )
{
  HCI_EXT_SetTxPowerCmd(LL_EXT_TX_POWER_MINUS_6_DBM);
  simpleBLEPeripheral_TaskID = task_id;
  if(osal_snv_read(0xfe,1,&gMP)!=NV_OPER_FAILED){
	advertData[29]=gMP;
  }
  // Setup the GAP
  VOID GAP_SetParamValue( TGAP_CONN_PAUSE_PERIPHERAL, DEFAULT_CONN_PAUSE_PERIPHERAL );//连接间隙
  
  // Setup the GAP Peripheral Role Profile
  {
    #if defined( CC2540_MINIDK )
      // For the CC2540DK-MINI keyfob, device doesn't start advertising until button is pressed
      uint8 initial_advertising_enable = FALSE;
    #else
      // For other hardware platforms, device starts advertising upon initialization
      uint8 initial_advertising_enable = TRUE;
    #endif

    // By setting this to zero, the device will go into the waiting state after
    // being discoverable for 30.72 second, and will not being advertising again
    // until the enabler is set back to TRUE
    uint16 gapRole_AdvertOffTime = 0;

    uint8 enable_update_request = DEFAULT_ENABLE_UPDATE_REQUEST;
    uint16 desired_min_interval = DEFAULT_DESIRED_MIN_CONN_INTERVAL;
    uint16 desired_max_interval = DEFAULT_DESIRED_MAX_CONN_INTERVAL;
    uint16 desired_slave_latency = DEFAULT_DESIRED_SLAVE_LATENCY;
    uint16 desired_conn_timeout = DEFAULT_DESIRED_CONN_TIMEOUT;
    uint16 desired_rssi_rate=DEFAULT_DESIRED_REEI_RATE;
    // Set the GAP Role Parameters
    GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &initial_advertising_enable );
    //GAPRole_SetParameter( GAPROLE_ADVERT_OFF_TIME, sizeof( uint16 ), &gapRole_AdvertOffTime );

    GAPRole_SetParameter( GAPROLE_SCAN_RSP_DATA, sizeof ( scanRspData ), scanRspData );
    GAPRole_SetParameter( GAPROLE_ADVERT_DATA, sizeof( advertData ), advertData );
    
    GAPRole_SetParameter(GAPROLE_RSSI_READ_RATE,sizeof(uint16),&desired_rssi_rate);//设定RSSI的参数值
    
    GAPRole_SetParameter( GAPROLE_PARAM_UPDATE_ENABLE, sizeof( uint8 ), &enable_update_request );
    
    GAPRole_SetParameter( GAPROLE_MIN_CONN_INTERVAL, sizeof( uint16 ), &desired_min_interval );
    GAPRole_SetParameter( GAPROLE_MAX_CONN_INTERVAL, sizeof( uint16 ), &desired_max_interval );
    GAPRole_SetParameter( GAPROLE_SLAVE_LATENCY, sizeof( uint16 ), &desired_slave_latency );
    GAPRole_SetParameter( GAPROLE_TIMEOUT_MULTIPLIER, sizeof( uint16 ), &desired_conn_timeout );
  }

  // Set the GAP Characteristics
  GGS_SetParameter( GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, attDeviceName );

  // Set advertising interval
  {
    uint16 advInt = DEFAULT_ADVERTISING_INTERVAL;

    GAP_SetParamValue( TGAP_LIM_DISC_ADV_INT_MIN, advInt );
    GAP_SetParamValue( TGAP_LIM_DISC_ADV_INT_MAX, advInt );
    GAP_SetParamValue( TGAP_GEN_DISC_ADV_INT_MIN, advInt );
    GAP_SetParamValue( TGAP_GEN_DISC_ADV_INT_MAX, advInt );
  }

  // Setup the GAP Bond Manager
  {
    uint32 passkey = 0; // passkey "000000"
    uint8 pairMode = GAPBOND_PAIRING_MODE_WAIT_FOR_REQ;
    uint8 mitm = TRUE;
    uint8 ioCap = GAPBOND_IO_CAP_DISPLAY_ONLY;
    uint8 bonding = TRUE;
    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 );
  }

  // Initialize GATT attributes
  GGS_AddService( GATT_ALL_SERVICES );            // GAP
  GATTServApp_AddService( GATT_ALL_SERVICES );    // GATT attributes
  DevInfo_AddService();                           // Device Information Service
  SimpleProfile_AddService( GATT_ALL_SERVICES );  // Simple GATT Profile
#if defined FEATURE_OAD
  VOID OADTarget_AddService();                    // OAD Profile
#endif

  // Setup the SimpleProfile Characteristic Values
  {
    uint8 charValue1 = 1;
    uint8 charValue2 = 0;
    uint8 charValue3 = 3;
    uint8 charValue4 = 4;
    uint8 charValue5[SIMPLEPROFILE_CHAR5_LEN] = { 1, 2, 3, 4, 5 };
    SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR1, sizeof ( uint8 ), &gMP );
    SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR2, sizeof ( uint8 ), &charValue2 );
    SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR3, sizeof ( uint8 ), &charValue3 );
    SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR4, sizeof ( uint8 ), &charValue4 );
    SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR5, SIMPLEPROFILE_CHAR5_LEN, charValue5 );
  }


#if defined( CC2540_MINIDK )

  SK_AddService( GATT_ALL_SERVICES ); // Simple Keys Profile

  // Register for all key events - This app will handle all key events
  RegisterForKeys( simpleBLEPeripheral_TaskID );

  // makes sure LEDs are off
  HalLedSet( (HAL_LED_1 | HAL_LED_2), HAL_LED_MODE_OFF );

  // For keyfob board set GPIO pins into a power-optimized state
  // Note that there is still some leakage current from the buzzer,
  // accelerometer, LEDs, and buttons on the PCB.

  P0SEL = 0; // Configure Port 0 as GPIO
  P1SEL = 0; // Configure Port 1 as GPIO
  P2SEL = 0; // Configure Port 2 as GPIO

  P0DIR = 0xFC; // Port 0 pins P0.0 and P0.1 as input (buttons),
                // all others (P0.2-P0.7) as output
  P1DIR = 0xFF; // All port 1 pins (P1.0-P1.7) as output
  P2DIR = 0x1F; // All port 1 pins (P2.0-P2.4) as output

  P0 = 0x03; // All pins on port 0 to low except for P0.0 and P0.1 (buttons)
  P1 = 0;   // All pins on port 1 to low
  P2 = 0;   // All pins on port 2 to low

#endif // #if defined( CC2540_MINIDK )

#if (defined HAL_LCD) && (HAL_LCD == TRUE)

#if defined FEATURE_OAD
  #if defined (HAL_IMAGE_A)
    HalLcdWriteStringValue( "BLE Peri-A", OAD_VER_NUM( _imgHdr.ver ), 16, HAL_LCD_LINE_1 );
  #else
    HalLcdWriteStringValue( "BLE Peri-B", OAD_VER_NUM( _imgHdr.ver ), 16, HAL_LCD_LINE_1 );
  #endif // HAL_IMAGE_A
#else
  HalLcdWriteString( "iBeacon", HAL_LCD_LINE_1 );
#endif // FEATURE_OAD

#endif // (defined HAL_LCD) && (HAL_LCD == TRUE)

  // Register callback with SimpleGATTprofile
  VOID SimpleProfile_RegisterAppCBs( &simpleBLEPeripheral_SimpleProfileCBs );

  // Enable clock divide on halt
  // This reduces active current while radio is active and CC254x MCU
  // is halted
  HCI_EXT_ClkDivOnHaltCmd( HCI_EXT_ENABLE_CLK_DIVIDE_ON_HALT );

#if defined ( DC_DC_P0_7 )

  // Enable stack to toggle bypass control on TPS62730 (DC/DC converter)
  HCI_EXT_MapPmIoPortCmd( HCI_EXT_PM_IO_PORT_P0, HCI_EXT_PM_IO_PORT_PIN7 );

#endif // defined ( DC_DC_P0_7 )

  // Setup a delayed profile startup
  osal_set_event( simpleBLEPeripheral_TaskID, SBP_START_DEVICE_EVT );

}
/*********************************************************************
 * @fn      DualImageConcept_init
 *
 * @brief   Called during initialization and contains application
 *          specific initialization (ie. hardware initialization/setup,
 *          table initialization, power up notification, etc), and
 *          profile initialization/setup.
 *
 * @param   None.
 *
 * @return  None.
 */
static void DualImageConcept_init(void)
{
  // For CC1350LP Set DIO1 High for 2.4 GHz Radio usage.
  // Set DIO30 High to power radio.
  
  
  
  // ******************************************************************
  // N0 STACK API CALLS CAN OCCUR BEFORE THIS CALL TO ICall_registerApp
  // ******************************************************************
  // Register the current thread as an ICall dispatcher application
  // so that the application can send and receive messages.
  ICall_registerApp(&selfEntity, &sem);
    
  // Hard code the BD Address till CC2650 board gets its own IEEE address
  uint8 bdAddress[B_ADDR_LEN] = { 0x1C, 0xCD, 0xD1, 0x1C, 0xCD, 0xD1 };
  HCI_EXT_SetBDADDRCmd(bdAddress);
  
  // Set device's Sleep Clock Accuracy
  //HCI_EXT_SetSCACmd(40);
  
  // Create an RTOS queue for message from profile to be sent to app.
  appMsgQueue = Util_constructQueue(&appMsg);
  
  Board_initKeys(DualImageConcept_keyChangeHandler);
  
  dispHandle = Display_open(Display_Type_LCD, NULL);
  
  // Setup the GAP
  GAP_SetParamValue(TGAP_CONN_PAUSE_PERIPHERAL, DEFAULT_CONN_PAUSE_PERIPHERAL);

  // Setup the GAP Peripheral Role Profile
  {
    // For all hardware platforms, device starts advertising upon initialization
    uint8_t initialAdvertEnable = TRUE;

    // By setting this to zero, the device will go into the waiting state after
    // being discoverable for 30.72 second, and will not being advertising again
    // until the enabler is set back to TRUE
    uint16_t advertOffTime = 0;

    uint8_t enableUpdateRequest = DEFAULT_ENABLE_UPDATE_REQUEST;
    uint16_t desiredMinInterval = DEFAULT_DESIRED_MIN_CONN_INTERVAL;
    uint16_t desiredMaxInterval = DEFAULT_DESIRED_MAX_CONN_INTERVAL;
    uint16_t desiredSlaveLatency = DEFAULT_DESIRED_SLAVE_LATENCY;
    uint16_t desiredConnTimeout = DEFAULT_DESIRED_CONN_TIMEOUT;

    // Set the GAP Role Parameters
    GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8_t), 
                         &initialAdvertEnable);
    GAPRole_SetParameter(GAPROLE_ADVERT_OFF_TIME, sizeof(uint16_t), 
                         &advertOffTime);

    GAPRole_SetParameter(GAPROLE_SCAN_RSP_DATA, sizeof(scanRspData), 
                         scanRspData);
    GAPRole_SetParameter(GAPROLE_ADVERT_DATA, sizeof(advertData), advertData);

    GAPRole_SetParameter(GAPROLE_PARAM_UPDATE_ENABLE, sizeof(uint8_t), 
                         &enableUpdateRequest);
    GAPRole_SetParameter(GAPROLE_MIN_CONN_INTERVAL, sizeof(uint16_t), 
                         &desiredMinInterval);
    GAPRole_SetParameter(GAPROLE_MAX_CONN_INTERVAL, sizeof(uint16_t), 
                         &desiredMaxInterval);
    GAPRole_SetParameter(GAPROLE_SLAVE_LATENCY, sizeof(uint16_t), 
                         &desiredSlaveLatency);
    GAPRole_SetParameter(GAPROLE_TIMEOUT_MULTIPLIER, sizeof(uint16_t), 
                         &desiredConnTimeout);
  }

  // Set the GAP Characteristics
  GGS_SetParameter(GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, attDeviceName);

  // Set advertising interval
  {
    uint16_t advInt = DEFAULT_ADVERTISING_INTERVAL;

    GAP_SetParamValue(TGAP_LIM_DISC_ADV_INT_MIN, advInt);
    GAP_SetParamValue(TGAP_LIM_DISC_ADV_INT_MAX, advInt);
    GAP_SetParamValue(TGAP_GEN_DISC_ADV_INT_MIN, advInt);
    GAP_SetParamValue(TGAP_GEN_DISC_ADV_INT_MAX, advInt);
  }

   // Initialize GATT attributes
  GGS_AddService(GATT_ALL_SERVICES);           // GAP
  GATTServApp_AddService(GATT_ALL_SERVICES);   // GATT attributes

  // Start the Device
  VOID GAPRole_StartDevice(&DualImageConcept_gapRoleCBs);
  
  Display_print0(dispHandle, 0, 0, "CC1350 BLE Image A");
  
  // Check for shared data
  osal_snv_read(0x80, sizeof(uint8_t), &sharedData);
  
  // Write the shared data to the LCD.
  Display_print1(dispHandle, 6, 0, "Shared Data: %d", sharedData);
}