コード例 #1
0
/*********************************************************************
 * @fn      SensorTagKeys_clockHandler
 *
 * @brief   Handler function for clock time-outs.
 *
 * @param   arg - event type
 *
 * @return  none
 */
static void SensorTagKeys_clockHandler(UArg arg)
{
    // Are both keys pressed?
    if (keys & SK_KEY_RIGHT)
    {
        keyTimer++;
    }
    else
    {
        keyTimer = 0;
    }



    // Both keys have been pressed for 6 seconds -> restore factory image
    if (keyTimer >= RESET_PRESS_PERIOD )
    {
        // Stop the clock
        if (Util_isActive(&periodicClock))
        {
            Util_stopClock(&periodicClock);
            keyTimer = 0;

            // set event flag and wake up the application thread
            event |= SK_EVT_FACTORY_RESET;
            Semaphore_post(sem);
        }
    }
//    // Right key (POWER) pressed for three seconds, disconnect if connected
//    else if (keyRightTimer >= POWER_PRESS_PERIOD && keyLeftTimer == 0)
//    {
//        // Stop the clock
//        if (Util_isActive(&periodicClock))
//        {
//            Util_stopClock(&periodicClock);
//            keyRightTimer = 0;
//
//            // set event flag and wake up the application thread
//            event |= SK_EVT_DISCONNECT;
//            Semaphore_post(sem);
//        }
//    }
    else if (keyTimer == 0)
    {
        // Stop the clock
        if (Util_isActive(&periodicClock))
        {
            Util_stopClock(&periodicClock);
        }
    }
}
コード例 #2
0
/*******************************************************************************
 * @fn      userAppInit
 *
 * @brief   user Application init
 *
 * @param   void
 *
 * @return  none
 */
void userAppInit(void)
{
	OLED_Init();
// 电池状态读初始化I2C	
    SMB_Init(); 
// 串口初始化	
	bspUartInit();  
	
// 按键初始化要等系统稳定后,防止外部中断引起系统死机
	KEY_Init();

//电池状态检测初始化
	chargeDetection_Init();

	//OLED_ShowString(40,32, "WiCore"); 
	OLED_Clear();
	
	// Create one-shot clocks for internal periodic events.
	Util_constructClock(&periodicClock_10ms, userApp_clockHandler,
	                  10, 0, false, USER_10MS_EVT);
#ifndef INCLUDE_CLKSTOP	
	systemState.powerOffFlag = 1;
	Util_startClock(&periodicClock_10ms);
#else
	Util_stopClock(&periodicClock_10ms);

#endif	
}
コード例 #3
0
static void rightKeyEvent_Handler(void) {

	if (PIN_getInputValue(Board_KEY_RIGHT) == 0) {
		longPressedButtonCheck |= KEY_RIGHT_EVT;
		longPressNotiSent = 0;

		if(Util_isActive(&longPressCheckClock)){
			Util_startClock(&longPressCheckClock);
		}else{
			Util_startClock(&longPressCheckClock);
		}
	} else {
		longPressedButtonCheck &= ~KEY_RIGHT_EVT;
		if(longPressedButtonCheck == 0){
			Util_stopClock(&longPressCheckClock);
		}

		if (Keys_AppCGs && longPressNotiSent == 0) {
			Keys_AppCGs->pfnKeysNotification(RIGHT_SHORT);
		}
	}



}
コード例 #4
0
/*********************************************************************
 * @fn      CyclingSensor_handleResetEvt
 *
 * @brief   "soft" resets the device.  This puts the device into a waiting 
 *           state, clears all white list, bonding and GATT service handle 
 *           information about previously previously connected devices.
 *
 * @param   none
 *
 * @return  none
 */
static void CyclingSensor_handleResetEvt(void)
{
  static uint8_t isWLClear = FALSE;
  
  if (gapProfileState == GAPROLE_CONNECTED)
  { 
    // Exit the connection.
    GAPRole_TerminateConnection();
  }
  else if (gapProfileState == GAPROLE_ADVERTISING)
  {
    uint8_t value = FALSE;

    // Turn off advertising.
    GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8_t), &value);
  }
  else if (USING_WHITE_LIST == TRUE && isWLClear == FALSE)
  {
    // Set internal white list flag to true.
    isWLClear = TRUE;
    
    // Disable white list use with advertising.
    sensorUsingWhiteList = FALSE;
    
    // Temporary variable.
    uint8_t value = GAP_FILTER_POLICY_ALL;

    // Turn off white list filter policy.
    GAPRole_SetParameter(GAPROLE_ADV_FILTER_POLICY, sizeof(uint8_t), &value);

    // Clear the white list.
    HCI_LE_ClearWhiteListCmd();
  }
  else if ((gapProfileState == GAPROLE_STARTED) ||
            (gapProfileState == GAPROLE_WAITING) ||
            (gapProfileState == GAPROLE_WAITING_AFTER_TIMEOUT))
  {
    uint8_t eraseBonds = TRUE;

    // Stop the periodic expirations of the reset clock.
    Util_stopClock(&resetClock);
    
    // Set internal white list flag to false for next reset event.
    isWLClear = FALSE;
    
    // Erase all bonds.
    GAPBondMgr_SetParameter(GAPBOND_ERASE_ALLBONDS, 0, &eraseBonds);
    
    // Turn on GREEN LED for set time.
    //HalLedSet(HAL_LED_1, HAL_LED_MODE_BLINK);
  }  
}
コード例 #5
0
/*******************************************************************************
 * @fn      appStateSet
 *
 * @brief   Set the application state
 *
 */
static void appStateSet(uint8_t newState)
{
  if (newState == APP_STATE_OFF)
  {
    appState = APP_STATE_OFF;

    SensorMpu9250_enable(0);
    SensorMpu9250_powerOff();

    // Stop scheduled data measurements
    Util_stopClock(&periodicClock);
  }

  if (newState == APP_STATE_ACTIVE || newState == APP_STATE_IDLE)
  {
    appState = APP_STATE_ACTIVE;
    nActivity = MOVEMENT_INACT_CYCLES;
    movThreshold = WOM_THR;
    mpuIntStatus = 0;
    shakeDetected = false;
    mpuDataRdy = false;

    SensorMpu9250_powerOn();
    SensorMpu9250_enable(mpuConfig & 0xFF);

    if (newState == APP_STATE_ACTIVE)
    {
      // Start scheduled data measurements
      Util_startClock(&periodicClock);
    }
    else
    {
      // Stop scheduled data measurements
      Util_stopClock(&periodicClock);
    }
  }
}
コード例 #6
0
ファイル: heartRate.c プロジェクト: victor-zheng/BLE
/*********************************************************************
 * @fn      HeartRate_battEvt
 *
 * @brief   Event handler for battery service callbacks.
 *
 * @param   event - service event
 *
 * @return  none
 */
static void HeartRate_battEvt(uint8_t event)
{
  if (event == BATT_LEVEL_NOTI_ENABLED)
  {
    // If connected start periodic measurement.
    if (gapProfileState == GAPROLE_CONNECTED)
    {
      Util_startClock(&battPerClock);
    }
  }
  else if (event == BATT_LEVEL_NOTI_DISABLED)
  {
    // Stop periodic measurement.
    Util_stopClock(&battPerClock);
  }
}
コード例 #7
0
ファイル: multi.c プロジェクト: 247765843/ble_examples
/*********************************************************************
 * @fn      gapRole_processStackMsg
 *
 * @brief   Process an incoming task message.
 *
 * @param   pMsg - message to process
 *
 * @return  none
 */
static uint8_t gapRole_processStackMsg(ICall_Hdr *pMsg)
{
  uint8_t safeToDealloc = TRUE;
  
  switch (pMsg->event)
  {
    case GAP_MSG_EVENT:
      safeToDealloc = gapRole_processGAPMsg((gapEventHdr_t *)pMsg);
      break;

    case L2CAP_SIGNAL_EVENT:
      {
        l2capSignalEvent_t *pPkt = (l2capSignalEvent_t *)pMsg;

        // Process the Parameter Update Response
        if (pPkt->opcode == L2CAP_PARAM_UPDATE_RSP)
        {
          l2capParamUpdateRsp_t *pRsp = (l2capParamUpdateRsp_t *)&(pPkt->cmd.updateRsp);

          if ((pRsp->result == L2CAP_CONN_PARAMS_REJECTED) &&
               (paramUpdateNoSuccessOption == GAPROLE_TERMINATE_LINK))
          {
            // Cancel connection param update timeout timer
            Util_stopClock(&updateTimeoutClock);

            // Terminate connection immediately
            GAPRole_TerminateConnection(pPkt->connHandle);
          }
          else
          {
            uint16_t timeout = GAP_GetParamValue(TGAP_CONN_PARAM_TIMEOUT);

            // Let's wait for Controller to update connection parameters if they're
            // accepted. Otherwise, decide what to do based on no success option.
            Util_restartClock(&updateTimeoutClock, timeout);
          }
        }
      }
      break;      
      
    default:
      break;
  }
  
  return (safeToDealloc);
}
コード例 #8
0
ファイル: glucose_ctlpnt.c プロジェクト: victor-zheng/BLE
/*********************************************************************
 * @fn      glucoseCtlPntGattMsg()
 *
 * @brief   Handle GATT messages for control point operations.
 *
 * @param   pMsg - GATT message.
 *
 * @return  None.
 */
void glucoseCtlPntGattMsg(gattMsgEvent_t *pMsg)
{ 
  if (pMsg->method == ATT_ERROR_RSP)
  {
     attErrorRsp_t *pRsp = &pMsg->msg.errorRsp;
     
     glucCollClearPending = false;
     LCD_WRITE_STRING("Write Error",  LCD_PAGE0);
     LCD_WRITE_STRING_VALUE("Handle:  ", pRsp->handle, 10, LCD_PAGE1);
     LCD_WRITE_STRING_VALUE("errCode: ", pRsp->errCode, 10, LCD_PAGE2);
  }
  else if (pMsg->method == ATT_WRITE_RSP)
  {
    // start procedure timer
    Util_stopClock(&procTimeoutClock);
    Util_startClock(&procTimeoutClock);
  }
  
  glucCollWritePending = false;
}
コード例 #9
0
ファイル: heartRate.c プロジェクト: victor-zheng/BLE
/*********************************************************************
 * @fn      HeartRate_heartRateEvt
 *
 * @brief   event handler for heart rate service callbacks.
 *
 * @param   event - service event
 *
 * @return  none
 */
static void HeartRate_heartRateEvt(uint8_t event)
{
  if (event == HEARTRATE_MEAS_NOTI_ENABLED)
  {
    // If connected start periodic measurement.
    if (gapProfileState == GAPROLE_CONNECTED)
    {
      Util_startClock(&measPerClock);
    }
  }
  else if (event == HEARTRATE_MEAS_NOTI_DISABLED)
  {
    // Stop periodic measurement.
    Util_stopClock(&measPerClock);
  }
  else if (event == HEARTRATE_COMMAND_SET)
  {
    // Reset energy expended.
    heartRateEnergyLvl = 0;
  }
}
コード例 #10
0
/********************************************************************
 * @fn          GAPRole_SendUpdateParam
 *
 * @brief       Update the parameters of an existing connection
 *
 * @param       minConnInterval - the new min connection interval
 * @param       maxConnInterval - the new max connection interval
 * @param       latency - the new slave latency
 * @param       connTimeout - the new timeout value
 * @param       handleFailure - what to do if the update does not occur.
 *              Method may choose to terminate connection, try again,
 *              or take no action
 *
 * @return      SUCCESS, bleNotConnected, or bleInvalidRange
 */
bStatus_t GAPRole_SendUpdateParam(uint16_t minConnInterval, uint16_t maxConnInterval, uint16_t latency, uint16_t connTimeout, uint8_t handleFailure, uint16_t connHandle) {

	uint8 connHandleIndex = gapRoleInfo_Find(connHandle);

	// If there is no existing connection no update need be sent
	if (multiConnInfo[connHandleIndex].gapRole_ConnectionHandle == GAPROLE_CONN_JUST_TERMINATED || multiConnInfo[connHandleIndex].gapRole_ConnectionHandle == INVALID_CONNHANDLE) {
		return (bleNotConnected);
	}

	if (multiConnInfo[connHandleIndex].gapRole_ConnRole != GAP_PROFILE_PERIPHERAL) {
		return (bleNotConnected);
	}

	  // If there is no existing connection no update need be sent
	if (gapRole_peripheralState != GAPROLE_CONNECTED) {
		return (bleNotConnected);
	}

	// Check that all parameters are in range before sending request
	if ((minConnInterval >= DEFAULT_MIN_CONN_INTERVAL) && (minConnInterval < DEFAULT_MAX_CONN_INTERVAL) && (maxConnInterval >= DEFAULT_MIN_CONN_INTERVAL)
			&& (maxConnInterval < DEFAULT_MAX_CONN_INTERVAL) && (latency < MAX_SLAVE_LATENCY) && (connTimeout >= MIN_TIMEOUT_MULTIPLIER)
			&& (connTimeout < MAX_TIMEOUT_MULTIPLIER)) {
		gapRole_MinConnInterval = minConnInterval;
		gapRole_MaxConnInterval = maxConnInterval;
		gapRole_SlaveLatency = latency;
		gapRole_TimeoutMultiplier = connTimeout;

		// Start connection update procedure
		VOID gapRole_startConnUpdate(handleFailure, multiConnInfo[connHandleIndex].gapRole_ConnectionHandle);

		// Connection update requested by app, cancel such pending procedure (if active)
		Util_stopClock(&startUpdateClock);

		return (SUCCESS);
	}

	return (bleInvalidRange);
}
コード例 #11
0
/*********************************************************************
 * @fn      CyclingSensor_processServiceEvt
 *
 * @brief   Handler function for CSC service callback.
 *
 * @param   event       - service event
 * @param   newCummVal  - new wheel revolution data if specified by event.
 *
 * @return  none
 */
static void CyclingSensor_processServiceEvt(uint8_t event, uint32_t newCummVal)
{
  switch (event)
  {
    case CSC_CMD_SET_CUMM_VAL:
#if USING_NEGLECT_TIMEOUT
      // If notifications aren't enabled
      if (!Util_isActive(&periodicClock))
      {
        // Restart neglect timer.
        Util_startClock(&neglectClock);
      }
#endif //USING_NEGLECT_TIMEOUT
      
      cummWheelRevs = newCummVal;
      break;

    case CSC_CMD_UPDATE_SENS_LOC:
#if USING_NEGLECT_TIMEOUT
      // If notifications aren't enabled
      if (!Util_isActive(&periodicClock))
      {
        // Restart neglect timer.
        Util_startClock(&neglectClock);
      }
#endif //USING_NEGLECT_TIMEOUT
      
      // Get updated sensor location.
      CyclingService_getParameter(CSC_SENS_LOC, &sensorLocation);
      break;

    case CSC_MEAS_NOTI_ENABLED:     
#if (USING_NEGLECT_TIMEOUT)
      // Stop neglect timer.
      Util_stopClock(&neglectClock);
#endif //USING_NEGLECT_TIMEOUT
      
      // If connected start periodic measurement.
      if (gapProfileState == GAPROLE_CONNECTED)
      {
        Util_startClock(&periodicClock);
      }
      break;

    case CSC_MEAS_NOTI_DISABLED:
      // Stop periodic measurement.
      Util_stopClock(&periodicClock);
      
#if USING_NEGLECT_TIMEOUT
      // Start neglect timer.
      Util_startClock(&neglectClock);
#endif //USING_NEGLECT_TIMEOUT
      break;

    case CSC_READ_ATTR:
    case CSC_WRITE_ATTR:
#if USING_NEGLECT_TIMEOUT
      // If notifications aren't enabled
      if (!Util_isActive(&periodicClock))
      {
        // Restart neglect timer.
        Util_startClock(&neglectClock);
      }
#endif //USING_NEGLECT_TIMEOUT
      break;

    default:
      // Do nothing.
      break;
  }
}
コード例 #12
0
ファイル: thermometer.c プロジェクト: victor-zheng/BLE
/*********************************************************************
 * @fn      Thermometer_processStateChangeEvt
 *
 * @brief   Notification from the profile of a state change.
 *
 * @param   newState - new state
 *
 * @return  none
 */
static void Thermometer_processStateChangeEvt(gaprole_States_t newState)
{
  // If connected
  if (newState == GAPROLE_CONNECTED)
  {
    // Get connection handle.
    GAPRole_GetParameter(GAPROLE_CONNHANDLE, &thermometer_connHandle);

    // Get peer bd address.
    GAPRole_GetParameter(GAPROLE_CONN_BD_ADDR, &connDeviceAddr);
    
    // Set the Time module's copy of the connHandle.
    Time_connHandle = thermometer_connHandle;
    
    // If connected to device without bond do service discovery.
    if (memcmp(connDeviceAddr, timeAppBondedAddr, B_ADDR_LEN))
    {
      servDiscComplete = FALSE;
    }
    else
    {
      servDiscComplete = TRUE;
    }
    
    // If this was last connection address don't do discovery.
    if(!memcmp(connDeviceAddr, lastConnAddr, B_ADDR_LEN))
    {
      servDiscComplete = TRUE;
      connectedToLastAddress = true;
    }
    else
    {
      // Save the last connected address.
      memcpy(lastConnAddr, connDeviceAddr, B_ADDR_LEN);
    }

    // Initiate service discovery if necessary.
    if (servDiscComplete == FALSE)
    {
      // Start timer for service discovery.
      Util_startClock(&startDiscoveryClock);
    }
    
    // Start timer for disconnect.
    Util_startClock(&disconnectClock);
  }
  // If disconnected
  else if (gapProfileState == GAPROLE_CONNECTED && 
            newState != GAPROLE_CONNECTED)
  { 
    // Stop discovery clock in case it is running.
    Util_stopClock(&startDiscoveryClock);

    // Stop intermediate timers.
    Util_stopClock(&perIMeasClock);
    Util_stopClock(&perMeasClock);
  
    // Re-initialize state variables.
    servDiscState = DISC_IDLE;
    servDiscPostponed = FALSE;
    
    // Invalidate the connection handle.
    thermometer_connHandle = Time_connHandle = INVALID_CONNHANDLE;
  }
  // If started
  else if (newState == GAPROLE_STARTED)
  {
    // Time module configuration have not been set.
    Time_configDone = FALSE;
    
    // Initialize time clock.
    Time_clockInit();
  }
  
  // Update to new state.
  gapProfileState = newState;
}
コード例 #13
0
/*********************************************************************
 * @fn      RunningSensor_processServiceEvt
 *
 * @brief   Handler RSC service callback.
 *
 * @param   event       - service event
 * @param   newCummVal  - new total distance data if specified by event.  
 *                        0 otherwise.
 *
 * @return  SUCCESS if operation successful. FAILURE, otherwise.
 */
static bStatus_t RunningSensor_processServiceEvt(uint8_t event,
                                                 uint32_t newCummVal)
{
  bStatus_t status = SUCCESS;

  switch (event)
  {
    case RSC_CMD_SET_CUMM_VAL:
#if USING_NEGLECT_TIMEOUT
      // If notifications aren't enabled
      if (!Util_isActive(&periodicClock))
      {
        // Restart neglect timer.
        Util_startClock(&neglectClock);
      }
#endif //USING_NEGLECT_TIMEOUT

      // Update total distance.
      totalDistance = newCummVal;
      break;
      
    case RSC_CMD_START_SENS_CALIB:
      // Do nothing for now
      break;
      
    case RSC_CMD_UPDATE_SENS_LOC:
#if USING_NEGLECT_TIMEOUT
      // If notifications aren't enabled
      if (!Util_isActive(&periodicClock))
      {
        // Restart neglect timer.
        Util_startClock(&neglectClock);
      }
#endif //USING_NEGLECT_TIMEOUT

      // Get updated sensor location.
      RunningService_getParameter(RSC_SENS_LOC, &sensorLocation);
      break;

    case RSC_MEAS_NOTI_ENABLED:
#if (USING_NEGLECT_TIMEOUT)
      // Stop neglect timer.
      Util_stopClock(&neglectClock);
#endif //USING_NEGLECT_TIMEOUT

      // If connected start periodic measurement for notifications.
      if (gapProfileState == GAPROLE_CONNECTED)
      {
        Util_startClock(&periodicClock);
      }
      break;

    case RSC_MEAS_NOTI_DISABLED:
      // Stop periodic measurement.
      Util_stopClock(&periodicClock);

#if USING_NEGLECT_TIMEOUT
      // Start neglect timer.
      Util_startClock(&neglectClock);
#endif //USING_NEGLECT_TIMEOUT
      break;

    case RSC_READ_ATTR:
    case RSC_WRITE_ATTR:
#if USING_NEGLECT_TIMEOUT
      // If notifications aren't enabled
      if (!Util_isActive(&periodicClock))
      {
        // Restart neglect timer.
        Util_startClock(&neglectClock);
      }
#endif //USING_NEGLECT_TIMEOUT
      break;

    default:
      // Do nothing.
      break;
  }

  return (status);
}
コード例 #14
0
ファイル: heartRate.c プロジェクト: victor-zheng/BLE
/*********************************************************************
 * @fn      HeartRate_stateChangeEvt
 *
 * @brief   Notification from the profile of a state change.
 *
 * @param   newState - new state
 *
 * @return  none
 */
static void HeartRate_stateChangeEvt(gaprole_States_t newState)
{
  // If no change to the GAP Role state has occurred
  if (gapProfileState == newState)
  {
    return; 
  }
  
  // If connected
  if (newState == GAPROLE_CONNECTED)
  {
    // Get connection handle.
    GAPRole_GetParameter(GAPROLE_CONNHANDLE, &gapConnHandle);
  }
  // If disconnected
  else if (gapProfileState == GAPROLE_CONNECTED && 
           newState != GAPROLE_CONNECTED)
  {
    // Stop periodic measurement of heart rate.
    Util_stopClock(&measPerClock);

    if (newState == GAPROLE_WAITING_AFTER_TIMEOUT)
    {
      // Link loss timeout-- use fast advertising
      GAP_SetParamValue(TGAP_GEN_DISC_ADV_INT_MIN, DEFAULT_FAST_ADV_INTERVAL);
      GAP_SetParamValue(TGAP_GEN_DISC_ADV_INT_MAX, DEFAULT_FAST_ADV_INTERVAL);
      GAP_SetParamValue(TGAP_GEN_DISC_ADV_MIN, DEFAULT_FAST_ADV_DURATION);
    }
    else
    {
      // Else use slow advertising
      GAP_SetParamValue(TGAP_GEN_DISC_ADV_INT_MIN, DEFAULT_SLOW_ADV_INTERVAL);
      GAP_SetParamValue(TGAP_GEN_DISC_ADV_INT_MAX, DEFAULT_SLOW_ADV_INTERVAL);
      GAP_SetParamValue(TGAP_GEN_DISC_ADV_MIN, DEFAULT_SLOW_ADV_DURATION);
    }

    // Enable advertising.
    HeartRate_toggleAdvertising();
  }
  // If advertising stopped
  else if (gapProfileState == GAPROLE_ADVERTISING && 
            newState == GAPROLE_WAITING)
  {
    // If advertising stopped by user
    if (advCancelled)
    {
      // Disable advertising.
      advCancelled = FALSE;
    }
    // Else if fast advertising switch to slow
    else if (GAP_GetParamValue(TGAP_GEN_DISC_ADV_INT_MIN) == DEFAULT_FAST_ADV_INTERVAL)
    { 
      GAP_SetParamValue(TGAP_GEN_DISC_ADV_INT_MIN, DEFAULT_SLOW_ADV_INTERVAL);
      GAP_SetParamValue(TGAP_GEN_DISC_ADV_INT_MAX, DEFAULT_SLOW_ADV_INTERVAL);
      GAP_SetParamValue(TGAP_GEN_DISC_ADV_MIN, DEFAULT_SLOW_ADV_DURATION);
      
      // Enable advertising.
      HeartRate_toggleAdvertising();
    }
#if ADVERTISE_WHEN_NOT_CONNECTED
    else
    {
      // Test mode: continue advertising.
      HeartRate_toggleAdvertising();
    }
#endif //ADVERTISE_WHEN_NOT_CONNECTED
  }
#if ADVERTISE_WHEN_NOT_CONNECTED  
  else if (newState == GAPROLE_WAITING_AFTER_TIMEOUT)
  {
    // Test mode: continue advertising.
    HeartRate_toggleAdvertising();      
  }
#endif //ADVERTISE_WHEN_NOT_CONNECTED
  // If started
  else if (newState == GAPROLE_STARTED)
  {
    // Set the system ID from the bd addr.
    uint8_t systemId[DEVINFO_SYSTEM_ID_LEN];
    GAPRole_GetParameter(GAPROLE_BD_ADDR, systemId);
    
    // Shift three bytes up.
    systemId[7] = systemId[5];
    systemId[6] = systemId[4];
    systemId[5] = systemId[3];
    
    // Set middle bytes to zero.
    systemId[4] = 0;
    systemId[3] = 0;
    
    // Pass systemId to the Device Info service.
    DevInfo_SetParameter(DEVINFO_SYSTEM_ID, DEVINFO_SYSTEM_ID_LEN, systemId);
  }
  
  // Update GAP profile state.
  gapProfileState = newState;
}
コード例 #15
0
ファイル: trainingTag.c プロジェクト: andrewfaf/SensorTagTest
/*********************************************************************
 * @fn      trainingTag_processStateChangeEvt
 *
 * @brief   Process a pending GAP Role state change event.
 *
 * @param   newState - new state
 *
 * @return  None.
 */
static void trainingTag_processStateChangeEvt(gaprole_States_t newState)
{
  switch ( newState )
  {
    case GAPROLE_STARTED:
      {
        uint8_t ownAddress[B_ADDR_LEN];
        uint8_t systemId[DEVINFO_SYSTEM_ID_LEN];

        GAPRole_GetParameter(GAPROLE_BD_ADDR, ownAddress);

        // use 6 bytes of device address for 8 bytes of system ID value
        systemId[0] = ownAddress[0];
        systemId[1] = ownAddress[1];
        systemId[2] = ownAddress[2];

        // set middle bytes to zero
        systemId[4] = 0x00;
        systemId[3] = 0x00;

        // shift three bytes up
        systemId[7] = ownAddress[5];
        systemId[6] = ownAddress[4];
        systemId[5] = ownAddress[3];

        DevInfo_SetParameter(DEVINFO_SYSTEM_ID, DEVINFO_SYSTEM_ID_LEN, systemId);

        // Display device address
        System_printf("Device address: %s\r\n", Util_convertBdAddr2Str(ownAddress));
        System_printf("Initialized\r\n");
      }
      break;

    case GAPROLE_ADVERTISING:
      System_printf("Advertising\r\n");
      break;

    case GAPROLE_CONNECTED:
      {
        uint8_t peerAddress[B_ADDR_LEN];

        GAPRole_GetParameter(GAPROLE_CONN_BD_ADDR, peerAddress);

        Util_startClock(&periodicClock);

        System_printf("Connected\r\n");
        System_printf("Device address: %s\r\n", Util_convertBdAddr2Str(peerAddress));

        #ifdef PLUS_BROADCASTER
          // Only turn advertising on for this state when we first connect
          // otherwise, when we go from connected_advertising back to this state
          // we will be turning advertising back on.
          if (firstConnFlag == false)
          {
            uint8_t advertEnabled = TRUE; // Turn on Advertising

            GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8_t),
                                 &advertEnabled);
            firstConnFlag = true;
          }
        #endif // PLUS_BROADCASTER
      }
      break;

    case GAPROLE_CONNECTED_ADV:
      System_printf("Connected Advertising\r\n");
      break;

    case GAPROLE_WAITING:
      Util_stopClock(&periodicClock);

      System_printf("Disconnected\r\n");
      break;

    case GAPROLE_WAITING_AFTER_TIMEOUT:
      System_printf("Timed Out\r\n");

      #ifdef PLUS_BROADCASTER
        // Reset flag for next connection.
        firstConnFlag = false;
      #endif //#ifdef (PLUS_BROADCASTER)
      break;

    case GAPROLE_ERROR:
      System_printf("Error\r\n");
      break;

    default:
      System_printf("\r\n");
      break;
  }

  // Update the state
  //gapProfileState = newState;
}
コード例 #16
0
ファイル: peripheral.c プロジェクト: ClarePhang/BLE_cc2650
/*********************************************************************
 * @fn      gapRole_processGAPMsg
 *
 * @brief   Process an incoming task message.
 *
 * @param   pMsg - message to process
 *
 * @return  none
 */
static void gapRole_processGAPMsg(gapEventHdr_t *pMsg)
{
    uint8_t notify = FALSE;   // State changed notify the app? (default no)

    switch (pMsg->opcode)
    {
    case GAP_DEVICE_INIT_DONE_EVENT:
    {
        gapDeviceInitDoneEvent_t *pPkt = (gapDeviceInitDoneEvent_t *)pMsg;
        bStatus_t stat = pPkt->hdr.status;

        if (stat == SUCCESS)
        {
            // Save off the generated keys
            VOID osal_snv_write(BLE_NVID_IRK, KEYLEN, gapRole_IRK);
            VOID osal_snv_write(BLE_NVID_CSRK, KEYLEN, gapRole_SRK);

            // Save off the information
            VOID memcpy(gapRole_bdAddr, pPkt->devAddr, B_ADDR_LEN);

            gapRole_state = GAPROLE_STARTED;

            // Update the advertising data
            stat = GAP_UpdateAdvertisingData(selfEntity,
                                             TRUE, gapRole_AdvertDataLen, gapRole_AdvertData);
        }

        if (stat != SUCCESS)
        {
            gapRole_state = GAPROLE_ERROR;
        }

        notify = TRUE;
    }
    break;

    case GAP_ADV_DATA_UPDATE_DONE_EVENT:
    {
        gapAdvDataUpdateEvent_t *pPkt = (gapAdvDataUpdateEvent_t *)pMsg;

        if (pPkt->hdr.status == SUCCESS)
        {
            if (pPkt->adType)
            {
                // Setup the Response Data
                pPkt->hdr.status = GAP_UpdateAdvertisingData(selfEntity,
                                   FALSE, gapRole_ScanRspDataLen, gapRole_ScanRspData);
            }
            else if ((gapRole_state != GAPROLE_ADVERTISING)   &&
                     (gapRole_state != GAPROLE_CONNECTED_ADV) &&
                     (gapRole_state != GAPROLE_CONNECTED ||
                      gapRole_AdvNonConnEnabled == TRUE)      &&
                     (Util_isActive(&startAdvClock) == FALSE))
            {
                // Start advertising
                gapRole_setEvent(START_ADVERTISING_EVT);
            }
        }

        if (pPkt->hdr.status != SUCCESS)
        {
            // Set into Error state
            gapRole_state = GAPROLE_ERROR;
            notify = TRUE;
        }
    }
    break;

    case GAP_MAKE_DISCOVERABLE_DONE_EVENT:
    case GAP_END_DISCOVERABLE_DONE_EVENT:
    {
        gapMakeDiscoverableRspEvent_t *pPkt = (gapMakeDiscoverableRspEvent_t *)pMsg;

        if (pPkt->hdr.status == SUCCESS)
        {
            if (pMsg->opcode == GAP_MAKE_DISCOVERABLE_DONE_EVENT)
            {
                if (gapRole_state == GAPROLE_CONNECTED)
                {
                    gapRole_state = GAPROLE_CONNECTED_ADV;
                }
                else if (gapRole_AdvEnabled)
                {
                    gapRole_state = GAPROLE_ADVERTISING;
                }
                else
                {
                    gapRole_state = GAPROLE_ADVERTISING_NONCONN;
                }
            }
            else // GAP_END_DISCOVERABLE_DONE_EVENT
            {
                if (gapRole_AdvertOffTime != 0)
                {
                    if ((gapRole_AdvEnabled) || (gapRole_AdvNonConnEnabled))
                    {
                        Util_restartClock(&startAdvClock, gapRole_AdvertOffTime);
                    }
                }
                else
                {
                    // Since gapRole_AdvertOffTime is set to 0, the device should not
                    // automatically become discoverable again after a period of time.
                    // Set enabler to FALSE; device will become discoverable again when
                    // this value gets set to TRUE
                    if (gapRole_AdvEnabled == TRUE)
                    {
                        gapRole_AdvEnabled = FALSE;
                    }
                    else
                    {
                        gapRole_AdvNonConnEnabled = FALSE;
                    }
                }

                // Update state.
                if (gapRole_state == GAPROLE_CONNECTED_ADV)
                {
                    // In the Advertising Off period
                    gapRole_state = GAPROLE_CONNECTED;
                }
                else
                {
                    // In the Advertising Off period
                    gapRole_state = GAPROLE_WAITING;
                }
            }
        }
        else
        {
            gapRole_state = GAPROLE_ERROR;
        }

        notify = TRUE;
    }
    break;

    case GAP_LINK_ESTABLISHED_EVENT:
    {
        gapEstLinkReqEvent_t *pPkt = (gapEstLinkReqEvent_t *)pMsg;

        if (pPkt->hdr.status == SUCCESS)
        {
            VOID memcpy(gapRole_ConnectedDevAddr, pPkt->devAddr, B_ADDR_LEN);
            gapRole_ConnectionHandle = pPkt->connectionHandle;
            gapRole_state = GAPROLE_CONNECTED;

            // Store connection information
            gapRole_ConnInterval = pPkt->connInterval;
            gapRole_ConnSlaveLatency = pPkt->connLatency;
            gapRole_ConnTimeout = pPkt->connTimeout;
            gapRole_ConnectedDevAddrType = pPkt->devAddrType;

            // Check whether update parameter request is enabled
            if (gapRole_ParamUpdateEnable == TRUE)
            {
                // Get the minimum time upon connection establishment before the
                // peripheral can start a connection update procedure.
                uint16_t timeout = GAP_GetParamValue(TGAP_CONN_PAUSE_PERIPHERAL);

                Util_restartClock(&startUpdateClock, timeout*1000);
            }

            // Notify the Bond Manager to the connection
            VOID GAPBondMgr_LinkEst(pPkt->devAddrType, pPkt->devAddr,
                                    pPkt->connectionHandle, GAP_PROFILE_PERIPHERAL);
        }
        else if (pPkt->hdr.status == bleGAPConnNotAcceptable)
        {
            // Set enabler to FALSE; device will become discoverable again when
            // this value gets set to TRUE
            gapRole_AdvEnabled = FALSE;

            // Go to WAITING state, and then start advertising
            gapRole_state = GAPROLE_WAITING;
        }
        else
        {
            gapRole_state = GAPROLE_ERROR;
        }
        notify = TRUE;
    }
    break;

    case GAP_LINK_TERMINATED_EVENT:
    {
        gapTerminateLinkEvent_t *pPkt = (gapTerminateLinkEvent_t *)pMsg;

        GAPBondMgr_LinkTerm(pPkt->connectionHandle);

        memset(gapRole_ConnectedDevAddr, 0, B_ADDR_LEN);

        // Erase connection information
        gapRole_ConnInterval = 0;
        gapRole_ConnSlaveLatency = 0;
        gapRole_ConnTimeout = 0;
        gapRole_ConnTermReason = pPkt->reason;

        // Cancel all connection parameter update timers (if any active)
        Util_stopClock(&startUpdateClock);
        Util_stopClock(&updateTimeoutClock);

        notify = TRUE;

        gapRole_ConnectionHandle = INVALID_CONNHANDLE;

        // If device was advertising when connection dropped
        if (gapRole_AdvNonConnEnabled)
        {
            // Continue advertising.
            gapRole_state = GAPROLE_ADVERTISING_NONCONN;
        }
        // Else go to WAITING state.
        else
        {
            if(pPkt->reason == LL_SUPERVISION_TIMEOUT_TERM)
            {
                gapRole_state = GAPROLE_WAITING_AFTER_TIMEOUT;
            }
            else
            {
                gapRole_state = GAPROLE_WAITING;
            }

            // Start advertising, if enabled.
            gapRole_setEvent(START_ADVERTISING_EVT);
        }
    }
    break;

    case GAP_LINK_PARAM_UPDATE_EVENT:
    {
        gapLinkUpdateEvent_t *pPkt = (gapLinkUpdateEvent_t *)pMsg;

        // Cancel connection param update timeout timer (if active)
        Util_stopClock(&updateTimeoutClock);

        if (pPkt->hdr.status == SUCCESS)
        {
            // Store new connection parameters
            gapRole_ConnInterval = pPkt->connInterval;
            gapRole_ConnSlaveLatency = pPkt->connLatency;
            gapRole_ConnTimeout = pPkt->connTimeout;

            // Make sure there's no pending connection update procedure
            if(Util_isActive(&startUpdateClock) == FALSE)
            {
                // Notify the application with the new connection parameters
                if (pGapRoles_ParamUpdateCB != NULL)
                {
                    (*pGapRoles_ParamUpdateCB)(gapRole_ConnInterval,
                                               gapRole_ConnSlaveLatency,
                                               gapRole_ConnTimeout);
                }
            }
        }
    }
    break;

    case GAP_PAIRING_REQ_EVENT:
    {
        gapPairingReqEvent_t *pPkt = (gapPairingReqEvent_t *)pMsg;

        // Send Pairing Failed Response
        VOID GAP_TerminateAuth(pPkt->connectionHandle,
                               SMP_PAIRING_FAILED_NOT_SUPPORTED);
    }
    break;

    default:
        break;
    }

    if (notify == TRUE)
    {
        // Notify the application with the new state change
        if (pGapRoles_AppCGs && pGapRoles_AppCGs->pfnStateChange)
        {
            pGapRoles_AppCGs->pfnStateChange(gapRole_state);
        }
    }
}
コード例 #17
0
ファイル: peripheral.c プロジェクト: ClarePhang/BLE_cc2650
/*********************************************************************
 * @brief   Set a GAP Role parameter.
 *
 * Public function defined in peripheral.h.
 */
bStatus_t GAPRole_SetParameter(uint16_t param, uint8_t len, void *pValue)
{
    bStatus_t ret = SUCCESS;
    switch (param)
    {
    case GAPROLE_IRK:
        if (len == KEYLEN)
        {
            VOID memcpy(gapRole_IRK, pValue, KEYLEN) ;
        }
        else
        {
            ret = bleInvalidRange;
        }
        break;

    case GAPROLE_SRK:
        if (len == KEYLEN)
        {
            VOID memcpy(gapRole_SRK, pValue, KEYLEN) ;
        }
        else
        {
            ret = bleInvalidRange;
        }
        break;

    case GAPROLE_SIGNCOUNTER:
        if (len == sizeof (uint32_t))
        {
            gapRole_signCounter = *((uint32_t*)pValue);
        }
        else
        {
            ret = bleInvalidRange;
        }
        break;

    case GAPROLE_ADVERT_ENABLED:
        if (len == sizeof(uint8_t))
        {
            // Non-connectable advertising must be disabled.
            if (gapRole_AdvNonConnEnabled != TRUE)
            {
                uint8_t oldAdvEnabled = gapRole_AdvEnabled;
                gapRole_AdvEnabled = *((uint8_t*)pValue);

                if ((oldAdvEnabled) && (gapRole_AdvEnabled == FALSE))
                {
                    // Turn off advertising.
                    if ((gapRole_state == GAPROLE_ADVERTISING)
                            || (gapRole_state == GAPROLE_WAITING_AFTER_TIMEOUT))
                    {
                        VOID GAP_EndDiscoverable(selfEntity);
                    }
                }
                else if ((oldAdvEnabled == FALSE) && (gapRole_AdvEnabled))
                {
                    // Turn on advertising.
                    if ((gapRole_state == GAPROLE_STARTED)
                            || (gapRole_state == GAPROLE_WAITING)
                            || (gapRole_state == GAPROLE_WAITING_AFTER_TIMEOUT))
                    {
                        gapRole_setEvent(START_ADVERTISING_EVT);
                    }
                }
            }
            else
            {
                ret = bleIncorrectMode;
            }
        }
        else
        {
            ret = bleInvalidRange;
        }
        break;

    case GAPROLE_ADV_NONCONN_ENABLED:
        if (len == sizeof(uint8_t))
        {
            // Connectable advertising must be disabled.
            if (gapRole_AdvEnabled != TRUE)
            {
                uint8_t oldAdvEnabled = gapRole_AdvNonConnEnabled;
                gapRole_AdvNonConnEnabled = *((uint8_t*)pValue);

                if ((oldAdvEnabled) && (gapRole_AdvNonConnEnabled == FALSE))
                {
                    if ((gapRole_state == GAPROLE_ADVERTISING_NONCONN)
                            || (gapRole_state == GAPROLE_CONNECTED_ADV)
                            || (gapRole_state == GAPROLE_WAITING_AFTER_TIMEOUT))
                    {
                        VOID GAP_EndDiscoverable(selfEntity);
                    }
                }
                else if ((oldAdvEnabled == FALSE) && (gapRole_AdvNonConnEnabled))
                {
                    // Turn on advertising.
                    if ((gapRole_state == GAPROLE_STARTED)
                            || (gapRole_state == GAPROLE_WAITING)
                            || (gapRole_state == GAPROLE_CONNECTED)
                            || (gapRole_state == GAPROLE_WAITING_AFTER_TIMEOUT))
                    {
                        gapRole_setEvent(START_ADVERTISING_EVT);
                    }
                }
            }
            else
            {
                ret = bleIncorrectMode;
            }
        }
        else
        {
            ret = bleInvalidRange;
        }
        break;

    case GAPROLE_ADVERT_OFF_TIME:
        if (len == sizeof (uint16_t))
        {
            gapRole_AdvertOffTime = *((uint16_t*)pValue);
        }
        else
        {
            ret = bleInvalidRange;
        }
        break;

    case GAPROLE_ADVERT_DATA:
        if (len <= B_MAX_ADV_LEN)
        {
            VOID memset(gapRole_AdvertData, 0, B_MAX_ADV_LEN);
            VOID memcpy(gapRole_AdvertData, pValue, len);
            gapRole_AdvertDataLen = len;

            // Update the advertising data
            ret = GAP_UpdateAdvertisingData(selfEntity,
                                            TRUE, gapRole_AdvertDataLen, gapRole_AdvertData);
        }
        else
        {
            ret = bleInvalidRange;
        }
        break;

    case GAPROLE_SCAN_RSP_DATA:
        if (len <= B_MAX_ADV_LEN)
        {
            VOID memset(gapRole_ScanRspData, 0, B_MAX_ADV_LEN);
            VOID memcpy(gapRole_ScanRspData, pValue, len);
            gapRole_ScanRspDataLen = len;

            // Update the Response Data
            ret = GAP_UpdateAdvertisingData(selfEntity,
                                            FALSE, gapRole_ScanRspDataLen, gapRole_ScanRspData);
        }
        else
        {
            ret = bleInvalidRange;
        }
        break;

    case GAPROLE_ADV_EVENT_TYPE:
        if ((len == sizeof (uint8_t)) && (*((uint8_t*)pValue) <= GAP_ADTYPE_ADV_LDC_DIRECT_IND))
        {
            gapRole_AdvEventType = *((uint8_t*)pValue);
        }
        else
        {
            ret = bleInvalidRange;
        }
        break;

    case GAPROLE_ADV_DIRECT_TYPE:
        if ((len == sizeof (uint8_t)) && (*((uint8_t*)pValue) <= ADDRTYPE_PRIVATE_RESOLVE))
        {
            gapRole_AdvDirectType = *((uint8_t*)pValue);
        }
        else
        {
            ret = bleInvalidRange;
        }
        break;

    case GAPROLE_ADV_DIRECT_ADDR:
        if (len == B_ADDR_LEN)
        {
            VOID memcpy(gapRole_AdvDirectAddr, pValue, B_ADDR_LEN) ;
        }
        else
        {
            ret = bleInvalidRange;
        }
        break;

    case GAPROLE_ADV_CHANNEL_MAP:
        if ((len == sizeof (uint8_t)) && (*((uint8_t*)pValue) <= 0x07))
        {
            gapRole_AdvChanMap = *((uint8_t*)pValue);
        }
        else
        {
            ret = bleInvalidRange;
        }
        break;

    case GAPROLE_ADV_FILTER_POLICY:
        if ((len == sizeof (uint8_t)) && (*((uint8_t*)pValue) <= GAP_FILTER_POLICY_WHITE))
        {
            gapRole_AdvFilterPolicy = *((uint8_t*)pValue);
        }
        else
        {
            ret = bleInvalidRange;
        }
        break;

    case GAPROLE_PARAM_UPDATE_ENABLE:
        if ((len == sizeof (uint8_t)) && (*((uint8_t*)pValue) <= TRUE))
        {
            gapRole_ParamUpdateEnable = *((uint8_t*)pValue);
        }
        else
        {
            ret = bleInvalidRange;
        }
        break;

    case GAPROLE_MIN_CONN_INTERVAL:
    {
        uint16_t newInterval = *((uint16_t*)pValue);
        if (  len == sizeof (uint16_t)           &&
                (newInterval >= MIN_CONN_INTERVAL) &&
                (newInterval <= MAX_CONN_INTERVAL))
        {
            gapRole_MinConnInterval = newInterval;
        }
        else
        {
            ret = bleInvalidRange;
        }
    }
    break;

    case GAPROLE_MAX_CONN_INTERVAL:
    {
        uint16_t newInterval = *((uint16_t*)pValue);
        if (  len == sizeof (uint16_t)          &&
                (newInterval >= MIN_CONN_INTERVAL) &&
                (newInterval <= MAX_CONN_INTERVAL))
        {
            gapRole_MaxConnInterval = newInterval;
        }
        else
        {
            ret = bleInvalidRange;
        }
    }
    break;

    case GAPROLE_SLAVE_LATENCY:
    {
        uint16_t latency = *((uint16_t*)pValue);
        if (len == sizeof (uint16_t) && (latency < MAX_SLAVE_LATENCY))
        {
            gapRole_SlaveLatency = latency;
        }
        else
        {
            ret = bleInvalidRange;
        }
    }
    break;

    case GAPROLE_TIMEOUT_MULTIPLIER:
    {
        uint16_t newTimeout = *((uint16_t*)pValue);
        if (len == sizeof (uint16_t)
                && (newTimeout >= MIN_TIMEOUT_MULTIPLIER) && (newTimeout <= MAX_TIMEOUT_MULTIPLIER))
        {
            gapRole_TimeoutMultiplier = newTimeout;
        }
        else
        {
            ret = bleInvalidRange;
        }
    }
    break;

    case GAPROLE_PARAM_UPDATE_REQ:
    {
        uint8_t req = *((uint8_t*)pValue);
        if (len == sizeof (uint8_t) && (req == TRUE))
        {
            // Make sure we don't send an L2CAP Connection Parameter Update Request
            // command within TGAP(conn_param_timeout) of an L2CAP Connection Parameter
            // Update Response being received.
            if (Util_isActive(&updateTimeoutClock) == FALSE)
            {
                // Start connection update procedure
                ret = gapRole_startConnUpdate(GAPROLE_NO_ACTION);
                if (ret == SUCCESS)
                {
                    // Connection update requested by app, cancel such pending procedure (if active)
                    Util_stopClock(&startUpdateClock);
                }
            }
            else
            {
                ret = blePending;
            }
        }
        else
        {
            ret = bleInvalidRange;
        }
    }
    break;

    default:
        // The param value isn't part of this profile, try the GAP.
        if ((param < TGAP_PARAMID_MAX) && (len == sizeof (uint16_t)))
        {
            ret = GAP_SetParamValue(param, *((uint16_t*)pValue));
        }
        else
        {
            ret = INVALIDPARAMETER;
        }
        break;
    }

    return (ret);
}
コード例 #18
0
/*********************************************************************
 * @fn      glucCollCentral_processRoleEvent
 *
 * @brief   Central event callback function.
 *
 * @param   pEvent - pointer to event structure
 *
 * @return  TRUE if safe to deallocate event message, FALSE otherwise.
 */
static uint8_t glucCollCentral_processRoleEvent(gapCentralRoleEvent_t *pEvent)
{
  switch (pEvent->gap.opcode)
  {
    case GAP_DEVICE_INIT_DONE_EVENT:  
      {
        LCD_WRITE_STRING("Gluc. Collector", LCD_PAGE0);
        LCD_WRITE_STRING(Util_convertBdAddr2Str(pEvent->initDone.devAddr), 
                         LCD_PAGE1);
      }
      break;

    case GAP_DEVICE_INFO_EVENT:
      {
        // if filtering device discovery results based on service UUID
        if (DEFAULT_DEV_DISC_BY_SVC_UUID == TRUE)
        {
          if (glucCollCentral_findSvcUuid(GLUCOSE_SERV_UUID,
                                          pEvent->deviceInfo.pEvtData,
                                          pEvent->deviceInfo.dataLen))
          {
            glucCollCentral_addDeviceInfo(pEvent->deviceInfo.addr, 
                                          pEvent->deviceInfo.addrType);
          }
        }
      }
      break;

    case GAP_DEVICE_DISCOVERY_EVENT:
      {
        // discovery complete
        glucCollScanning = FALSE;

        // if not filtering device discovery results based on service UUID
        if (DEFAULT_DEV_DISC_BY_SVC_UUID == FALSE)
        {
          // Copy results
          glucCollScanRes = pEvent->discCmpl.numDevs;
          memcpy(glucCollDevList, pEvent->discCmpl.pDevList,
                 (sizeof(gapDevRec_t) * pEvent->discCmpl.numDevs));
        }
        
        LCD_WRITE_STRING_VALUE("Devices Found", glucCollScanRes,
                                10, LCD_PAGE0);
        if (glucCollScanRes > 0)
        {
          LCD_WRITE_STRING("<- To Select", LCD_PAGE1);
        }

        // initialize scan index to last device
        glucCollScanIdx = glucCollScanRes;
      }
      break;

    case GAP_LINK_ESTABLISHED_EVENT:
      {
        if (pEvent->gap.hdr.status == SUCCESS)
        {          
          glucCollState = BLE_STATE_CONNECTED;
          glucCollConnHandle = pEvent->linkCmpl.connectionHandle;

          // If service discovery not performed initiate service discovery
          if (glucCollCharHdls == false)
          {
            // start procedure timer
            Util_stopClock(&discoveryClock);
            Util_startClock(&discoveryClock);
          }

          LCD_WRITE_STRING("Connected", LCD_PAGE0);
          LCD_WRITE_STRING(Util_convertBdAddr2Str(pEvent->linkCmpl.devAddr), 
                           LCD_PAGE1);
        }
        else
        {
          glucCollState = BLE_STATE_IDLE;
          glucCollConnHandle = GAP_CONNHANDLE_INIT;
          glucCollDiscState = DISC_IDLE;

          LCD_WRITE_STRING("Connect Failed", LCD_PAGE0);
          LCD_WRITE_STRING_VALUE("Reason:", pEvent->gap.hdr.status, 10, 
                                 LCD_PAGE1);
          LCD_WRITE_STRING("", LCD_PAGE2);
        }
      }
      break;

    case GAP_LINK_TERMINATED_EVENT:
      {
        glucCollState = BLE_STATE_IDLE;
        glucCollConnHandle = GAP_CONNHANDLE_INIT;
        glucCollDiscState = DISC_IDLE;
        glucCollPairingStarted = false;
        glucCollDiscPostponed = false;
        glucCollClearPending = false;

        // stop procedure timer
        Util_stopClock(&procTimeoutClock);

        LCD_WRITE_STRING("Disconnected", LCD_PAGE0);
        LCD_WRITE_STRING_VALUE("Reason:", pEvent->linkTerminate.reason,
                                10, LCD_PAGE1);
        LCD_WRITE_STRING("", LCD_PAGE2);        
      }
      break;

    case GAP_LINK_PARAM_UPDATE_EVENT:
      {
        LCD_WRITE_STRING("Param Update", LCD_PAGE0);
        LCD_WRITE_STRING("", LCD_PAGE1);
        LCD_WRITE_STRING("", LCD_PAGE2);
      }
      break;

    default:
      break;
  }

  return (TRUE);
}
コード例 #19
0
/*********************************************************************
 * @fn      SimpleBLEPeripheral_processStateChangeEvt
 *
 * @brief   Process a pending GAP Role state change event.
 *
 * @param   newState - new state
 *
 * @return  None.
 */
static void SimpleBLEPeripheral_processStateChangeEvt(gaprole_States_t newState)
{
#ifdef PLUS_BROADCASTER
  static bool firstConnFlag = false;
#endif // PLUS_BROADCASTER

  switch ( newState )
  {
    case GAPROLE_STARTED:
      {
        uint8_t ownAddress[B_ADDR_LEN];
        uint8_t systemId[DEVINFO_SYSTEM_ID_LEN];

        GAPRole_GetParameter(GAPROLE_BD_ADDR, ownAddress);

        // use 6 bytes of device address for 8 bytes of system ID value
        systemId[0] = ownAddress[0];
        systemId[1] = ownAddress[1];
        systemId[2] = ownAddress[2];

        // set middle bytes to zero
        systemId[4] = 0x00;
        systemId[3] = 0x00;

        // shift three bytes up
        systemId[7] = ownAddress[5];
        systemId[6] = ownAddress[4];
        systemId[5] = ownAddress[3];

        DevInfo_SetParameter(DEVINFO_SYSTEM_ID, DEVINFO_SYSTEM_ID_LEN, systemId);

        // Display device address
        Display_print0(dispHandle, 1, 0, Util_convertBdAddr2Str(ownAddress));
        Display_print0(dispHandle, 2, 0, "Initialized");
      }
      break;

    case GAPROLE_ADVERTISING:
      Display_print0(dispHandle, 2, 0, "Advertising");
      break;

#ifdef PLUS_BROADCASTER
    /* After a connection is dropped a device in PLUS_BROADCASTER will continue
     * sending non-connectable advertisements and shall sending this change of
     * state to the application.  These are then disabled here so that sending
     * connectable advertisements can resume.
     */
    case GAPROLE_ADVERTISING_NONCONN:
      {
        uint8_t advertEnabled = FALSE;

        // Disable non-connectable advertising.
        GAPRole_SetParameter(GAPROLE_ADV_NONCONN_ENABLED, sizeof(uint8_t),
                           &advertEnabled);

        advertEnabled = TRUE;

        // Enabled connectable advertising.
        GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8_t),
                             &advertEnabled);

        // Reset flag for next connection.
        firstConnFlag = false;

        SimpleBLEPeripheral_freeAttRsp(bleNotConnected);
      }
      break;
#endif //PLUS_BROADCASTER

    case GAPROLE_CONNECTED:
      {
        linkDBInfo_t linkInfo;
        uint8_t numActive = 0;

        Util_startClock(&periodicClock);

        numActive = linkDB_NumActive();

        // Use numActive to determine the connection handle of the last
        // connection
        if ( linkDB_GetInfo( numActive - 1, &linkInfo ) == SUCCESS )
        {
          Display_print1(dispHandle, 2, 0, "Num Conns: %d", (uint16_t)numActive);
          Display_print0(dispHandle, 3, 0, Util_convertBdAddr2Str(linkInfo.addr));
        }
        else
        {
          uint8_t peerAddress[B_ADDR_LEN];

          GAPRole_GetParameter(GAPROLE_CONN_BD_ADDR, peerAddress);

          Display_print0(dispHandle, 2, 0, "Connected");
          Display_print0(dispHandle, 3, 0, Util_convertBdAddr2Str(peerAddress));
        }

        #ifdef PLUS_BROADCASTER
          // Only turn advertising on for this state when we first connect
          // otherwise, when we go from connected_advertising back to this state
          // we will be turning advertising back on.
          if (firstConnFlag == false)
          {
            uint8_t advertEnabled = FALSE; // Turn on Advertising

            // Disable connectable advertising.
            GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8_t),
                                 &advertEnabled);

            // Set to true for non-connectabel advertising.
            advertEnabled = TRUE;

            // Enable non-connectable advertising.
            GAPRole_SetParameter(GAPROLE_ADV_NONCONN_ENABLED, sizeof(uint8_t),
                                 &advertEnabled);
            firstConnFlag = true;
          }
        #endif // PLUS_BROADCASTER
      }
      break;

    case GAPROLE_CONNECTED_ADV:
      Display_print0(dispHandle, 2, 0, "Connected Advertising");
      break;

    case GAPROLE_WAITING:
      Util_stopClock(&periodicClock);
      SimpleBLEPeripheral_freeAttRsp(bleNotConnected);

      Display_print0(dispHandle, 2, 0, "Disconnected");

      // Clear remaining lines
      Display_clearLines(dispHandle, 3, 5);
      break;

    case GAPROLE_WAITING_AFTER_TIMEOUT:
      SimpleBLEPeripheral_freeAttRsp(bleNotConnected);

      Display_print0(dispHandle, 2, 0, "Timed Out");

      // Clear remaining lines
      Display_clearLines(dispHandle, 3, 5);

      #ifdef PLUS_BROADCASTER
        // Reset flag for next connection.
        firstConnFlag = false;
      #endif //#ifdef (PLUS_BROADCASTER)
      break;

    case GAPROLE_ERROR:
      Display_print0(dispHandle, 2, 0, "Error");
      break;

    default:
      Display_clearLine(dispHandle, 2);
      break;
  }

  // Update the state
  //gapProfileState = newState;
}
コード例 #20
0
// 以下1-9每100毫秒执行一次
static void Pollint100mSec(void)
{
    switch(r_pollint._10msCount)
    {
		case 0:
			Pollint1Sec();
			break;
        case 1:
			
            break;
		case 2:
            if ((r_pollint._500msCount++) >= 5)
            {
                r_pollint._500msCount = 0;
				if (1 == systemState.lowBatteryFlag)
				{
					static uint8_t bmpFlash = 0;
					if (bmpFlash)
					{
						bmpFlash = 0;
						OLED_showBatteryBmp(0, 88, 8);
					}
					else
					{						
						bmpFlash = 1;
						OLED_showBatteryBmp(0, 88, 6);
					}
				}
                OLED_Refresh_Gram();//更新显示
            }
			break;
        case 3:
			//OLED_Refresh_Gram();//更新显示
            break;
        case 4:
			if (3 == systemState.keyUpFlag)
			{
				if (systemState.delayCnt-- == 0)
				{
					systemState.keyUpFlag = 0;
					{							
						// 关闭广播
						uint8_t initialAdvertEnable = FALSE;
						GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8_t), &initialAdvertEnable);
					}
					Util_stopClock(&periodicClock_10ms);
				}
					
			}
            break;
        case 5:
			
            break;
        case 6:
            break;
        case 7:
            break;
        case 8:
            break;
        default:
            break;
    }
}
コード例 #21
0
//===============================================
void userStopClock10ms(void)
{
	Util_stopClock(&periodicClock_10ms);
}
コード例 #22
0
/*******************************************************************************
 * @fn      userAppClockStop
 *
 * @brief   stop task clock
 *
 * @param   evnet
 *
 * @return  none
 */
void userAppClockStop(void)
{
	Util_stopClock(&periodicClock_10ms);
}
コード例 #23
0
/*******************************************************************************
 * @fn      userAppPro
 *
 * @brief   user Application event process
 *
 * @param   evnet
 *
 * @return  none
 */
void userAppPro(void)
{
	if (userEvents & USER_10MS_EVT)
	{
		userEvents &= ~USER_10MS_EVT;
		
		Util_startClock(&periodicClock_10ms);
		
		KEY_Scan_10ms();
		
		ChangeTime10mSec();

		Pollint100mSec();
	}

#ifdef INCLUDE_CLKSTOP
	while (!Queue_empty(keyMsgQueue))
	{
		KEY_stEvt_t *pMsg = (KEY_stEvt_t *)Util_dequeueMsg(keyMsgQueue);
		if (pMsg)
		{
			// Process message.
			switch(pMsg->GPIOName)
			{
				case KEY_NAME_3V3:
					if (KEY_HIGH == pMsg->GPIOStatus)
					{
						wifiPowerOn();
						uartWriteDebug("poweron3v3", 10);
						OLED_ShowString(40,32, "WiCore"); 
						
						userAppShowCharge();
						// 启动广播
						{
							uint8_t initialAdvertEnable = TRUE;
							GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8_t), &initialAdvertEnable);
						}
						Util_startClock(&periodicClock_10ms);
					}
					else
					{
						wifiPowerDown();
						uartWriteDebug("powerdown3v3", 12);
						// 清低电闪烁
						systemState.lowBatteryFlag = 0;
						OLED_Clear(); // 这个执行时间较长 打乱了定时周期,所以stopClock是没有用的
						//Util_stopClock(&periodicClock_10ms);
					
						// 服务器的按键开关机 设置一个按键放开标志位,等待1s后没有放开
						// 就清标志位,关闭时钟	
						systemState.keyUpFlag = 3;	     // 2 为电源按键 等待按键放开标志,3为 服务器按键
						systemState.delayCnt = 10;
						// 有链接,关闭	
						GAPRole_TerminateConnection();
						
					}
					break;
				case KEY_POWER:
					if (KEY_IQR == pMsg->GPIOStatus)
					{
						KEY_DisableIRQ();
						uartWriteDebug("tttt", 4);
						systemState.powerOffFlag = 1;
						systemState.delayPowerOffTime = 5; // 延时5s 判断是否是按键长按
						Util_startClock(&periodicClock_10ms);
					}
					else if (KEY_LONG == pMsg->GPIOStatus)
					{
						if (1 == systemState.powerOffFlag)
						{
							systemState.powerOffFlag = 0;
							systemState.delayPowerOffTime = 0;
							wifiPowerOn();
							
							userAppShowCharge();
							OLED_ShowString(40,32, "WiCore");
							
							// 启动广播
							{
								uint8_t initialAdvertEnable = TRUE;
								GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8_t), &initialAdvertEnable);
							}

							uartWriteDebug("poweron", 7);
						}
						else
						{
							//系统断电
							
							wifiPowerDown();
							uartWriteDebug("powerdown", 9);
							
							OLED_Clear();
													
							systemState.lowBatteryFlag = 0;  // 清低电闪烁 
							systemState.keyUpFlag = 2;	     // 2 为电源按键 等待按键放开标志,3为 服务器按键
							// 有链接,关闭	
							GAPRole_TerminateConnection();
						}
						systemState.keyShortFlag = 0;   // 忽略短按事件 
						
					}
					else if (KEY_LOW == pMsg->GPIOStatus)// 松开
					{
						if (2 == systemState.keyUpFlag)	// 长按松开,关机 
						{
							systemState.keyUpFlag = 0;
							//开启外部中断
							KEY_EnableIRQ();
							{		
								// 关闭广播
								uint8_t initialAdvertEnable = FALSE;
								GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8_t), &initialAdvertEnable);
							}
							Util_stopClock(&periodicClock_10ms);
						}
						else if (1 == systemState.keyShortFlag)// 短按松开 产生一次短按完整事件
						{
							//短按事件处理
							uartWriteDebug("短按", 4);
						}
					}
					else if (KEY_HIGH == pMsg->GPIOStatus) // 短按
					{
						if (1 == systemState.powerOffFlag) // 等待长按事件 忽略此时的短按事件
						{
							systemState.delayPowerOffTime = 5;	// 防止timout 剩2s时又产生长按事件					
						}
						else
						{
							systemState.keyShortFlag = 1;
						}
						
					}
					break;
				default:
					break;
			}
	
			// Free the space from the message.
			ICall_free(pMsg);
		}
	}
#else
	while (!Queue_empty(keyMsgQueue))
	{
		KEY_stEvt_t *pMsg = (KEY_stEvt_t *)Util_dequeueMsg(keyMsgQueue);
		if (pMsg)
		{
			// Process message.
			switch(pMsg->GPIOName)
			{
				case KEY_NAME_3V3:
					if (KEY_HIGH == pMsg->GPIOStatus)
					{
						wifiPowerOn();
						uartWriteDebug("poweron3v3", 10);
						OLED_ShowString(40,32, "WiCore"); 
						
						userAppShowCharge();
						// 启动广播
						{
							uint8_t initialAdvertEnable = TRUE;
							GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8_t), &initialAdvertEnable);
						}

						systemState.powerOffFlag = 0;
					}
					else
					{
						wifiPowerDown();
						uartWriteDebug("powerdown3v3", 12);
						// 清低电闪烁
						systemState.lowBatteryFlag = 0;
						OLED_Clear(); // 这个执行时间较长 打乱了定时周期,所以stopClock是没有用的

						// 有链接,关闭 
						GAPRole_TerminateConnection();

						systemState.powerOffFlag = 1;
						
					}
					break;
				case KEY_POWER:
					if (KEY_LONG == pMsg->GPIOStatus)
					{
						if (1 == systemState.powerOffFlag)
						{
							systemState.powerOffFlag = 0;
							systemState.delayPowerOffTime = 0;
							systemState.keyUpFlag=0;
							wifiPowerOn();
							
							userAppShowCharge();
							OLED_ShowString(40,32, "WiCore");
							
							// 启动广播
							{
								uint8_t initialAdvertEnable = TRUE;
								GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8_t), &initialAdvertEnable);
							}

							uartWriteDebug("poweron", 7);
						}
						else
						{
							//系统断电
							systemState.keyUpFlag=0;
							systemState.powerOffFlag = 1;
							wifiPowerDown();
							uartWriteDebug("powerdown", 9);
							
							OLED_Clear();
													
							systemState.lowBatteryFlag = 0;  // 清低电闪烁 
							// 有链接,关闭 
							GAPRole_TerminateConnection();
						}
						systemState.keyShortFlag = 0;	// 忽略短按事件 
						
					}
					else if (KEY_LOW == pMsg->GPIOStatus)// 松开
					{
						
						if (1 == systemState.keyShortFlag)// 短按松开 产生一次短按完整事件
						{
							//短按事件处理
							uartWriteDebug("短按", 4);
							systemState.keyShortFlag = 0;
						}
					}
					else if (KEY_HIGH == pMsg->GPIOStatus) // 短按
					{
						if (1 == systemState.powerOffFlag) // 等待长按事件 忽略此时的短按事件
						{
							// 关机中 不处理				
						}
						else
						{
							systemState.keyShortFlag = 1;
						}
						
					}
					break;
				default:
					break;
			}

			// Free the space from the message.
			ICall_free(pMsg);
		}
	}

#endif
}
コード例 #24
0
/*********************************************************************
 * @fn      RunningSensor_HandleKeys
 *
 * @brief   Handles all key events for this device.
 *
 * @param   shift - true if in shift/alt.
 * @param   keys - bit field for key events. Valid entries:
 *                 KEY_SELECT
 *                 KEY_UP
 *                 KEY_RIGHT
 *
 * @return  none
 */
static void RunningSensor_handleKeys(uint8_t shift, uint8_t keys)
{
  // If a reset was in progress, cancel it.
  if (resetInProgress == TRUE)
  {
    resetInProgress = FALSE;
    
    Util_stopClock(&resetClock);
    
#if USING_NEGLECT_TIMEOUT    
    // If using neglect time and in a connection.
    if (gapProfileState == GAPROLE_CONNECTED)
    {
      // Restart neglect timer.
      Util_startClock(&neglectClock);
    }
#endif //USING_NEGLECT_TIMEOUT    
    
    return;
  }
  
  if (keys & KEY_SELECT)
  {
    // Reset in progress has started.
    resetInProgress = TRUE;

#if USING_NEGLECT_TIMEOUT
    // Stop the neglect timer.
    Util_stopClock(&neglectClock);
#endif //USING_NEGLECT_TIMEOUT
    
    // Start reset timer.
    Util_startClock(&resetClock);
  }
  else if (keys & KEY_UP)
  {
    // Set simulated measurement flag index.
    if (++sensorFlagsIdx == FLAGS_IDX_MAX)
    {
      sensorFlagsIdx = 0;
    }
  }
  else if (keys & KEY_RIGHT)
  {
    // If not in a connection, toggle advertising on and off.
    if (gapProfileState != GAPROLE_CONNECTED)
    {
      uint8_t advStatus;

      // Set fast advertising interval for user-initiated connections.
      GAP_SetParamValue(TGAP_GEN_DISC_ADV_INT_MIN, DEFAULT_FAST_ADV_INTERVAL);
      GAP_SetParamValue(TGAP_GEN_DISC_ADV_INT_MAX, DEFAULT_FAST_ADV_INTERVAL);
      GAP_SetParamValue(TGAP_GEN_DISC_ADV_MIN, DEFAULT_WHITE_LIST_ADV_DURATION);

      // Toggle GAP advertisement status.
      GAPRole_GetParameter(GAPROLE_ADVERT_ENABLED, &advStatus);
      advStatus = !advStatus;

      // If not already using white list, begin to do so.
      // Only do so if about to begin advertising.
      if (USING_WHITE_LIST && advStatus == TRUE)
      {
        uint8_t bondCount = 0;

        GAPBondMgr_GetParameter(GAPBOND_BOND_COUNT, &bondCount);

        if ((sensorUsingWhiteList == FALSE) && (bondCount > 0))
        {
          uint8_t value = GAP_FILTER_POLICY_WHITE;

          GAPRole_SetParameter(GAPROLE_ADV_FILTER_POLICY, sizeof(uint8_t), 
                               &value);

          sensorUsingWhiteList = TRUE;
        }
      }

      GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8_t), &advStatus);

      // Set state variable.
      if (advStatus == FALSE)
      {
        sensorAdvCancelled = TRUE;
      }
    }
    else if (gapProfileState == GAPROLE_CONNECTED)
    {
      // If connected, change rate of motion.
      if(++motionIdx == MOTION_IDX_MAX)
      {
        motionIdx = 0;
      }

      motion = motionCycle[motionIdx];
    }
  }
}
コード例 #25
0
ファイル: multi.c プロジェクト: 247765843/ble_examples
/*********************************************************************
 * @fn      gapRole_processGAPMsg
 *
 * @brief   Process an incoming task message.
 *
 * @param   pMsg - message to process
 *
 * @return  none
 */
static uint8_t gapRole_processGAPMsg(gapEventHdr_t *pMsg)
{
  uint8_t notify = FALSE;   // State changed notify the app? (default no)

  switch (pMsg->opcode)
  {
    case GAP_DEVICE_INIT_DONE_EVENT:
      {
        gapDeviceInitDoneEvent_t *pPkt = (gapDeviceInitDoneEvent_t *)pMsg;
        bStatus_t stat = pPkt->hdr.status;

        if (stat == SUCCESS)
        {
          // Save off the generated keys
          VOID osal_snv_write(BLE_NVID_IRK, KEYLEN, gapRole_IRK);
          VOID osal_snv_write(BLE_NVID_CSRK, KEYLEN, gapRole_SRK);

          // Save off the information
          VOID memcpy(gapRole_bdAddr, pPkt->devAddr, B_ADDR_LEN);

          // Update the advertising data
          stat = GAP_UpdateAdvertisingData(selfEntity,
                              TRUE, gapRole_AdvertDataLen, gapRole_AdvertData);
        }

        if (stat != SUCCESS)
        {
          gapRole_abort();
        }

        notify = TRUE;
      }
      break;

    case GAP_ADV_DATA_UPDATE_DONE_EVENT:
      {
        gapAdvDataUpdateEvent_t *pPkt = (gapAdvDataUpdateEvent_t *)pMsg;

        if (pPkt->hdr.status == SUCCESS)
        {
          if (pPkt->adType)
          {
            // Setup the Response Data
            pPkt->hdr.status = GAP_UpdateAdvertisingData(selfEntity,
                              FALSE, gapRole_ScanRspDataLen, gapRole_ScanRspData);
          }
          else if (Util_isActive(&startAdvClock) == FALSE)
          {
            // Start advertising
            gapRole_setEvent(START_ADVERTISING_EVT);
          }
        }

        if (pPkt->hdr.status != SUCCESS)
        {
          // Set into Error state
          gapRole_abort();
          notify = TRUE;
        }
      }
      break;

    case GAP_MAKE_DISCOVERABLE_DONE_EVENT:
    case GAP_END_DISCOVERABLE_DONE_EVENT:
      {
        gapMakeDiscoverableRspEvent_t *pPkt = (gapMakeDiscoverableRspEvent_t *)pMsg;

        if (pPkt->hdr.status == SUCCESS)
        {
          if (pMsg->opcode == GAP_MAKE_DISCOVERABLE_DONE_EVENT)
          {
            gapRole_AdvEnabled = TRUE;
          }
          else // GAP_END_DISCOVERABLE_DONE_EVENT
          {
            if (gapRole_AdvertOffTime != 0) //restart advertising if param is set
            {
              if ((gapRole_AdvEnabled) || (gapRole_AdvNonConnEnabled))
              {
                Util_restartClock(&startAdvClock, gapRole_AdvertOffTime);
              }
            }
            else
            {
              // Since gapRole_AdvertOffTime is set to 0, the device should not
              // automatically become discoverable again after a period of time.
              // Set enabler to FALSE; device will become discoverable again when
              // this value gets set to TRUE
              if (gapRole_AdvEnabled == TRUE)
              {
                gapRole_AdvEnabled = FALSE;
              }
            }
          }
          notify = TRUE;
        }
        else if (pPkt->hdr.status == LL_STATUS_ERROR_COMMAND_DISALLOWED) //we're already advertising
        {
          notify = FALSE;
        }
        else
        {
          gapRole_abort();
        }
      }
      break;

    case GAP_LINK_ESTABLISHED_EVENT:
      {
        gapEstLinkReqEvent_t *pPkt = (gapEstLinkReqEvent_t *)pMsg;
        uint8_t advertEnable = TRUE;

        if (pPkt->hdr.status == SUCCESS)
        {
          // Notify the Bond Manager to the connection
          VOID GAPBondMgr_LinkEst(pPkt->devAddrType, pPkt->devAddr,
                                  pPkt->connectionHandle, pPkt->connRole);    

          //advertising will stop after connection formed as slave
          if ((pPkt->connRole) == GAP_PROFILE_PERIPHERAL)
          {
            gapRole_AdvEnabled = FALSE;
            //reenable advertising
            GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8_t),
                                 &advertEnable, NULL);            
          }
        }
        else if (pPkt->hdr.status == bleGAPConnNotAcceptable)
        {
          // Set enabler to FALSE; device will become discoverable again when
          // this value gets set to TRUE
          gapRole_AdvEnabled = FALSE;
        }
        else
        {
          gapRole_abort();
        }
        
        notify = TRUE;
      }
      break;

    case GAP_LINK_TERMINATED_EVENT:
      {
        gapTerminateLinkEvent_t *pPkt = (gapTerminateLinkEvent_t *)pMsg;

        linkDBInfo_t pInfo;
        linkDB_GetInfo(pPkt->connectionHandle, &pInfo);
        
        // notify bond manager
        GAPBondMgr_LinkTerm(pPkt->connectionHandle);

        notify = TRUE;
      }
      break;

    case GAP_SLAVE_REQUESTED_SECURITY_EVENT:
      {
        uint16_t connHandle = ((gapSlaveSecurityReqEvent_t *)pMsg)->connectionHandle;
        uint8_t authReq = ((gapSlaveSecurityReqEvent_t *)pMsg)->authReq;
        
        GAPBondMgr_SlaveReqSecurity(connHandle, authReq);
      }
      break;     
      
    case GAP_LINK_PARAM_UPDATE_EVENT:
      {
        gapLinkUpdateEvent_t *pPkt = (gapLinkUpdateEvent_t *)pMsg;
        
        // Cancel connection param update timeout timer (if active)
        Util_stopClock(&updateTimeoutClock);
        
        if (pPkt->hdr.status == SUCCESS)
        {
          notify = TRUE;
        }
      }
      break;
      
    default:
      notify = TRUE;
      break;
  }

  if (notify == TRUE) //app needs to take further action
  {
    if (pGapRoles_AppCGs && pGapRoles_AppCGs->pfnPassThrough)
    {
      return (pGapRoles_AppCGs->pfnPassThrough((gapMultiRoleEvent_t *)pMsg));
    }
  }
  
  return TRUE;
    
}
コード例 #26
0
/*********************************************************************
 * @fn      gapRole_processGAPMsg
 *
 * @brief   Process an incoming task message.
 *
 * @param   pMsg - message to process
 *
 * @return  none
 */
static uint8_t gapRole_processGAPMsg(gapEventHdr_t *pMsg) {
	uint8_t notify = FALSE;   // State changed notify the app? (default no)

	switch (pMsg->opcode) {
	case GAP_DEVICE_INIT_DONE_EVENT: {
		gapDeviceInitDoneEvent_t *pPkt = (gapDeviceInitDoneEvent_t *) pMsg;
		bStatus_t stat = pPkt->hdr.status;

		if (stat == SUCCESS) {
			// Save off the generated keys
			VOID osal_snv_write(BLE_NVID_IRK, KEYLEN, gapRole_IRK);
			VOID osal_snv_write(BLE_NVID_CSRK, KEYLEN, gapRole_SRK);

			// Save off the information
			VOID memcpy(gapRole_bdAddr, pPkt->devAddr, B_ADDR_LEN);

			gapRole_peripheralState = GAPROLE_STARTED;
			gapRole_peripheralStateChangeHandler(gapRole_peripheralState);

			// Update the advertising data
			stat = GAP_UpdateAdvertisingData(selfEntity,
			TRUE, gapRole_AdvertDataLen, gapRole_AdvertData);
		}

		if (stat != SUCCESS) {
			gapRole_peripheralState = GAPROLE_ERROR;
			gapRole_peripheralStateChangeHandler(gapRole_peripheralState);
			//gapRole_abort();
		}

		notify = TRUE;
	}
		break;

	case GAP_ADV_DATA_UPDATE_DONE_EVENT: {
		gapAdvDataUpdateEvent_t *pPkt = (gapAdvDataUpdateEvent_t *) pMsg;

        if (pPkt->hdr.status == SUCCESS)
        {
          if (pPkt->adType)
          {
            // Setup the Response Data
            pPkt->hdr.status = GAP_UpdateAdvertisingData(selfEntity,
                              FALSE, gapRole_ScanRspDataLen, gapRole_ScanRspData);
          }
          else if ((gapRole_peripheralState != GAPROLE_ADVERTISING)   &&
                   (gapRole_peripheralState != GAPROLE_CONNECTED_ADV) &&
                   (gapRole_peripheralState != GAPROLE_CONNECTED ||
                    gapRole_AdvNonConnEnabled == TRUE)      &&
                   (Util_isActive(&startAdvClock) == FALSE))
          {
            // Start advertising
            gapRole_setEvent(START_ADVERTISING_EVT);
          }
          notify = FALSE;
        }else {
			// Set into Error state
			gapRole_peripheralState = GAPROLE_ERROR;
			gapRole_peripheralStateChangeHandler(gapRole_peripheralState);
			//gapRole_abort();
			notify = TRUE;
		}
	}
		break;

	case GAP_MAKE_DISCOVERABLE_DONE_EVENT:
	case GAP_END_DISCOVERABLE_DONE_EVENT: {
		gapMakeDiscoverableRspEvent_t *pPkt = (gapMakeDiscoverableRspEvent_t *) pMsg;

		if (pPkt->hdr.status == SUCCESS) {
			if (pMsg->opcode == GAP_MAKE_DISCOVERABLE_DONE_EVENT) {
				if (gapRole_peripheralState == GAPROLE_CONNECTED) {
					gapRole_peripheralState = GAPROLE_CONNECTED_ADV;
					gapRole_peripheralStateChangeHandler(gapRole_peripheralState);
				} else if (gapRole_AdvEnabled) {
					gapRole_peripheralState = GAPROLE_ADVERTISING;
					gapRole_peripheralStateChangeHandler(gapRole_peripheralState);
				} else {
					gapRole_peripheralState = GAPROLE_ADVERTISING_NONCONN;
					gapRole_peripheralStateChangeHandler(gapRole_peripheralState);
				}
			} else // GAP_END_DISCOVERABLE_DONE_EVENT
			{
				if (gapRole_AdvertOffTime != 0) //restart advertising if param is set
						{
					if ((gapRole_AdvEnabled) || (gapRole_AdvNonConnEnabled)) {
						Util_restartClock(&startAdvClock, gapRole_AdvertOffTime);
					}
				} else {
					// Since gapRole_AdvertOffTime is set to 0, the device should not
					// automatically become discoverable again after a period of time.
					// Set enabler to FALSE; device will become discoverable again when
					// this value gets set to TRUE
					if (gapRole_AdvEnabled == TRUE) {
						gapRole_AdvEnabled = FALSE;
					} else {
						gapRole_AdvNonConnEnabled = FALSE;
					}
				}

				// Update state.
				if (gapRole_peripheralState == GAPROLE_CONNECTED_ADV) {
					// In the Advertising Off period
					gapRole_peripheralState = GAPROLE_CONNECTED;
					gapRole_peripheralStateChangeHandler(gapRole_peripheralState);
				} else {
					// In the Advertising Off period
					gapRole_peripheralState = GAPROLE_WAITING;
					gapRole_peripheralStateChangeHandler(gapRole_peripheralState);
				}
			}
			notify = TRUE;
		} else if (pPkt->hdr.status == LL_STATUS_ERROR_COMMAND_DISALLOWED) //we're already advertising
		{
			notify = FALSE;
		} else {
			gapRole_peripheralState = GAPROLE_ERROR;
			gapRole_peripheralStateChangeHandler(gapRole_peripheralState);
			//gapRole_abort();
		}
	}
		break;

	case GAP_LINK_ESTABLISHED_EVENT: {
		gapEstLinkReqEvent_t *pPkt = (gapEstLinkReqEvent_t *) pMsg;

		if (pPkt->hdr.status == SUCCESS) {
			//add to database
			gapRoleInfo_Add(pPkt);

			// advertising will stop when a connection forms in the peripheral role
			if (pPkt->connRole == GAP_PROFILE_PERIPHERAL) {

				gapRole_peripheralState = GAPROLE_CONNECTED;
				gapRole_peripheralStateChangeHandler(gapRole_peripheralState);

				// Check whether update parameter request is enabled
				if (gapRole_ParamUpdateEnable == TRUE) {
						// Get the minimum time upon connection establishment before the
						// peripheral can start a connection update procedure.
						uint16_t timeout = GAP_GetParamValue(
						TGAP_CONN_PAUSE_PERIPHERAL);

						Util_restartClock(&startUpdateClock, timeout * 1000);

				}
			}
			// Notify the Bond Manager to the connection
			VOID GAPBondMgr_LinkEst(pPkt->devAddrType, pPkt->devAddr, pPkt->connectionHandle, pPkt->connRole);
		} else if (pPkt->hdr.status == bleGAPConnNotAcceptable) {
			// Set enabler to FALSE; device will become discoverable again when
			// this value gets set to TRUE
			gapRole_AdvEnabled = FALSE;

	        // Go to WAITING state, and then start advertising
			if (pPkt->connRole == GAP_PROFILE_PERIPHERAL) {
				gapRole_peripheralState = GAPROLE_WAITING;
				gapRole_peripheralStateChangeHandler(gapRole_peripheralState);
			}
		} else {
			if (pPkt->connRole == GAP_PROFILE_PERIPHERAL) {
				gapRole_peripheralState = GAPROLE_ERROR;
				gapRole_peripheralStateChangeHandler(gapRole_peripheralState);
			} else {
				gapRole_abort();
			}
		}
		notify = TRUE;
	}
		break;

	case GAP_LINK_TERMINATED_EVENT: {
		gapTerminateLinkEvent_t *pPkt = (gapTerminateLinkEvent_t *) pMsg;

		// notify bond manager
		GAPBondMgr_LinkTerm(pPkt->connectionHandle);

		// Erase connection information (maybe make this a function)
		uint8 connHandleIndex = gapRoleInfo_Find(pPkt->connectionHandle);
		multiConnInfo[connHandleIndex].gapRole_ConnectionHandle = INVALID_CONNHANDLE;
		multiConnInfo[connHandleIndex].gapRole_ConnInterval = 0;
		multiConnInfo[connHandleIndex].gapRole_ConnSlaveLatency = 0;
		multiConnInfo[connHandleIndex].gapRole_ConnTimeout = 0;

		// Cancel all connection parameter update timers (if any active)
		Util_stopClock(&startUpdateClock);
		Util_stopClock(&updateTimeoutClock);

		notify = TRUE;

		if (multiConnInfo[connHandleIndex].gapRole_ConnRole == GAP_PROFILE_PERIPHERAL) {
			// If device was advertising when connection dropped
			if (gapRole_AdvNonConnEnabled) {
				// Continue advertising.
				gapRole_peripheralState = GAPROLE_ADVERTISING_NONCONN;
				gapRole_peripheralStateChangeHandler(gapRole_peripheralState);
			}
			// Else go to WAITING state.
			else {
				if (pPkt->reason == LL_SUPERVISION_TIMEOUT_TERM) {
					gapRole_peripheralState = GAPROLE_WAITING_AFTER_TIMEOUT;
					gapRole_peripheralStateChangeHandler(gapRole_peripheralState);
				} else {
					gapRole_peripheralState = GAPROLE_WAITING;
					gapRole_peripheralStateChangeHandler(gapRole_peripheralState);
				}

				// Start advertising, if enabled.
				gapRole_setEvent(START_ADVERTISING_EVT);
			}
		}
	}
		break;

	case GAP_LINK_PARAM_UPDATE_EVENT: {
		gapLinkUpdateEvent_t *pPkt = (gapLinkUpdateEvent_t *) pMsg;

		// Cancel connection param update timeout timer (if active)
		Util_stopClock(&updateTimeoutClock);

		if (pPkt->hdr.status == SUCCESS) {
			// Store new connection parameters
//              gapRole_ConnInterval = pPkt->connInterval;
//              gapRole_ConnSlaveLatency = pPkt->connLatency;
//              gapRole_ConnTimeout = pPkt->connTimeout;

			// Make sure there's no pending connection update procedure
			if (Util_isActive(&startUpdateClock) == FALSE) {
//                // Notify the application with the new connection parameters
//                if (pGapRoles_ParamUpdateCB != NULL)
//                {
//                  (*pGapRoles_ParamUpdateCB)(gapRole_ConnInterval,
//                                             gapRole_ConnSlaveLatency,
//                                             gapRole_ConnTimeout);
//                }
			}
		}
		notify = TRUE;
	}
		break;

	case GAP_PAIRING_REQ_EVENT: {
		gapPairingReqEvent_t *pPkt = (gapPairingReqEvent_t *) pMsg;

		// Send Pairing Failed Response
		VOID GAP_TerminateAuth(pPkt->connectionHandle,
		SMP_PAIRING_FAILED_NOT_SUPPORTED);
	}
		break;

	case GAP_SLAVE_REQUESTED_SECURITY_EVENT: {
        uint16_t connHandle = ((gapSlaveSecurityReqEvent_t *)pMsg)->connectionHandle;
        uint8_t authReq = ((gapSlaveSecurityReqEvent_t *)pMsg)->authReq;

        GAPBondMgr_SlaveReqSecurity(connHandle, authReq);
	}
		break;

	case GAP_DEVICE_INFO_EVENT:
	case GAP_DEVICE_DISCOVERY_EVENT:
		notify = TRUE;
		break;

	default:
		notify = FALSE;
		break;
	}

	if (notify == TRUE) //app needs to take further action
	{
		if (pGapRoles_AppCGs && pGapRoles_AppCGs->pfnPassThrough) {
			return (pGapRoles_AppCGs->pfnPassThrough((gapMultiRoleEvent_t *) pMsg));
		}
	}

	return TRUE;

}
コード例 #27
0
// 以下1-9每1秒执行一次
static void Pollint1Sec(void)
{
    switch(r_pollint._100msCount)
    {
        case 1:
			#if 0
			{
				uint8_t smbBuf[3];
				uartWriteDebug("Test=", 5);
				SMB_Read(RELATIVE_SOC, smbBuf, 1);
				uartWriteDebug(smbBuf, 1);
				SMB_Read(ABSOLUTE_SOC, smbBuf, 1);
				uartWriteDebug(smbBuf, 1);
				SMB_Read(BATTERY_STATUS, smbBuf, 2);
				uartWriteDebug(smbBuf, 2);
				SMB_Read(BATTERY_MODE, smbBuf, 2);
				uartWriteDebug(smbBuf, 2);
			}
			#endif
            break;
        case 2:
			if (systemState.delayPowerOffTime)
			{
				if (--systemState.delayPowerOffTime == 0)
				{
					systemState.powerOffFlag = 0;
					//开启外部中断
					KEY_EnableIRQ();

					//关掉时钟
					uartWriteDebug("tmout", 5);
					Util_stopClock(&periodicClock_10ms);
				}
			}
			else if (systemState.powerOffFlag!=1 || systemState.keyUpFlag==1)
			{
				/* 
				在长按关机时,还没松开前默认是关机的所以不能显示图标
				
				在长按开机时,以为短按触发中断系统开启,但此时不是开机事件,
				所以也不能显示图标
				*/
				
				systemState.lowBatteryFlag = userAppShowCharge();

				if (2 == systemState.lowBatteryFlag)
				{
					OLED_ShowString(40, 0, "           ");
					OLED_ShowString(40, 0, "No battery ");  
				}
				else if (1 == systemState.lowBatteryFlag)
				{
					// 没电 图标闪烁警告
				}
				else
				{
					//正常显示
				}
				//OLED_testShowGengeeRoll(3);
			}
            break;
        case 3:
			if(CHARGING == chargeStateRead())
			{
				systemState.keyUpFlag=1;
			}
            break;
        default:
            break;
    }
}
コード例 #28
0
/*********************************************************************
 * @fn      RunningSensor_processStateChangeEvt
 *
 * @brief   Notification from the profile of a state change.
 *
 * @param   newState - new state
 *
 * @return  none
 */
static void RunningSensor_processStateChangeEvt(gaprole_States_t newState)
{
  // If connected
  if (newState == GAPROLE_CONNECTED)
  {
    // Get the connection handle.
    GAPRole_GetParameter(GAPROLE_CONNHANDLE, &gapConnHandle);

    // Begin delay for service discovery.
    Util_startClock(&paramUpdateClock);
  }
  // If disconnected
  else if (gapProfileState == GAPROLE_CONNECTED &&
           newState != GAPROLE_CONNECTED)
  {
    uint8_t advState = TRUE;
    uint8_t bondCount = 0;

    // Stop periodic measurement.
    Util_stopClock(&periodicClock);

    // Get the bond count.
    GAPBondMgr_GetParameter(GAPBOND_BOND_COUNT, &bondCount);
    
    // If enabled and previously bonded, turn on white list if not already done.
    if(USING_WHITE_LIST && sensorUsingWhiteList == FALSE && bondCount > 0)
    {
      uint8_t value = GAP_FILTER_POLICY_WHITE;

      GAPRole_SetParameter(GAPROLE_ADV_FILTER_POLICY, sizeof(uint8_t), &value);

      sensorUsingWhiteList = TRUE;
    }
    
    // If waiting after a connection timeout
    if (newState == GAPROLE_WAITING_AFTER_TIMEOUT)
    {
      // Link loss timeout-- use fast advertising.
      GAP_SetParamValue(TGAP_GEN_DISC_ADV_INT_MIN, DEFAULT_FAST_ADV_INTERVAL);
      GAP_SetParamValue(TGAP_GEN_DISC_ADV_INT_MAX, DEFAULT_FAST_ADV_INTERVAL);
      GAP_SetParamValue(TGAP_GEN_DISC_ADV_MIN, DEFAULT_WHITE_LIST_ADV_DURATION);
    }
    else
    {
      // Use slow advertising.
      GAP_SetParamValue(TGAP_GEN_DISC_ADV_INT_MIN, DEFAULT_SLOW_ADV_INTERVAL);
      GAP_SetParamValue(TGAP_GEN_DISC_ADV_INT_MAX, DEFAULT_SLOW_ADV_INTERVAL);
      GAP_SetParamValue(TGAP_GEN_DISC_ADV_MIN, DEFAULT_WHITE_LIST_ADV_DURATION);
    }

    // Enable advertising.
    GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8_t), &advState);
  }
  // If advertising stopped
  else if (gapProfileState == GAPROLE_ADVERTISING &&
            newState == GAPROLE_WAITING)
  {
    uint8_t whiteListUsed = FALSE;

    // If white list is in use, turn off white list filtering to allow general 
    // access.
    if (sensorUsingWhiteList == TRUE)
    {
      uint8_t value = GAP_FILTER_POLICY_ALL;

      GAPRole_SetParameter(GAPROLE_ADV_FILTER_POLICY, sizeof(uint8_t), &value);

      whiteListUsed = TRUE;

      sensorUsingWhiteList = FALSE;
    }

    // If advertising stopped by user
    if (sensorAdvCancelled)
    {
      sensorAdvCancelled = FALSE;
    }
    // If fast advertising was interrupted to cancel white list
    else if (((!USING_WHITE_LIST) || whiteListUsed) &&
              (GAP_GetParamValue(TGAP_GEN_DISC_ADV_INT_MIN) == DEFAULT_FAST_ADV_INTERVAL))
    {
      uint8_t advState = TRUE;

      GAP_SetParamValue(TGAP_GEN_DISC_ADV_INT_MIN, DEFAULT_FAST_ADV_INTERVAL);
      GAP_SetParamValue(TGAP_GEN_DISC_ADV_INT_MAX, DEFAULT_FAST_ADV_INTERVAL);
      GAP_SetParamValue(TGAP_GEN_DISC_ADV_MIN, DEFAULT_FAST_ADV_DURATION);
      GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8_t), &advState);
    }
    // If fast advertising or was using white list switch to slow advertising.
    else if (((!USING_WHITE_LIST) || whiteListUsed) ||
              (GAP_GetParamValue(TGAP_GEN_DISC_ADV_INT_MIN) == DEFAULT_FAST_ADV_INTERVAL))
    {
      uint8_t advState = TRUE;

      GAP_SetParamValue(TGAP_GEN_DISC_ADV_INT_MIN, DEFAULT_SLOW_ADV_INTERVAL);
      GAP_SetParamValue(TGAP_GEN_DISC_ADV_INT_MAX, DEFAULT_SLOW_ADV_INTERVAL);
      GAP_SetParamValue(TGAP_GEN_DISC_ADV_MIN, DEFAULT_SLOW_ADV_DURATION);
      GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8_t), &advState);
    }
  }
  // If started
  else if (newState == GAPROLE_STARTED)
  {
    // Set the system ID from the bd addr.
    uint8_t systemId[DEVINFO_SYSTEM_ID_LEN];
    
    GAPRole_GetParameter(GAPROLE_BD_ADDR, systemId);

    // Shift three bytes up.
    systemId[7] = systemId[5];
    systemId[6] = systemId[4];
    systemId[5] = systemId[3];

    // Set middle bytes to zero.
    systemId[4] = 0;
    systemId[3] = 0;

    DevInfo_SetParameter(DEVINFO_SYSTEM_ID, DEVINFO_SYSTEM_ID_LEN, systemId);
  }

  // Update state.
  gapProfileState = newState;
}