예제 #1
0
파일: fan.c 프로젝트: drme/ble-remote
uint16 FanProcessEvent(uint8 taskId, uint16 events)
{
	if (events & SYS_EVENT_MSG)
	{
		uint8* message = NULL;

		if ((message = osal_msg_receive(fanTaskId)) != NULL)
		{
			FanProcessOSALMessage((osal_event_hdr_t*)message);
			osal_msg_deallocate(message);
		}

		return (events ^ SYS_EVENT_MSG);
	}

	if (events & FAN_START_DEVICE_EVT)
	{
		GAPRole_StartDevice(&fanPeripheralCallBacks);
		GAPBondMgr_Register(&fanBondManagerCallBacks);
	
		return (events ^ FAN_START_DEVICE_EVT);
	}

	if (events & FAN_UPDATE_STATUS_EVT)
	{
		FanUpdateStatus();
	
		return (events ^ FAN_UPDATE_STATUS_EVT);
	}

	return 0;
};
예제 #2
0
/*********************************************************************
 * @fn      SimpleBLEPeripheral_ProcessEvent
 *
 * @brief   Simple BLE Peripheral Application Task event processor.  This function
 *          is called to process all events for the task.  Events
 *          include timers, messages and any other user defined events.
 *
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events - events to process.  This is a bit map and can
 *                   contain more than one event.
 *
 * @return  events not processed
 */
uint16 SimpleBLEPeripheral_ProcessEvent( uint8 task_id, uint16 events )
{
  //tasksArr[] ÊÇ11¸öTaskµÄ×îºóÒ»¸ö£¬ÓÉOSAL ϵͳ½øÐе÷¶È¡£ÓÐʱ¼äÀ´ÁË£¬Óø÷½·¨´¦Àí¡£³õʼ»¯OSAL_SimpleBLEperipheal

  VOID task_id; // OSAL required parameter that isn't used in this function

  if ( events & SYS_EVENT_MSG )
  {
    uint8 *pMsg;

    if ( (pMsg = osal_msg_receive( simpleBLEPeripheral_TaskID )) != NULL )
    {
      simpleBLEPeripheral_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );

      // Release the OSAL message
      VOID osal_msg_deallocate( pMsg );
    }

    // return unprocessed events
    return (events ^ SYS_EVENT_MSG);
  }

  if ( events & SBP_START_DEVICE_EVT )
  {
    // Start the Device   Õâ¸öÊÇÉ豸ÓÐ״̬±ä»¯²Å»áµ÷ÓõĻص÷º¯Êý
    VOID GAPRole_StartDevice( &simpleBLEPeripheral_PeripheralCBs );

    // Start Bond Manager
    VOID GAPBondMgr_Register( &simpleBLEPeripheral_BondMgrCBs );
    
    // Set timer for first periodic event
    //init LED
    PWM_init();
    init_QI_Switch(1);
    //dataChange(1,0);
    
    //osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD );
    //LedChange();
    return ( events ^ SBP_START_DEVICE_EVT );
  }
  
 if ( events & SBP_PERIODIC_EVT )
  {
    //osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD );
    //Ö´ÐеƹâchangeµÄº¯Êý
    
    if(P1_1 == 1){
        //HalLcdWriteString("HEIGH",HAL_LCD_LINE_4);
    }else{
        //HalLcdWriteString("LOW",HAL_LCD_LINE_4);
    }

    LedChange();
    return (events ^ SBP_PERIODIC_EVT);
  }

  // Discard unknown events
  return 0;
}
예제 #3
0
/*********************************************************************
 * @fn      TimeApp_ProcessEvent
 *
 * @brief   Time App Application Task event processor.  This function
 *          is called to process all events for the task.  Events
 *          include timers, messages and any other user defined events.
 *
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events - events to process.  This is a bit map and can
 *                   contain more than one event.
 *
 * @return  events not processed
 */
uint16 TimeApp_ProcessEvent( uint8 task_id, uint16 events )
{
  
  VOID task_id; // OSAL required parameter that isn't used in this function
  
  if ( events & SYS_EVENT_MSG )
  {
    uint8 *pMsg;

    if ( (pMsg = osal_msg_receive( timeAppTaskId )) != NULL )
    {
      timeApp_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );

      // Release the OSAL message
      VOID osal_msg_deallocate( pMsg );
    }

    // return unprocessed events
    return ( events ^ SYS_EVENT_MSG );
  }

  if ( events & START_DEVICE_EVT )
  {
    // Start the Device
    VOID GAPRole_StartDevice( &timeAppPeripheralCB );

    // Register with bond manager after starting device
    GAPBondMgr_Register( (gapBondCBs_t *) &timeAppBondCB );

    return ( events ^ START_DEVICE_EVT );
  }

  if ( events & START_DISCOVERY_EVT )
  {
    if ( timeAppPairingStarted )
    {
      // Postpone discovery until pairing completes
      timeAppDiscPostponed = TRUE;
    }
    else
    {
      timeAppDiscState = timeAppDiscStart();
    }  
    return ( events ^ START_DISCOVERY_EVT );
  }

  if ( events & CLOCK_UPDATE_EVT )
  {
    timeAppClockDisplay();

    // Restart clock tick timer
    osal_start_timerEx( timeAppTaskId, CLOCK_UPDATE_EVT, DEFAULT_CLOCK_UPDATE_PERIOD );

    return ( events ^ CLOCK_UPDATE_EVT );
  }
     
  // Discard unknown events
  return 0;
}
예제 #4
0
/*********************************************************************
 * @fn      SimpleBLEPeripheral_ProcessEvent
 *
 * @brief   Simple BLE Peripheral Application Task event processor.  This function
 *          is called to process all events for the task.  Events
 *          include timers, messages and any other user defined events.
 *
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events - events to process.  This is a bit map and can
 *                   contain more than one event.
 *
 * @return  events not processed
 */
uint16 SimpleBLEPeripheral_ProcessEvent( uint8 task_id, uint16 events )
{

  VOID task_id; // OSAL required parameter that isn't used in this function

  if ( events & SYS_EVENT_MSG )
  {
    uint8 *pMsg;

    if ( (pMsg = osal_msg_receive( simpleBLEPeripheral_TaskID )) != NULL )
    {
      simpleBLEPeripheral_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );

      // Release the OSAL message
      VOID osal_msg_deallocate( pMsg );
    }

    // return unprocessed events
    return (events ^ SYS_EVENT_MSG);
  }

  if ( events & SBP_START_DEVICE_EVT )
  {
    P0_7 = 0;  //防止继电器跳变,初始化为高
    P0DIR |= BV(7); //设置为输出
    P0SEL &=~BV(7); //设置该脚为普通GPIO
    //HCI_EXT_SetTxPowerCmd (HCI_EXT_TX_POWER_MINUS_23_DBM);
    // Start the Device
    VOID GAPRole_StartDevice( &simpleBLEPeripheral_PeripheralCBs );

    // Start Bond Manager
    VOID GAPBondMgr_Register( &simpleBLEPeripheral_BondMgrCBs );

    return ( events ^ SBP_START_DEVICE_EVT );
  }

  if ( events & SBP_PERIODIC_EVT )
  {
    //成功写入后,重启从机
    HAL_SYSTEM_RESET();
    return (events ^ SBP_PERIODIC_EVT);
  }

#if defined ( PLUS_BROADCASTER )
  if ( events & SBP_ADV_IN_CONNECTION_EVT )
  {
    uint8 turnOnAdv = TRUE;
    // Turn on advertising while in a connection
    GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &turnOnAdv );

    return (events ^ SBP_ADV_IN_CONNECTION_EVT);
  }
#endif // PLUS_BROADCASTER

  // Discard unknown events
  return 0;
}
예제 #5
0
/*********************************************************************
 * @fn      PIRSensor_ProcessEvent
 *
 * @brief   Simple BLE Peripheral Application Task event processor.  This function
 *          is called to process all events for the task.  Events
 *          include timers, messages and any other user defined events.
 *
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events - events to process.  This is a bit map and can
 *                   contain more than one event.
 *
 * @return  events not processed
 */
uint16 PIRSensor_ProcessEvent( uint8 task_id, uint16 events )
{

  VOID task_id; // OSAL required parameter that isn't used in this function

  if ( events & SYS_EVENT_MSG )
  {
    uint8 *pMsg;

    if ( (pMsg = osal_msg_receive( PIRSensor_TaskID )) != NULL )
    {
      PIRSensor_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );

      // Release the OSAL message
      VOID osal_msg_deallocate( pMsg );
    }

    // return unprocessed events
    return (events ^ SYS_EVENT_MSG);
  }

  if ( events & SBP_START_DEVICE_EVT )
  {
    // Start the Device
    VOID GAPRole_StartDevice( &PIRSensor_PeripheralCBs );

    // Start Bond Manager
    VOID GAPBondMgr_Register( &PIRSensor_BondMgrCBs );

    return ( events ^ SBP_START_DEVICE_EVT );
  }

  //////////////////////////
  //         AIN          //
  //////////////////////////
  if ( events & SBP_READ_AIN_EVT )
  {
    if(ainEnabled)
    {
      uint16 ainData;
      ainData = readAdcData(HAL_ADC_CHANNEL_6);
      Ain_SetParameter(SENSOR_DATA, AIN_DATA_LEN, &ainData);
      
      osal_start_timerEx( PIRSensor_TaskID, SBP_READ_AIN_EVT, sensorAinPeriod );
    }
    else
    {
      resetCharacteristicValue( AIN_SERV_UUID, SENSOR_DATA, 0, AIN_DATA_LEN);
      resetCharacteristicValue( AIN_SERV_UUID, SENSOR_CONF, ST_CFG_SENSOR_DISABLE, sizeof ( uint8 ));
    }

    return (events ^ SBP_READ_AIN_EVT);
  }

  // Discard unknown events
  return 0;
}
예제 #6
0
/*********************************************************************
 * @fn      SoftCmd_ProcessEvent
 *
 * @brief   Soft Command Application Task event processor.  This function
 *          is called to process all events for the task.  Events
 *          include timers, messages and any other user defined events.
 *
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events - events to process.  This is a bit map and can
 *                   contain more than one event.
 *
 * @return  events not processed
 */
uint16 SoftCmd_ProcessEvent( uint8 task_id, uint16 events )
{
  
  VOID task_id; // OSAL required parameter that isn't used in this function
  
  if ( events & SYS_EVENT_MSG )
  {
    uint8 *pMsg;

    if ( (pMsg = osal_msg_receive( softCmdTaskId )) != NULL )
    {
      softCmd_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );

      // Release the OSAL message
      VOID osal_msg_deallocate( pMsg );
    }

    // return unprocessed events
    return (events ^ SYS_EVENT_MSG);
  }

  if ( events & START_DEVICE_EVT )
  {
    // Start the Device
    VOID GAPRole_StartDevice( &softCmdPeripheralCBs );

    // Register with bond manager after starting device
    GAPBondMgr_Register( (gapBondCBs_t *) &softCmdBondCB );
    
    return ( events ^ START_DEVICE_EVT );
  }

  if ( events & START_DISCOVERY_EVT )
  {
    if ( softCmdPairingStarted )
    {
      // Postpone discovery until pairing completes
      softCmdDiscPostponed = TRUE;
    }
    else
    {
      softCmdDiscState = softCmdDiscStart();
    }  
    return ( events ^ START_DISCOVERY_EVT );
  }

  if ( events & BATT_PERIODIC_EVT )
  {
    // Perform periodic battery task
    softCmdBattPeriodicTask();
    
    return (events ^ BATT_PERIODIC_EVT);
  }  
  
  // Discard unknown events
  return 0;
}
예제 #7
0
/*********************************************************************
 * @fn      SimpleBLECentral_ProcessEvent
 *
 * @brief   Simple BLE Central Application Task event processor.  This function
 *          is called to process all events for the task.  Events
 *          include timers, messages and any other user defined events.
 *
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events - events to process.  This is a bit map and can
 *                   contain more than one event.
 *
 * @return  events not processed
 */
uint16 SimpleBLECentral_ProcessEvent( uint8 task_id, uint16 events )
{
  
  VOID task_id; // OSAL required parameter that isn't used in this function
  
  if ( events & SYS_EVENT_MSG )
  {
    uint8 *pMsg;

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

      // Release the OSAL message
      VOID osal_msg_deallocate( pMsg );
    }

    // return unprocessed events
    return (events ^ SYS_EVENT_MSG);
  }

  if ( events & START_DEVICE_EVT )
  {
    // Start the Device
    VOID GAPCentralRole_StartDevice( (gapCentralRoleCB_t *) &simpleBLERoleCB );

    // Register with bond manager after starting device
    GAPBondMgr_Register( (gapBondCBs_t *) &simpleBLEBondCB );

    return ( events ^ START_DEVICE_EVT );
  }

  if ( events & START_DISCOVERY_EVT )
  {
    simpleBLECentralStartDiscovery( );
    
    return ( events ^ START_DISCOVERY_EVT );
  }
  
  if ( events & SBP_PERIODIC_EVT )
  {
    // Restart timer
    if ( SBP_PERIODIC_EVT_PERIOD && simpleBLEState == BLE_STATE_CONNECTED )
    {
      osal_start_timerEx( simpleBLETaskId, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD );
    }

    // Perform periodic application task
    performPeriodicTask();

    return (events ^ SBP_PERIODIC_EVT);
  }
  
  // Discard unknown events
  return 0;
}
예제 #8
0
/*********************************************************************
 * @fn      Biscuit_ProcessEvent
 *
 * @brief   Simple BLE Peripheral Application Task event processor.  This function
 *          is called to process all events for the task.  Events
 *          include timers, messages and any other user defined events.
 *
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events - events to process.  This is a bit map and can
 *                   contain more than one event.
 *
 * @return  events not processed
 */
uint16 Biscuit_ProcessEvent( uint8 task_id, uint16 events )
{

  VOID task_id; // OSAL required parameter that isn't used in this function

  if ( events & SYS_EVENT_MSG )
  {
    uint8 *pMsg;

    if ( (pMsg = osal_msg_receive( biscuit_TaskID )) != NULL )
    {
      biscuit_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );

      // Release the OSAL message
      VOID osal_msg_deallocate( pMsg );
    }

    // return unprocessed events
    return (events ^ SYS_EVENT_MSG);
  }

  if ( events & SBP_START_DEVICE_EVT )
  {
    // Start the Device
    VOID GAPRole_StartDevice( &biscuit_PeripheralCBs );

    // Start Bond Manager
    VOID GAPBondMgr_Register( &biscuit_BondMgrCBs );

    // Set timer for first periodic event
    osal_start_timerEx( biscuit_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD );

    return ( events ^ SBP_START_DEVICE_EVT );
  }

  if ( events & SBP_PERIODIC_EVT )
  {
    // Restart timer
    if ( SBP_PERIODIC_EVT_PERIOD )
    {
      osal_start_timerEx( biscuit_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD );
    }

    // Perform periodic application task
    performPeriodicTask();

    return (events ^ SBP_PERIODIC_EVT);
  }

  // Discard unknown events
  return 0;
}
예제 #9
0
/*********************************************************************
 * @fn      HeartRate_ProcessEvent
 *
 * @brief   Heart Rate Application Task event processor.  This function
 *          is called to process all events for the task.  Events
 *          include timers, messages and any other user defined events.
 *
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events - events to process.  This is a bit map and can
 *                   contain more than one event.
 *
 * @return  events not processed
 */
uint16 HeartRate_ProcessEvent( uint8 task_id, uint16 events )
{
  
  VOID task_id; // OSAL required parameter that isn't used in this function
  
  if ( events & SYS_EVENT_MSG )
  {
    uint8 *pMsg;

    if ( (pMsg = osal_msg_receive( heartRate_TaskID )) != NULL )
    {
      heartRate_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );

      // Release the OSAL message
      VOID osal_msg_deallocate( pMsg );
    }

    // return unprocessed events
    return (events ^ SYS_EVENT_MSG);
  }

  if ( events & START_DEVICE_EVT )
  {
    // Start the Device
    VOID GAPRole_StartDevice( &heartRatePeripheralCB );

    // Register with bond manager after starting device
    GAPBondMgr_Register( (gapBondCBs_t *) &heartRateBondCB );
    
    return ( events ^ START_DEVICE_EVT );
  }

  if ( events & HEART_PERIODIC_EVT )
  {
    // Perform periodic heart rate task
    heartRatePeriodicTask();
    
    return (events ^ HEART_PERIODIC_EVT);
  }  

  if ( events & BATT_PERIODIC_EVT )
  {
    // Perform periodic battery task
    heartRateBattPeriodicTask();
    
    return (events ^ BATT_PERIODIC_EVT);
  }  
  
  // Discard unknown events
  return 0;
}
예제 #10
0
/*---------------------------------------------------------------------------
* Application event processor.  This function
* is called to process all events for the task. Events
* include timers, messages and any other user defined events.
* - task_id: The OSAL assigned task ID.
* - events: Events to process.  This is a bit map and can contain more 
*           than one event.
*-------------------------------------------------------------------------*/
uint16 PMD_processEvent( uint8 taskId, uint16 events )
{
  
  if ( events & START_STREAMING)
  {
    attHandleValueNoti_t nData2;
    nData2.len = 20;
    nData2.handle = 20;
    getNameWithAddressInfo(nData2);
    
    GATT_Notification( 0, &nData2, FALSE );

    return (events ^ START_STREAMING);
  }
  
  if ( events & SYS_EVENT_MSG )
  {
    uint8 *pMsg;

    if ( (pMsg = osal_msg_receive( pmd.taskId )) != NULL )
    {
      processOSALMsg( (osal_event_hdr_t *)pMsg );

      VOID osal_msg_deallocate( pMsg );
    }

    return (events ^ SYS_EVENT_MSG);
  }

  if ( events & PMD_START_DEVICE_EVT )
  {
    // Start the Device
    VOID GAPRole_StartDevice( &peripheralRoleCallbacks );

    // Start Bond Manager
    VOID GAPBondMgr_Register( &bondMgrCallbacks );       

    
    // Flash red LED twice
    //cbLED_flash(cbLED_RED, 2, 250, 500);
    PMD_INT_init();

    return ( events ^ PMD_START_DEVICE_EVT );    
  }


  // Discard unknown events
  return 0;
}
예제 #11
0
/*********************************************************************
 * @fn      SimpleBLECentral_ProcessEvent
 *
 * @brief   Simple BLE Central Application Task event processor.  This function
 *          is called to process all events for the task.  Events
 *          include timers, messages and any other user defined events.
 *
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events - events to process.  This is a bit map and can
 *                   contain more than one event.
 *
 * @return  events not processed
 */
uint16 SimpleBLECentral_ProcessEvent( uint8 task_id, uint16 events )
{
  
  VOID task_id; // OSAL required parameter that isn't used in this function
  
  if ( events & SYS_EVENT_MSG )
  {
    uint8 *pMsg;

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

      // Release the OSAL message
      VOID osal_msg_deallocate( pMsg );
    }

    // return unprocessed events
    return (events ^ SYS_EVENT_MSG);
  }

  if ( events & START_DEVICE_EVT )
  {
    // Start the Device
    VOID GAPCentralRole_StartDevice( (gapCentralRoleCB_t *) &simpleBLERoleCB );

    // Register with bond manager after starting device
    GAPBondMgr_Register( (gapBondCBs_t *) &simpleBLEBondCB );

    return ( events ^ START_DEVICE_EVT );
  }

  if ( events & START_DISCOVERY_EVT )
  {
    controlBLECentralStartDiscovery( );
    
    return ( events ^ START_DISCOVERY_EVT );
  }
  
  // Discard unknown events
  return 0;
}
예제 #12
0
파일: hidapp.c 프로젝트: AubrCool/BLE
/*******************************************************************************
 *
 * @fn      hidappInit
 *
 * @brief   This is the Sample Application task initialization called by OSAL.
 *
 * @param   taskId - task ID assigned after it was added in the OSAL task queue
 *
 * @return  none
 */
void Hidapp_Init( uint8 taskId )
{
  // save task ID assigned by OSAL
  hidappTaskId = taskId;

  // Setup Central Profile
  {
    uint8 scanRes = DEFAULT_MAX_SCAN_RES;
    VOID GAPCentralRole_SetParameter( GAPCENTRALROLE_MAX_SCAN_RES, sizeof( uint8 ), &scanRes );
  }

  // Setup GAP
  {
    VOID GAP_SetParamValue( TGAP_GEN_DISC_SCAN, DEFAULT_SCAN_DURATION );
    VOID GAP_SetParamValue( TGAP_LIM_DISC_SCAN, DEFAULT_SCAN_DURATION );

    // Set scanning interval, 48 = 30ms
    VOID GAP_SetParamValue( TGAP_LIM_DISC_SCAN_INT, 48 );

    // Set scannng window, 48 = 30ms
    VOID GAP_SetParamValue( TGAP_LIM_DISC_SCAN_WIND, 48 );
  }

  // Setup the GAP Bond Manager
  {
    uint32 passkey = DEFAULT_PASSCODE;
    uint8 pairMode = GAPBOND_PAIRING_MODE_WAIT_FOR_REQ;
    uint8 mitm = DEFAULT_MITM_MODE;
    uint8 ioCap = DEFAULT_IO_CAPABILITIES;
    uint8 bonding = DEFAULT_BONDING_MODE;
    uint8 autoSync = TRUE;
    uint8 bondFailAction = GAPBOND_FAIL_TERMINATE_ERASE_BONDS;

    VOID GAPBondMgr_SetParameter( GAPBOND_DEFAULT_PASSCODE, sizeof( uint32 ), &passkey );
    VOID GAPBondMgr_SetParameter( GAPBOND_PAIRING_MODE, sizeof( uint8 ), &pairMode );
    VOID GAPBondMgr_SetParameter( GAPBOND_MITM_PROTECTION, sizeof( uint8 ), &mitm );
    VOID GAPBondMgr_SetParameter( GAPBOND_IO_CAPABILITIES, sizeof( uint8 ), &ioCap );
    VOID GAPBondMgr_SetParameter( GAPBOND_BONDING_ENABLED, sizeof( uint8 ), &bonding );
    VOID GAPBondMgr_SetParameter( GAPBOND_AUTO_SYNC_WL, sizeof( uint8 ), &autoSync );
    VOID GAPBondMgr_SetParameter( GAPBOND_BOND_FAIL_ACTION, sizeof( uint8 ), &bondFailAction );
  }

  // USB suspend entry/exit hook function setup
  pFnSuspendEnterHook = hidappSuspendEnter;
  pFnSuspendExitHook = hidappSuspendExit;

  // Initialize GATT Client
  VOID GATT_InitClient();

  // Register to receive notifications
  GATT_RegisterForInd( hidappTaskId );

  // Set connection parameters:
  {
    uint16 connectionInterval = APP_CONN_INTERVAL;
    uint16 slaveLatency = APP_SLAVE_LATENCY;
    uint16 timeout = APP_CONN_TIMEOUT;

    VOID GAP_SetParamValue( TGAP_CONN_EST_INT_MIN, connectionInterval );
    VOID GAP_SetParamValue( TGAP_CONN_EST_INT_MAX, connectionInterval );
    VOID GAP_SetParamValue( TGAP_CONN_EST_LATENCY, slaveLatency );
    VOID GAP_SetParamValue( TGAP_CONN_EST_SUPERV_TIMEOUT, timeout );
  }

  // Register callbacks with the GAP Bond Manager.
  GAPBondMgr_Register( &gapBondCBs );

  //HalKeyConfig(HAL_KEY_INTERRUPT_ENABLE, hidappHandleKeys);
  RegisterForKeys( hidappTaskId );

  // set up continued initialization from within OSAL task loop
  VOID osal_start_timerEx( taskId, HIDAPP_EVT_START, 100 );

  // Clear remote data
  hidappEraseHandles();

  VOID HCI_EXT_HaltDuringRfCmd( HCI_EXT_HALT_DURING_RF_DISABLE );
}
/*********************************************************************
 * @fn      glucCollCentral_Init
 *
 * @brief   Initialization function for the Glucose Collector App Task.
 *          This is called during initialization and should contain
 *          any application specific initialization (ie. hardware
 *          initialization/setup, table initialization, power up
 *          notification).
 *
 *
 * @return  none
 */
static void glucCollCentral_Init()
{
	// ******************************************************************
  // 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);

  // Set device's Sleep Clock Accuracy
  //HCI_EXT_SetSCACmd(40);
  
  // Save the taskId
  glucCollTaskId = selfEntity;

  // Create an RTOS queue for message from profile to be sent to app.
  appMsgQueue = Util_constructQueue(&appMsg);

  Board_openLCD();

  // Create clock objects for discovery and procedure timeout
  Util_constructClock(&discoveryClock, glucCollCentral_clockHandler,
                      DEFAULT_SVC_DISCOVERY_DELAY, 0, false, 
                      GLUCOLL_START_DISCOVERY_EVT);

  Util_constructClock(&procTimeoutClock, glucCollCentral_clockHandler,
                      GLUCOSE_PROCEDURE_TIMEOUT, 0, false, 
                      GLUCOLL_PROCEDURE_TIMEOUT_EVT);

  // Setup Central Profile
  {
    uint8_t scanRes = DEFAULT_MAX_SCAN_RES;
    
    GAPCentralRole_SetParameter (GAPCENTRALROLE_MAX_SCAN_RES, sizeof(uint8_t), 
                                 &scanRes);
  }
  
  // Setup GAP
  GAP_SetParamValue(TGAP_GEN_DISC_SCAN, DEFAULT_SCAN_DURATION);
  GAP_SetParamValue(TGAP_LIM_DISC_SCAN, DEFAULT_SCAN_DURATION);
  GGS_SetParameter(GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, 
                   (uint8_t *)glucCollDeviceName);

  // Setup the GAP Bond Manager
  {
    uint32_t passkey = DEFAULT_PASSCODE;
    uint8_t pairMode = DEFAULT_PAIRING_MODE;
    uint8_t mitm = DEFAULT_MITM_MODE;
    uint8_t ioCap = DEFAULT_IO_CAPABILITIES;
    uint8_t bonding = DEFAULT_BONDING_MODE;
    
    GAPBondMgr_SetParameter(GAPBOND_DEFAULT_PASSCODE, sizeof(uint32_t), &passkey);
    GAPBondMgr_SetParameter(GAPBOND_PAIRING_MODE, sizeof(uint8_t), &pairMode);
    GAPBondMgr_SetParameter(GAPBOND_MITM_PROTECTION, sizeof(uint8_t), &mitm);
    GAPBondMgr_SetParameter(GAPBOND_IO_CAPABILITIES, sizeof(uint8_t), &ioCap);
    GAPBondMgr_SetParameter(GAPBOND_BONDING_ENABLED, sizeof(uint8_t), &bonding);
  }  

  // Initialize GATT Client
  VOID GATT_InitClient();

  // Register to receive incoming ATT Indications/Notifications
  GATT_RegisterForInd(glucCollTaskId);

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

  // Register for all key events - This app will handle all key events
  Board_initKeys(glucCollCentral_keyChangeHandler);

  // Register with bond manager after starting device
  GAPBondMgr_Register((gapBondCBs_t *)&glucCollBondCB);  

  // Start the Device
  VOID GAPCentralRole_StartDevice((gapCentralRoleCB_t *)&glucCollRoleCB);
}
예제 #14
0
/*********************************************************************
 * @fn      GlucColl_ProcessEvent
 *
 * @brief   Glucose Collector Application Task event processor.  This function
 *          is called to process all events for the task.  Events
 *          include timers, messages and any other user defined events.
 *
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events - events to process.  This is a bit map and can
 *                   contain more than one event.
 *
 * @return  events not processed
 */
uint16 GlucColl_ProcessEvent( uint8 task_id, uint16 events )
{
  
  VOID task_id; // OSAL required parameter that isn't used in this function
  
  if ( events & SYS_EVENT_MSG )
  {
    uint8 *pMsg;

    if ( (pMsg = osal_msg_receive( glucCollTaskId )) != NULL )
    {
      glucCollCentral_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );

      // Release the OSAL message
      VOID osal_msg_deallocate( pMsg );
    }

    // return unprocessed events
    return (events ^ SYS_EVENT_MSG);
  }

  if ( events & PROCEDURE_TIMEOUT_EVT )
  {
    if ( glucCollState == BLE_STATE_CONNECTED )
    {
      // disconnect
      glucCollState = BLE_STATE_DISCONNECTING;

      GAPCentralRole_TerminateLink( glucCollConnHandle );
      
      LCD_WRITE_STRING( "Timeout", HAL_LCD_LINE_1 ); 
      LCD_WRITE_STRING( "", HAL_LCD_LINE_2 );
      LCD_WRITE_STRING( "", HAL_LCD_LINE_3 );
    }

    // return unprocessed events
    return ( events ^ PROCEDURE_TIMEOUT_EVT );
  }

  if ( events & START_DEVICE_EVT )
  {
    // Start the Device
    VOID GAPCentralRole_StartDevice( (gapCentralRoleCB_t *) &glucCollRoleCB );

    // Register with bond manager after starting device
    GAPBondMgr_Register( (gapBondCBs_t *) &glucCollBondCB );

    return ( events ^ START_DEVICE_EVT );
  }

  if ( events & START_DISCOVERY_EVT )
  {
    if ( glucCollPairingStarted )
    {
      // Postpone discovery until pairing completes
      glucCollDiscPostponed = TRUE;
    }
    else
    {
      glucCollCentralStartDiscovery( );
    }  
    return ( events ^ START_DISCOVERY_EVT );
  }
  
  // Discard unknown events
  return 0;
}
예제 #15
0
/*********************************************************************
 * @fn      Thermometer_ProcessEvent
 *
 * @brief   Thermometer Application Task event processor.  This function
 *          is called to process all events for the task.  Events
 *          include timers, messages and any other user defined events.
 *
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events - events to process.  This is a bit map and can
 *                   contain more than one event.
 *
 * @return  events not processed
 */
uint16 Thermometer_ProcessEvent( uint8 task_id, uint16 events )
{

    VOID task_id; // OSAL required parameter that isn't used in this function
    uint8 notify_interval;
    int32 n32;

    if ( events & SYS_EVENT_MSG )
    {
        uint8 *pMsg;

        if ( (pMsg = osal_msg_receive( thermometerTaskId )) != NULL )
        {
            thermometer_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );

            // Release the OSAL message
            VOID osal_msg_deallocate( pMsg );
        }

        // return unprocessed events
        return (events ^ SYS_EVENT_MSG);
    }

    if ( events & TH_START_DEVICE_EVT )
    {
        // Start the Device
        VOID GAPRole_StartDevice( &thermometer_PeripheralCBs );

        // Register with bond manager after starting device
        VOID GAPBondMgr_Register( &thermometer_BondMgrCBs );

        updateUI();

        return ( events ^ TH_START_DEVICE_EVT );
    }

    if ( events & TH_START_DISCOVERY_EVT )
    {
        if ( timeAppPairingStarted )
        {
            // Postpone discovery until pairing completes
            timeAppDiscPostponed = TRUE;
        }
        else
        {
            timeAppDiscState = timeAppDiscStart();
        }

        timeAppDiscState = timeAppDiscStart();

        return ( events ^ TH_START_DISCOVERY_EVT );
    }

    //periodic indications - if enabled
    if ( events & TH_PERIODIC_MEAS_EVT )
    {
        // Perform periodic application task
        performPeriodicTask();
        return (events ^ TH_PERIODIC_MEAS_EVT);
    }
    //periodic notifications for IMEAS
    if ( events & TH_PERIODIC_IMEAS_EVT )
    {
        // Perform periodic application task
        performPeriodicImeasTask();
        return (events ^ TH_PERIODIC_IMEAS_EVT);
    }

    // Disconnect after sending measurement
    if ( events & TH_DISCONNECT_EVT )
    {

        uint8 advEnable = FALSE;

        //disable advertising on disconnect
        GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &advEnable );

        // Terminate Connection
        GAPRole_TerminateConnection();

        return (events ^ TH_DISCONNECT_EVT);
    }

    if ( events & TH_CCC_UPDATE_EVT )

        //This event is triggered when CCC is enabled
        if (gapProfileState == GAPROLE_CONNECTED)
        {
            temperatureMeasCharConfig = true;

            //if previously connected and measurements are active send stored
            if( connectedToLastAddress == true)
            {
                //send stored measurements
                thermometerSendStoredMeas();
            }

            //Only start meas timer if it's not running
            if(thMeasTimerRunning == FALSE)
            {
                //read stored interval value
                Thermometer_GetParameter( THERMOMETER_INTERVAL, &notify_interval );
                n32 = ((uint32)(notify_interval)) * (1000);

                //zero interval means should not perform meas
                if (n32 !=0)
                {
                    // Start interval timer
                    osal_start_timerEx( thermometerTaskId, TH_PERIODIC_MEAS_EVT, n32 );
                    thMeasTimerRunning = TRUE;
                }
            }
            return (events ^ TH_CCC_UPDATE_EVT);
        }

    return 0;
}
예제 #16
0
/*********************************************************************
 * @fn      BloodPressure_ProcessEvent
 *
 * @brief   BloodPressure Application Task event processor.  This function
 *          is called to process all events for the task.  Events
 *          include timers, messages and any other user defined events.
 *
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events - events to process.  This is a bit map and can
 *                   contain more than one event.
 *
 * @return  events not processed
 */
uint16 BloodPressure_ProcessEvent( uint8 task_id, uint16 events )
{
  
  VOID task_id; // OSAL required parameter that isn't used in this function
  
  if ( events & SYS_EVENT_MSG )
  {
    uint8 *pMsg;

    if ( (pMsg = osal_msg_receive( bloodPressureTaskId )) != NULL )
    {
      bloodPressure_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );

      // Release the OSAL message
      VOID osal_msg_deallocate( pMsg );
    }

    // return unprocessed events
    return (events ^ SYS_EVENT_MSG);
  }

  if ( events & BP_START_DEVICE_EVT )
  {
    // Start the Device
    VOID GAPRole_StartDevice( &bloodPressure_PeripheralCBs );
 
   // Register with bond manager after starting device
    GAPBondMgr_Register( (gapBondCBs_t *) &timeAppBondCB );

    updateUI();    
    
    return ( events ^ BP_START_DEVICE_EVT );
  }

  if ( events & BP_START_DISCOVERY_EVT )
  {
    if ( timeAppPairingStarted )
    {
      // Postpone discovery until pairing completes
      timeAppDiscPostponed = TRUE;
    }
    else
    {
      timeAppDiscState = timeAppDiscStart();
    }  
    return ( events ^ BP_START_DISCOVERY_EVT );
  }
  
  ///////////////////////////////////
  // BP MEAS DONE
  ///////////////////////////////////
  if ( events & TIMER_BPMEAS_EVT )
  {
    // Perform final measurement
    bpFinalMeas();
    
    return (events ^ TIMER_BPMEAS_EVT);
  }

  ///////////////////////////////////
  // CUFF
  ///////////////////////////////////
  if ( events & BP_TIMER_CUFF_EVT )
  {
    // Perform a Cutoff Measurement
    cuffMeas(); 
    
    cuffCount++;
    
    // If cuff count not met, keep sending cuff measurements
    if(cuffCount < CUFF_MAX)
    {
      // Start interval timer to send BP, just for simulation
      osal_start_timerEx( bloodPressureTaskId, BP_TIMER_CUFF_EVT, TIMER_CUFF_PERIOD );
     
    }
    // Get ready to send final measurement
    else
    {
      // Start timer to send final BP meas
      osal_start_timerEx( bloodPressureTaskId, TIMER_BPMEAS_EVT, TIMER_CUFF_PERIOD );    
    }
      
    return (events ^ BP_TIMER_CUFF_EVT);
  }  

  // Enable Bloodpressure CCC
  if ( events & BP_CCC_UPDATE_EVT )
  {
    if (gapProfileState == GAPROLE_CONNECTED)
    {
      
      //if previously connected and measurements are active send stored
      if( connectedToLastAddress == true)
      {
        //send stored measurements
        bpSendStoredMeas();
      }
    }      

    return (events ^ BP_CCC_UPDATE_EVT);
  }
  
  // Disconnect after sending measurement
  if ( events & BP_DISCONNECT_EVT )
  {
    
    uint8 advEnable = FALSE;
    
    //disable advertising on disconnect
    GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &advEnable );
    
    HalLedSet ( HAL_LED_1, HAL_LED_MODE_ON );
    
    // Terminate Connection
    GAPRole_TerminateConnection();

    return (events ^ BP_DISCONNECT_EVT);
  }    
 
   return 0;
}
예제 #17
0
/*********************************************************************
 * @fn      KeyFobApp_ProcessEvent
 *
 * @brief   Key Fob Application Task event processor.  This function
 *          is called to process all events for the task.  Events
 *          include timers, messages and any other user defined events.
 *
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events - events to process.  This is a bit map and can
 *                   contain more than one event.
 *
 * @return  none
 */
uint16 KeyFobApp_ProcessEvent( uint8 task_id, uint16 events )
{
  if ( events & SYS_EVENT_MSG )
  {
    uint8 *pMsg;

    if ( (pMsg = osal_msg_receive( keyfobapp_TaskID )) != NULL )
    {
      keyfobapp_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );

      // Release the OSAL message
      VOID osal_msg_deallocate( pMsg );
    }

    // return unprocessed events
    return (events ^ SYS_EVENT_MSG);
  }

  if ( events & KFD_START_DEVICE_EVT )
  {
    // Start the Device
    VOID GAPRole_StartDevice( &keyFob_PeripheralCBs );

    // Start Bond Manager
    VOID GAPBondMgr_Register( &keyFob_BondMgrCBs );

    // Start the Proximity Profile
    VOID ProxReporter_RegisterAppCBs( &keyFob_ProximityCBs );

    // Set timer for first battery read event
    osal_start_timerEx( keyfobapp_TaskID, KFD_BATTERY_CHECK_EVT, BATTERY_CHECK_PERIOD );

    // Start the Accelerometer Profile
    VOID Accel_RegisterAppCBs( &keyFob_AccelCBs );

    //Set the proximity attribute values to default
    ProxReporter_SetParameter( PP_LINK_LOSS_ALERT_LEVEL,  sizeof ( uint8 ), &keyfobProxLLAlertLevel );
    ProxReporter_SetParameter( PP_IM_ALERT_LEVEL,  sizeof ( uint8 ), &keyfobProxIMAlertLevel );
    ProxReporter_SetParameter( PP_TX_POWER_LEVEL,  sizeof ( int8 ), &keyfobProxTxPwrLevel );

    // Set LED1 on to give feedback that the power is on, and a timer to turn off
    HalLedSet( HAL_LED_1, HAL_LED_MODE_ON );
    osal_pwrmgr_device( PWRMGR_ALWAYS_ON ); // To keep the LED on continuously.
    osal_start_timerEx( keyfobapp_TaskID, KFD_POWERON_LED_TIMEOUT_EVT, 1000 );
    
    return ( events ^ KFD_START_DEVICE_EVT );
  }

  if ( events & KFD_POWERON_LED_TIMEOUT_EVT )
  {
    osal_pwrmgr_device( PWRMGR_BATTERY ); // Revert to battery mode after LED off
    HalLedSet( HAL_LED_1, HAL_LED_MODE_OFF ); 
    return ( events ^ KFD_POWERON_LED_TIMEOUT_EVT );
  }
  
  if ( events & KFD_ACCEL_READ_EVT )
  {
    bStatus_t status = Accel_GetParameter( ACCEL_ENABLER, &accelEnabler );

    if (status == SUCCESS)
    {
      if ( accelEnabler )
      {
        // Restart timer
        if ( ACCEL_READ_PERIOD )
        {
          osal_start_timerEx( keyfobapp_TaskID, KFD_ACCEL_READ_EVT, ACCEL_READ_PERIOD );
        }

        // Read accelerometer data
        accelRead();
      }
      else
      {
        // Stop the acceleromter
        osal_stop_timerEx( keyfobapp_TaskID, KFD_ACCEL_READ_EVT);
      }
    }
    else
    {
        //??
    }
    return (events ^ KFD_ACCEL_READ_EVT);
  }

  if ( events & KFD_BATTERY_CHECK_EVT )
  {
    // Restart timer
    if ( BATTERY_CHECK_PERIOD )
    {
      osal_start_timerEx( keyfobapp_TaskID, KFD_BATTERY_CHECK_EVT, BATTERY_CHECK_PERIOD );
    }

    // perform battery level check
    Batt_MeasLevel( );

    return (events ^ KFD_BATTERY_CHECK_EVT);
  }

  if ( events & KFD_TOGGLE_BUZZER_EVT )
  {
    // if this event was triggered while buzzer is on, turn it off, increment beep_count,
    // check whether max has been reached, and if not set the OSAL timer for next event to
    // turn buzzer back on.
    if ( buzzer_state == BUZZER_ON )
    {
      buzzerStop();
      buzzer_state = BUZZER_OFF;
      buzzer_beep_count++;
      #if defined ( POWER_SAVING )
        osal_pwrmgr_device( PWRMGR_BATTERY );
      #endif

      // check to see if buzzer has beeped maximum number of times
      // if it has, then don't turn it back on
      if ( ( buzzer_beep_count < BUZZER_MAX_BEEPS ) &&
           ( ( keyfobProximityState == KEYFOB_PROXSTATE_LINK_LOSS ) ||
             ( keyfobProximityState == KEYFOB_PROXSTATE_PATH_LOSS )    ) )
      {
        osal_start_timerEx( keyfobapp_TaskID, KFD_TOGGLE_BUZZER_EVT, 800 );
      }
    }
    else if ( keyfobAlertState != ALERT_STATE_OFF )
    {
      // if this event was triggered while the buzzer is off then turn it on if appropriate
      keyfobapp_PerformAlert();
    }

    return (events ^ KFD_TOGGLE_BUZZER_EVT);
  }


#if defined ( PLUS_BROADCASTER )
  if ( events & KFD_ADV_IN_CONNECTION_EVT )
  {
    uint8 turnOnAdv = TRUE;
    // Turn on advertising while in a connection
    GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &turnOnAdv );
  }
#endif

  // Discard unknown events
  return 0;
}
/*********************************************************************
 * @fn      SimpleBLEPeripheral_ProcessEvent
 *
 * @brief   Simple BLE Peripheral Application Task event processor.  This function
 *          is called to process all events for the task.  Events
 *          include timers, messages and any other user defined events.
 *
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events - events to process.  This is a bit map and can
 *                   contain more than one event.
 *
 * @return  events not processed
 */
uint16 SimpleBLEPeripheral_ProcessEvent( uint8 task_id, uint16 events )
{

  VOID task_id; // OSAL required parameter that isn't used in this function

  if ( events & SYS_EVENT_MSG )
  {
    uint8 *pMsg;

    if ( (pMsg = osal_msg_receive( simpleBLEPeripheral_TaskID )) != NULL )
    {
      simpleBLEPeripheral_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );

      // Release the OSAL message
      VOID osal_msg_deallocate( pMsg );
    }

    // return unprocessed events
    return (events ^ SYS_EVENT_MSG);
  }
  
  //user add
  if ( events & ZIGBEE_READ_ZM516X_INFO_EVT )
  {
    static uint8 state = 0;
    switch(state)
    {
    case 0:     
      init_zigbee_zm516x( task_id, ZIGBEE_READ_ZM516X_INFO_EVT );
      state = 1;
      break;
    case 1:
      HalGpioSet(HAL_GPIO_ZM516X_ALL,1); 
      HalGpioSet( HAL_GPIO_ZM516X_RESET,1 );
      osal_start_timerEx( task_id, ZIGBEE_READ_ZM516X_INFO_EVT, 100 );
      state = 2;
      break;
    case 2:
      HalGpioSet(HAL_GPIO_ZM516X_ALL,1); 
      read_local_cfg();
      state = 3;
      break;
    case 3:
      UartReceiveData( task_id, ZIGBEE_READ_ZM516X_INFO_EVT );
      state = 2;
      osal_start_timerEx( task_id, ZIGBEE_READ_ZM516X_INFO_EVT, 100 );
      break;
    default:
      break;
    }
    return (events ^ ZIGBEE_READ_ZM516X_INFO_EVT);
  }
  
  if ( events & UART_RECEIVE_EVT )
  {
    static unsigned char lenold = 0;
    unsigned char len = 0;
    //; NPI_ReadTransport(buf,len);
    if((len = NPI_RxBufLen()) > 0)
    {
      if(lenold == len)
      {
        osal_set_event( task_id, ZIGBEE_READ_ZM516X_INFO_EVT );
        lenold = 0;
      }
      else
      {
        lenold = len;
        osal_stop_timerEx( task_id, UART_RECEIVE_EVT );
        osal_start_timerEx( task_id, UART_RECEIVE_EVT, 3 );
      }
      return ( events ^ UART_RECEIVE_EVT );
    }
    else
    {
      //if(lenold > 0)
      //osal_set_event( task_id, SBP_READ_ZM516X_INFO_EVT );
      //lenold = len;
      //osal_start_timerEx( task_id, UART_RECEIVE_EVT, 10 );
      //osal_set_event( task_id, SBP_READ_ZM516X_INFO_EVT );
      return ( events ^ UART_RECEIVE_EVT );
    }
  }
  //end user add
  
  
  if ( events & SBP_START_DEVICE_EVT )
  {
    // Start the Device
    VOID GAPRole_StartDevice( &simpleBLEPeripheral_PeripheralCBs );

    // Start Bond Manager
    VOID GAPBondMgr_Register( &simpleBLEPeripheral_BondMgrCBs );

    // Set timer for first periodic event
    osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD );
    
    // user add : start user event
    osal_set_event( simpleBLEPeripheral_TaskID, ZIGBEE_READ_ZM516X_INFO_EVT );

    return ( events ^ SBP_START_DEVICE_EVT );
  }

  if ( events & SBP_PERIODIC_EVT )
  {
    // Restart timer
    if ( SBP_PERIODIC_EVT_PERIOD )
    {
      osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD );
    }

    // Perform periodic application task
    performPeriodicTask();

    return (events ^ SBP_PERIODIC_EVT);
  }

  // Discard unknown events
  return 0;
}
예제 #19
0
/*******************************************************************************
 * @fn      SensorTag_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 SensorTag_init(void)
{
  //uint8_t selfTestMap;
  // Setup I2C for sensors
  //bspI2cInit();

  // Handling of buttons, LED, relay
  hGpioPin = PIN_open(&pinGpioState, SensortagAppPinTable);
  PIN_registerIntCb(hGpioPin, SensorTag_callback);

	// ***************************************************************************
  // 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);

  // Create an RTOS queue for message from profile to be sent to app.
  appMsgQueue = Util_constructQueue(&appMsg);

  // Create one-shot clocks for internal periodic events.
  Util_constructClock(&periodicClock, SensorTag_clockHandler,
                      ST_PERIODIC_EVT_PERIOD, 0, false, ST_PERIODIC_EVT);

  // 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);

    //Returns 18, but this seems to be normal
    GAPRole_SetParameter(GAPROLE_SCAN_RSP_DATA, sizeof(scanRspData),
                         scanRspData);
    //Returns 18
    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,
                   (void*)attDeviceName);


#ifdef FEATURE_OAD
  // Register connection parameter update
  GAPRole_RegisterAppCBs( &paramUpdateCB);
#endif

  // 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
  DevInfo_AddService();                        // Device Information Service

  // Add application specific device information
  SensorTag_setDeviceInfo();

#ifdef FACTORY_IMAGE
  // Check if a factory image exists and apply current image if necessary
  //if (!SensorTag_hasFactoryImage())
  //{
  //  SensorTag_saveFactoryImage();
  //}
#endif

#ifdef FEATURE_REGISTER_SERVICE
  //Register_addService();                          // Generic register access
  //
#endif

#ifdef FEATURE_LCD
  SensorTagDisplay_init();                        // Display service DevPack LCD
#endif

#ifdef FEATURE_OAD
  SensorTagConnectionControl_init();              // Connection control to
                                                  // support OAD for iOs/Android
  OAD_addService();                               // OAD Profile
  OAD_register((oadTargetCBs_t *)&simpleBLEPeripheral_oadCBs);
  hOadQ = Util_constructQueue(&oadQ);
#endif

  // Start the Device
  GAPRole_StartDevice(&SensorTag_gapRoleCBs);

  // Start Bond Manager
  GAPBondMgr_Register(NULL);
  
  // Enable interrupt handling for keys and relay
  PIN_registerIntCb(hGpioPin, SensorTag_callback);
}
예제 #20
0
/*********************************************************************
 * @fn      SensorTag_ProcessEvent
 *
 * @brief   Simple BLE Peripheral Application Task event processor.  This function
 *          is called to process all events for the task.  Events
 *          include timers, messages and any other user defined events.
 *
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events - events to process.  This is a bit map and can
 *                   contain more than one event.
 *
 * @return  events not processed
 */
uint16 SensorTag_ProcessEvent( uint8 task_id, uint16 events )
{
    VOID task_id; // OSAL required parameter that isn't used in this function
    if ( events & SYS_EVENT_MSG )
    {
        uint8 *pMsg;
        if ( (pMsg = osal_msg_receive( sensorTag_TaskID )) != NULL )
        {
            sensorTag_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );
            // Release the OSAL message
            osal_msg_deallocate( pMsg );
        }
        // return unprocessed events
        return (events ^ SYS_EVENT_MSG);
    }
    // Handle system reset (long press on side key)
    if ( events & ST_SYS_RESET_EVT )
    {
        if (sysResetRequest)
        {
            HAL_SYSTEM_RESET();
        }
        return ( events ^ ST_SYS_RESET_EVT );
    }
    if ( events & ST_START_DEVICE_EVT )
    {
        // Start the Device
        GAPRole_StartDevice( &sensorTag_PeripheralCBs );
        // Start Bond Manager
        GAPBondMgr_Register( &sensorTag_BondMgrCBs );
        return ( events ^ ST_START_DEVICE_EVT );
    }

    ////////////////////////////
    ////    Accelerometer     //
    ////////////////////////////
//    if ( events & ST_ACCELEROMETER_SENSOR_EVT )
//    {
//        if(accConfig != ST_CFG_SENSOR_DISABLE)
//        {
//            readAccData();
//            osal_start_timerEx( sensorTag_TaskID, ST_ACCELEROMETER_SENSOR_EVT, sensorAccPeriod );
//        }
//        else
//        {
//            VOID resetCharacteristicValue( ACCELEROMETER_SERV_UUID, ACCELEROMETER_DATA, 0, ACCELEROMETER_DATA_LEN );
//            VOID resetCharacteristicValue( ACCELEROMETER_SERV_UUID, ACCELEROMETER_CONF, ST_CFG_SENSOR_DISABLE, sizeof ( uint8 ));
//            VOID resetCharacteristicValue( ACCELEROMETER_SERV_UUID, ACCELEROMETER_PERI, ACC_DEFAULT_PERIOD/ACCELEROMETER_TIME_UNIT, sizeof ( uint8 ));
//        }
//        return (events ^ ST_ACCELEROMETER_SENSOR_EVT);
//    }

    //////////////////////////
    //      Gyroscope       //
    //////////////////////////
    if ( events & ST_GYROSCOPE_SENSOR_EVT )
    {
        uint8 status;
        status = HalGyroStatus();
        if(gyroEnabled)
        {
            if (status == HAL_GYRO_STOPPED)
            {
                HalGyroSelectAxes(sensorGyroAxes);
                HalGyroTurnOn();
                GAPRole_SendUpdateParam( 240, 256,0, 138, GAPROLE_TERMINATE_LINK);
                //GAPRole_SendUpdateParam( 100, 105,0, 138, GAPROLE_TERMINATE_LINK);
                osal_start_timerEx( sensorTag_TaskID, ST_GYROSCOPE_SENSOR_EVT, GYRO_STARTUP_TIME);
            }
            else
            {
                if(sensorGyroUpdateAxes)
                {
                    HalGyroSelectAxes(sensorGyroAxes);
                    sensorGyroUpdateAxes = FALSE;
                }
                if (status == HAL_GYRO_DATA_READY)
                {
                    readGyroData();
                    osal_start_timerEx( sensorTag_TaskID, ST_GYROSCOPE_SENSOR_EVT, GYRO_DEFAULT_PERIOD - GYRO_STARTUP_TIME);
                }
                else
                {
                    // Gyro needs to be activated;
                    HalGyroWakeUp();
                    osal_start_timerEx( sensorTag_TaskID, ST_GYROSCOPE_SENSOR_EVT, GYRO_STARTUP_TIME);
                }
            }
        }
        else
        {
            HalGyroTurnOff();
            if ( status == HAL_GYRO_STOPPED)
            {
                resetCharacteristicValue( GYROSCOPE_SERV_UUID, GYROSCOPE_DATA, 0, GYROSCOPE_DATA_LEN);
                resetCharacteristicValue( GYROSCOPE_SERV_UUID, GYROSCOPE_CONF, ST_CFG_SENSOR_DISABLE, sizeof( uint8 ));
            }
            else
            {
                // Indicate error
                resetCharacteristicValue( GYROSCOPE_SERV_UUID, GYROSCOPE_DATA, ST_CFG_ERROR, GYROSCOPE_DATA_LEN);
                resetCharacteristicValue( GYROSCOPE_SERV_UUID, GYROSCOPE_CONF, ST_CFG_ERROR, sizeof( uint8 ));
            }
        }
        return (events ^ ST_GYROSCOPE_SENSOR_EVT);
    }
#if defined ( PLUS_BROADCASTER )
    if ( events & ST_ADV_IN_CONNECTION_EVT )
    {
        uint8 turnOnAdv = TRUE;
        // Turn on advertising while in a connection
        GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &turnOnAdv );
        return (events ^ ST_ADV_IN_CONNECTION_EVT);
    }
#endif // PLUS_BROADCASTER
    // Discard unknown events
    return 0;
}
예제 #21
0
/*********************************************************************
 * @fn      HidDev_ProcessEvent
 *
 * @brief   Hid Dev Task event processor.  This function
 *          is called to process all events for the task.  Events
 *          include timers, messages and any other user defined events.
 *
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events - events to process.  This is a bit map and can
 *                   contain more than one event.
 *
 * @return  events not processed
 */
uint16 HidDev_ProcessEvent( uint8 task_id, uint16 events )
{

  VOID task_id; // OSAL required parameter that isn't used in this function

  if ( events & SYS_EVENT_MSG )
  {
    uint8 *pMsg;

    if ( (pMsg = osal_msg_receive( hidDevTaskId )) != NULL )
    {
      hidDev_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );

      // Release the OSAL message
      VOID osal_msg_deallocate( pMsg );
    }

    // return unprocessed events
    return (events ^ SYS_EVENT_MSG);
  }

  if ( events & START_DEVICE_EVT )
  {
    // Start the Device
    VOID GAPRole_StartDevice( &hidDev_PeripheralCBs );

    // Register with bond manager after starting device
    GAPBondMgr_Register( (gapBondCBs_t *) &hidDevBondCB );

    return ( events ^ START_DEVICE_EVT );
  }

  if ( events & HID_IDLE_EVT )
  {
    if ( hidDevGapState == GAPROLE_CONNECTED )
    {
      // if pairing in progress then restart timer
      if ( hidDevPairingStarted )
      {
        hidDevStartIdleTimer();
      }
      // else disconnect
      else
      {
        GAPRole_TerminateConnection();
      }
    }

    return ( events ^ HID_IDLE_EVT );
  }

  if ( events & BATT_PERIODIC_EVT )
  {
    // Perform periodic battery task
    hidDevBattPeriodicTask();

    return ( events ^ BATT_PERIODIC_EVT );
  }

  if ( events & HID_SEND_REPORT_EVT )
  {
    // if connection is secure
    if ( hidDevConnSecure )
    {
      hidDevReport_t *pReport = hidDevDequeueReport();

      if ( pReport != NULL )
      {
        // Send report
        hidDevSendReport( pReport->id, pReport->type, pReport->len, pReport->data );
      }

      return ( reportQEmpty() ? events ^ HID_SEND_REPORT_EVT : events );
    }

    return ( events ^ HID_SEND_REPORT_EVT );
  }

  return 0;
}
예제 #22
0
/*********************************************************************
 * @fn      HeartRate_init
 *
 * @brief   Initialization function for the Heart Rate application thread.
 *          This is called during initialization and should contain
 *          any application specific initialization (ie. hardware
 *          initialization/setup, table initialization, power up
 *          notification ...).
 *
 * @param   none
 *
 * @return  none
 */
void HeartRate_init(void)
{
  // ******************************************************************
  // 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 DB Address till CC2650 board gets its own IEEE address.
  //uint8_t bdAddress[B_ADDR_LEN] = { 0x22, 0x22, 0x22, 0x22, 0x22, 0x22 };
  //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);
  
  // Create one-shot clocks for internal periodic events.
  Util_constructClock(&measPerClock, HeartRate_clockHandler,
                      DEFAULT_HEARTRATE_PERIOD, 0, false,
                      HEARTRATE_MEAS_PERIODIC_EVT);
  Util_constructClock(&battPerClock, HeartRate_clockHandler,
                      DEFAULT_BATT_PERIOD, 0, false,
                      HEARTRATE_BATT_PERIODIC_EVT);
  
  // Initialize keys on SRF06.
  Board_initKeys(HeartRate_keyPressHandler);
    
  // Setup the GAP Peripheral Role Profile.
  {
#if ADVERTISE_WHEN_NOT_CONNECTED
    uint8_t initial_advertising_enable = TRUE;
#else
    // Press right key to initiate advertising and measurement.
    uint8_t initial_advertising_enable = FALSE;
#endif //ADVERTISE_WHEN_NOT_CONNECTED

    // 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 gapRole_AdvertOffTime = 0;
      
    uint8_t enable_update_request  = DEFAULT_ENABLE_UPDATE_REQUEST;
    uint16_t desired_min_interval  = DEFAULT_DESIRED_MIN_CONN_INTERVAL;
    uint16_t desired_max_interval  = DEFAULT_DESIRED_MAX_CONN_INTERVAL;
    uint16_t desired_slave_latency = DEFAULT_DESIRED_SLAVE_LATENCY;
    uint16_t desired_conn_timeout  = DEFAULT_DESIRED_CONN_TIMEOUT;

    // Set the GAP Role Parameters.
    GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8_t),
                          &initial_advertising_enable);
    GAPRole_SetParameter(GAPROLE_ADVERT_OFF_TIME, sizeof(uint16_t),
                          &gapRole_AdvertOffTime);
    
    GAPRole_SetParameter(GAPROLE_SCAN_RSP_DATA, sizeof (scanData),
                          scanData);
    GAPRole_SetParameter(GAPROLE_ADVERT_DATA, sizeof(advertData),
                          advertData);
    
    GAPRole_SetParameter(GAPROLE_PARAM_UPDATE_ENABLE, sizeof(uint8_t), 
                          &enable_update_request);
    GAPRole_SetParameter(GAPROLE_MIN_CONN_INTERVAL, sizeof(uint16_t), 
                          &desired_min_interval);
    GAPRole_SetParameter(GAPROLE_MAX_CONN_INTERVAL, sizeof(uint16_t), 
                          &desired_max_interval);
    GAPRole_SetParameter(GAPROLE_SLAVE_LATENCY, sizeof(uint16_t), 
                          &desired_slave_latency);
    GAPRole_SetParameter(GAPROLE_TIMEOUT_MULTIPLIER, sizeof(uint16_t), 
                          &desired_conn_timeout);
  }
  
  // Set the GAP Characteristics.
  GGS_SetParameter(GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, attDeviceName);
  
  // Setup the GAP Bond Manager.
  {
    uint32 passkey = 0; // passkey "000000"
    uint8_t pairMode = GAPBOND_PAIRING_MODE_WAIT_FOR_REQ;
    uint8_t mitm = FALSE;
    uint8_t ioCap = GAPBOND_IO_CAP_DISPLAY_ONLY;
    uint8_t bonding = TRUE;
    GAPBondMgr_SetParameter(GAPBOND_DEFAULT_PASSCODE, sizeof (uint32),
                             &passkey);
    GAPBondMgr_SetParameter(GAPBOND_PAIRING_MODE, sizeof (uint8_t),
                             &pairMode);
    GAPBondMgr_SetParameter(GAPBOND_MITM_PROTECTION, sizeof (uint8_t), &mitm);
    GAPBondMgr_SetParameter(GAPBOND_IO_CAPABILITIES, sizeof (uint8_t),
                             &ioCap);
    GAPBondMgr_SetParameter(GAPBOND_BONDING_ENABLED, sizeof (uint8_t),
                             &bonding);
  }
  
  // Initialize GATT attributes.
  GGS_AddService(GATT_ALL_SERVICES);         // GAP
  GATTServApp_AddService(GATT_ALL_SERVICES); // GATT attributes
  
  // Add heart rate service.
  HeartRate_AddService(GATT_ALL_SERVICES);
  // Add device info service.
  DevInfo_AddService();
  // Add battery service.
  Batt_AddService();
  
  // Setup the Heart Rate Characteristic Values.
  {
    uint8_t sensLoc = HEARTRATE_SENS_LOC_WRIST;
    HeartRate_SetParameter(HEARTRATE_SENS_LOC, sizeof (uint8_t), &sensLoc);
  }
  
  // Setup Battery Characteristic Values.
  {
    uint8_t critical = DEFAULT_BATT_CRITICAL_LEVEL;
    Batt_SetParameter(BATT_PARAM_CRITICAL_LEVEL, sizeof(uint8_t), &critical);
  }
  
  // Register for Heart Rate service callback.
  HeartRate_Register(&HeartRate_serviceCB);
  
  // Register for Battery service callback.
  Batt_Register (&HeartRate_battCB);
  
  // Start the Device.
  GAPRole_StartDevice(&heartRatePeripheralCB);
  
  // Start the Bond Manager.
  GAPBondMgr_Register((gapBondCBs_t *)&heartRateBondCB);
}
/*********************************************************************
* @fn      SimpleBLEPeripheral_ProcessEvent
*
* @brief   Simple BLE Peripheral Application Task event processor.  This function
*          is called to process all events for the task.  Events
*          include timers, messages and any other user defined events.
*
* @param   task_id  - The OSAL assigned task ID.
* @param   events - events to process.  This is a bit map and can
*                   contain more than one event.
*
* @return  events not processed
*/
uint16 SimpleBLEPeripheral_ProcessEvent( uint8 task_id, uint16 events )
{
	
	VOID task_id; // OSAL required parameter that isn't used in this function
	
	if ( events & SYS_EVENT_MSG )
	{
		uint8 *pMsg;
		
		if ( (pMsg = osal_msg_receive( simpleBLEPeripheral_TaskID )) != NULL )
		{
			simpleBLEPeripheral_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );
			
			// Release the OSAL message
			VOID osal_msg_deallocate( pMsg );
		}
		
		// return unprocessed events
		return (events ^ SYS_EVENT_MSG);
	}
	
	if ( events & SBP_START_DEVICE_EVT )
	{
		// Start the Device
		VOID GAPRole_StartDevice( &simpleBLEPeripheral_PeripheralCBs );
		
		// Start Bond Manager
		VOID GAPBondMgr_Register( &simpleBLEPeripheral_BondMgrCBs );
		
		// Set timer for first periodic event
		osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD );
		
		return ( events ^ SBP_START_DEVICE_EVT );
	}
	
	if ( events & SBP_PERIODIC_EVT )
	{
		// Restart timer
		if ( SBP_PERIODIC_EVT_PERIOD )
		{
			osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD );
		}
		
		// Perform periodic application task
		performPeriodicTask();
		
		return (events ^ SBP_PERIODIC_EVT);
	}
	
	if ( events & SBP_LED_TOGGLE_EVT )
	{
		// Assuming that the LED is on P0_4 in the circuit.
		if(led_toggle_flag == 0)
		{
			P0_4 = 1;
			led_toggle_flag = 1;
		}
		else
		{
			P0_4 = 0;
			led_toggle_flag = 0;
		}
		
		VOID osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_LED_TOGGLE_EVT, 1000 );
		return ( events ^ SBP_LED_TOGGLE_EVT );
	}
	// Discard unknown events
	return 0;
}
예제 #24
0
uint16 SensorTag_ProcessEvent(uint8 task_id, uint16 events)
{
	VOID	task_id;	// OSAL required parameter that isn't used in this function


	///////////////////////////////////////////////////////////////////////
	// system event handle                                               //
	///////////////////////////////////////////////////////////////////////
	if (events & SYS_EVENT_MSG) {
		uint8	*msg;

		if ((msg = osal_msg_receive(sensorTag_TaskID)) != NULL) {
			sensorTag_ProcessOSALMsg((osal_event_hdr_t *) msg);

			// release the OSAL message
			osal_msg_deallocate(msg);
		}

		// return unprocessed events
		return (events ^ SYS_EVENT_MSG);
	}


	///////////////////////////////////////////////////////////////////////
	// start device event                                                //
	///////////////////////////////////////////////////////////////////////
	if (events & EVT_START_DEVICE) {
		// start the device
		GAPRole_StartDevice(&sensorTag_PeripheralCBs);

		// start bond manager
#if !defined(GAPBONDMGR_NO_SUPPORT)
		GAPBondMgr_Register(&sensorTag_BondMgrCBs);
#endif
		// start peripheral device
		oled_init();
		adxl345_softrst();
//		adxl345_self_calibration();

		steps	     = 0;
		BATCD_PXIFG  = ~(BATCD_BV);
		BATCD_IEN   |=  BATCD_IENBIT;

		osal_start_reload_timer(sensorTag_TaskID, EVT_RTC, PERIOD_RTC);
		pwmgr_state_change(PWMGR_S0, 0);

		fmsg(("\033[40;32m\n[power on]\033[0m\n"));
		return (events ^ EVT_START_DEVICE);
	}


	///////////////////////////////////////////////////////////////////////
	// key long press handle                                             //
	///////////////////////////////////////////////////////////////////////
	if (events & EVT_MODE) {
		if (key1_press) {
			oled_clr_screen();
			if ((opmode & 0xF0) == MODE_NORMAL) {
				opmode        = MODE_WORKOUT | MODE_TIME;
				workout.steps = normal.steps;
				workout.time  = osal_getClock();
				fmsg(("\033[40;32m[workout mode]\033[0m\n"));
			} else {
				opmode        = MODE_NORMAL | MODE_TIME;
				fmsg(("\033[40;32m[normal mode]\033[0m\n"));
			}

			pwmgr_state_change(pwmgr, TIME_OLED_OFF);
		}
		return (events ^ EVT_MODE);
	}

	if (events & EVT_SLEEP) {
		if (key1_press) {
			oled_clr_screen();
			opmode = MODE_SLEEP;
			fmsg(("\033[40;32m[sleep mode]\033[0m\n"));

			pwmgr_state_change(pwmgr, TIME_OLED_OFF);
		}
		return (events ^ EVT_SLEEP);
	}

	if (events & EVT_SYSRST) {
		if (key1_press) {
			fmsg(("\033[40;32m[system reset]\033[0m\n"));
			HAL_SYSTEM_RESET();
//			adxl345_self_calibration();
		}
		return (events ^ EVT_SYSRST);
	}


	///////////////////////////////////////////////////////////////////////
	// display handle                                                    //
	///////////////////////////////////////////////////////////////////////
	if (events & EVT_DISP) {
		if (pwmgr == PWMGR_S1) {
			sensorTag_HandleDisp(opmode, acc);
		} else {
			// display battery only
			sensorTag_BattDisp(batt_get_level());
		}
		if (pwmgr != PWMGR_S6)  {
			osal_start_timerEx(sensorTag_TaskID, EVT_DISP, PERIOD_DISP);
		}
		return (events ^ EVT_DISP);
	}


	///////////////////////////////////////////////////////////////////////
	// g-sensor handle                                                   //
	///////////////////////////////////////////////////////////////////////
	if (events & EVT_GSNINT1) {
		adxl345_exit_sleep();
		pwmgr_state_change(PWMGR_S3, TIME_GSEN_OFF);
		return (events ^ EVT_GSNINT1);
	}

	if (events & EVT_GSNINT2) {
		unsigned char	sampling;
		unsigned char	i;

		sampling = adxl345_chk_fifo();
		for (i=0; i<sampling; i++) {
			adxl345_read(acc);
#if (DEBUG_MESSAGE & MSG_STEPS)
			{
				unsigned long	tmp = algo_step(acc);
				if (normal.steps != tmp) {
					stepmsg(("\033[1;33mstep=%0lu\n\033[0m", tmp));
				}
				normal.steps = tmp;
			}
#else
			normal.steps = algo_step(acc);
#endif
		}

		normal.distance  = calc_distance(normal.steps, pi.stride);
		workout.distance = calc_distance((normal.steps - workout.steps), pi.stride);
		normal.calorie   = calc_calorie(normal.distance, pi.weight);
		workout.calorie  = calc_calorie(workout.distance, pi.weight);
		return (events ^ EVT_GSNINT2);
	}

	if (events & EVT_GSENSOR) {
		adxl345_exit_sleep();
		return (events ^ EVT_GSENSOR);
	}


	///////////////////////////////////////////////////////////////////////
	// RTC handle                                                        //
	///////////////////////////////////////////////////////////////////////
	if (events & EVT_RTC) {
		// performed once per second


		// record data
		if ((pwmgr != PWMGR_S5) && (pwmgr != PWMGR_S6)) {
#if defined(HAL_IMAGE_A) || defined(HAL_IMAGE_B)
			if ((osal_getClock() - mark.time) >= (12UL*60UL)) {
#else
			if ((osal_getClock() - mark.time) >= (12UL)) {
#endif
				if (!hash_is_full()) {
					unsigned short	tmp = normal.steps - mark.steps;

					switch (opmode & 0xF0) {
					case MODE_WORKOUT: tmp |= 0x8000; break;
					case MODE_SLEEP:   tmp |= 0x4000; break;
					}
					hash_put(&tmp);
				}
				mark.time  = osal_getClock();
#if defined(HAL_IMAGE_A) || defined(HAL_IMAGE_B)
				if ((mark.time % (24UL*60UL*60UL)) <= (13UL*60UL)) {
#else
				if ((mark.time % (24UL*60UL*60UL)) <= (13UL)) {
#endif
					dmsg(("reset steps...\n"));
					normal.steps  = 0;
					workout.steps = 0;
					STEPS         = 0;
				}
				mark.steps = normal.steps;
			}
		}

		// power management
		switch (pwmgr) {
		case PWMGR_S0:
			pmsg(("\033[40;35mS0 (power on)\033[0m\n"));
			if (pwmgr_saving_timer()) {
				adxl345_enter_sleep();

				osal_pwrmgr_device(PWRMGR_BATTERY);
				pwmgr_state_change(PWMGR_S4, 0);
			}
			break;

		case PWMGR_S1:
			pmsg(("\033[40;35mS1 (rtc+gsen+ble+oled)\033[0m\n"));
			if (pwmgr_saving_timer()) {
				oled_enter_sleep();
				osal_stop_timerEx(sensorTag_TaskID, EVT_MODE);
				osal_stop_timerEx(sensorTag_TaskID, EVT_SLEEP);
				osal_stop_timerEx(sensorTag_TaskID, EVT_SYSRST);

				pwmgr_state_change(PWMGR_S3, TIME_GSEN_OFF);
			}
			break;

		case PWMGR_S2:
			pmsg(("\033[40;35mS2 (rtc+gsen+ble)\033[0m\n"));
			if (gapProfileState == GAPROLE_WAITING) {
				// enable key interrupt mode
				InitBoard(OB_READY);
				pwmgr_state_change(PWMGR_S3, TIME_GSEN_OFF);
			}
			break;

		case PWMGR_S3:
			pmsg(("\033[40;35mS3 (rtc+gsen)\033[0m\n"));
			if (steps == normal.steps) {
				if (pwmgr_saving_timer()) {
					adxl345_enter_sleep();
					pwmgr_state_change(PWMGR_S4, 0);
				}
			} else {
				steps = normal.steps;
				pwmgr_state_change(pwmgr, TIME_GSEN_OFF);
			}
			break;

		case PWMGR_S4:
			pmsg(("\033[40;35mS4 (rtc)\033[0m\n"));
			dmsg(("$"));
			break;

		default:
		case PWMGR_S5:
			pmsg(("\033[40;35mS5 (shutdown)\033[0m\n"));
			adxl345_shutdown();
			osal_stop_timerEx(sensorTag_TaskID, EVT_RTC);
			break;

		case PWMGR_S6:
			pmsg(("\033[40;35mS6 (rtc+oled)\033[0m\n"));
			if (pwmgr_saving_timer()) {
				oled_enter_sleep();

				// enable key interrupt mode
				InitBoard(OB_READY);
				pwmgr_state_change(PWMGR_S5, 0);
			}
			break;
		}

		// battery measure
		if ((!batt_measure()) && (pwmgr != PWMGR_S6)) {
			pwmgr_state_change(PWMGR_S5, 0);
		}
		return (events ^ EVT_RTC);
	}


	///////////////////////////////////////////////////////////////////////
	// battery charge detect handle                                      //
	///////////////////////////////////////////////////////////////////////
	if (events & EVT_CHARGING) {
		if (pwmgr != PWMGR_S1) {
			if (!BATCD_SBIT) {
				dmsg(("[charging]\n"));
				oled_exit_sleep();
				if ((pwmgr == PWMGR_S5) || (pwmgr == PWMGR_S6)) {
					osal_start_reload_timer(sensorTag_TaskID, EVT_RTC, PERIOD_RTC);
					pwmgr_state_change(PWMGR_S4, 0);
				}
			} else {
				dmsg(("[no charge]\n"));
				oled_enter_sleep();
			}
		}
		return (events ^ EVT_CHARGING);
	}


	///////////////////////////////////////////////////////////////////////
	// discard unknown events                                            //
	///////////////////////////////////////////////////////////////////////

	return 0;
}
예제 #25
0
/*********************************************************************
 * @fn      SimpleBLEPeripheral_ProcessEvent
 *
 * @brief   Simple BLE Peripheral Application Task event processor.  This function
 *          is called to process all events for the task.  Events
 *          include timers, messages and any other user defined events.
 *
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events - events to process.  This is a bit map and can
 *                   contain more than one event.
 *
 * @return  events not processed
 */
uint16 SimpleBLEPeripheral_ProcessEvent(uint8 task_id, uint16 events) {

	VOID task_id; // OSAL required parameter that isn't used in this function

	if (events & SYS_EVENT_MSG) {
		uint8 *pMsg;

		if ((pMsg = osal_msg_receive(simpleBLEPeripheral_TaskID)) != NULL) {
			simpleBLEPeripheral_ProcessOSALMsg((osal_event_hdr_t *) pMsg);

			// Release the OSAL message
			VOID osal_msg_deallocate(pMsg);
		}

		// return unprocessed events
		return (events ^ SYS_EVENT_MSG);
	}

	if (events & SBP_START_DEVICE_EVT) {
		// Start the Device
		GAPRole_StartDevice(&simpleBLEPeripheral_PeripheralCBs);

		// Start Bond Manager
		GAPBondMgr_Register(&simpleBLEPeripheral_BondMgrCBs);

		// Set timer for first periodic event
		osal_start_timerEx(simpleBLEPeripheral_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD);

		return (events ^ SBP_START_DEVICE_EVT);
	}

	if (events & SBP_PERIODIC_EVT) {
		// Restart timer
		if (SBP_PERIODIC_EVT_PERIOD) {
			osal_start_timerEx(simpleBLEPeripheral_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD);
		}

		// Perform periodic application task
		performPeriodicTask();

		return (events ^ SBP_PERIODIC_EVT);
	}

	if (events & SBP_ZEKEZANG_EVT) {
		uint8 initial_advertising_enable = FALSE;
		GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8), &initial_advertising_enable);
		return (events ^ SBP_ZEKEZANG_EVT);
	}

	if (events & SBP_SEND_IRDATA_EVT) {
		HalLcdWriteString("send plan complete...", HAL_LCD_LINE_4);
		return (events ^ SBP_SEND_IRDATA_EVT);
	}

	if (events & SBP_ADV_IN_CONNECTION_EVT) {
		uint8 turnOnAdv = TRUE;
		// Turn on advertising while in a connection
		GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8), &turnOnAdv);

		return (events ^ SBP_ADV_IN_CONNECTION_EVT);
	}

	return 0;
}
예제 #26
0
/*********************************************************************
 * @fn      RunningSensor_ProcessEvent
 *
 * @brief   Running Application Task event processor.  This function
 *          is called to process all events for the task.  Events
 *          include timers, messages and any other user defined events.
 *
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events - events to process.  This is a bit map and can
 *                   contain more than one event.
 *
 * @return  events not processed
 */
uint16 RunningSensor_ProcessEvent( uint8 task_id, uint16 events )
{

  VOID task_id; // OSAL required parameter that isn't used in this function

  if ( events & SYS_EVENT_MSG )
  {
    uint8 *pMsg;

    if ( (pMsg = osal_msg_receive( sensor_TaskID )) != NULL )
    {
      sensor_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );

      // Release the OSAL message
      VOID osal_msg_deallocate( pMsg );
    }

    // return unprocessed events
    return (events ^ SYS_EVENT_MSG);
  }

  if ( events & START_DEVICE_EVT )
  {
    // Start the Device
    VOID GAPRole_StartDevice( &runningPeripheralCB );

    // Register with bond manager after starting device
    GAPBondMgr_Register( (gapBondCBs_t *) &runningBondCB );

    return ( events ^ START_DEVICE_EVT );
  }

  if ( events & RSC_PERIODIC_EVT )
  {
    // Perform periodic sensor's periodic task
    sensorPeriodicTask();

    return (events ^ RSC_PERIODIC_EVT);
  }

  if ( events & RSC_CONN_PARAM_UPDATE_EVT )
  {
    // Send param update.  If it fails, retry until successful.
    GAPRole_SendUpdateParam( DEFAULT_DESIRED_MIN_CONN_INTERVAL, DEFAULT_DESIRED_MAX_CONN_INTERVAL,
                             DEFAULT_DESIRED_SLAVE_LATENCY, DEFAULT_DESIRED_CONN_TIMEOUT,
                             GAPROLE_RESEND_PARAM_UPDATE );

    // Assuming service discovery complete, start neglect timer
    if ( USING_NEGLECT_TIMEOUT )
    {
      osal_start_timerEx( sensor_TaskID, RSC_NEGLECT_TIMEOUT_EVT, NEGLECT_TIMEOUT_DELAY );
    }

    return (events ^ RSC_CONN_PARAM_UPDATE_EVT);
  }

  if ( events & RSC_NEGLECT_TIMEOUT_EVT )
  {
    // No user input, terminate connection.
    GAPRole_TerminateConnection();

    return ( events ^ RSC_NEGLECT_TIMEOUT_EVT );
  }

  if ( events & RSC_RESET_EVT )
  {
     if ( gapProfileState == GAPROLE_CONNECTED )
     {
       // Exit the connection
       GAPRole_TerminateConnection();

       // There is no callback for manual termination of the link.  change state variable here.
       gapProfileState = GAPROLE_WAITING;

       // Set timer to give the end advertising event time to finish
       osal_start_timerEx( sensor_TaskID, RSC_RESET_EVT, 500 );
     }
     else if ( gapProfileState == GAPROLE_ADVERTISING )
     {
       uint8 value = FALSE;

       // Turn off advertising
       GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &value );

       // Set timer to give the end advertising event time to finish
       osal_start_timerEx( sensor_TaskID, RSC_RESET_EVT, 500 );
     }
     else if ( USING_WHITE_LIST == TRUE )
     {
       //temporary variable
       uint8 value = GAP_FILTER_POLICY_ALL;

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

       sensorUsingWhiteList = FALSE;

       // Clear the white list
       HCI_LE_ClearWhiteListCmd();

       // Set timer to give the end advertising event time to finish
       osal_start_timerEx( sensor_TaskID, RSC_RESET_EVT, 500 );
     }
     else if ( (gapProfileState == GAPROLE_STARTED) ||
               (gapProfileState == GAPROLE_WAITING) ||
               (gapProfileState == GAPROLE_WAITING_AFTER_TIMEOUT) )
     {
       uint8 eraseBonds = TRUE;

       // 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 );

       return (events ^ RSC_RESET_EVT);
     }
  }

  // Discard unknown events
  return 0;
}
/*********************************************************************
 * @fn      SimpleBLEPeripheral_ProcessEvent
 *
 * @brief   Simple BLE Peripheral Application Task event processor.  This function
 *          is called to process all events for the task.  Events
 *          include timers, messages and any other user defined events.
 *
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events - events to process.  This is a bit map and can
 *                   contain more than one event.
 *
 * @return  events not processed
 */
uint16 SimpleBLEPeripheral_ProcessEvent( uint8 task_id, uint16 events )
{

  VOID task_id; // OSAL required parameter that isn't used in this function

  if ( events & SYS_EVENT_MSG )
  {
    uint8 *pMsg;

    if ( (pMsg = osal_msg_receive( simpleBLEPeripheral_TaskID )) != NULL )
    {
      simpleBLEPeripheral_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );

      // Release the OSAL message
      VOID osal_msg_deallocate( pMsg );
    }

    // return unprocessed events
    return (events ^ SYS_EVENT_MSG);
  }

  if ( events & SBP_START_DEVICE_EVT )
  {
    // Start the Device
    VOID GAPRole_StartDevice( &simpleBLEPeripheral_PeripheralCBs );

    // Start Bond Manager
    VOID GAPBondMgr_Register( &simpleBLEPeripheral_BondMgrCBs );

//    sys_config.pwm[0] = 0; //blue
//    sys_config.pwm[1] = 0;//green
//    sys_config.pwm[2] = 0;//red
//    sys_config.pwm[3] = 0;//white


    ti_pwm_init(2500, sys_config.pwm[0], sys_config.pwm[1], sys_config.pwm[2], sys_config.pwm[3]);  

    osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_SET_PWM_EVT, 100 );


    //if(g_initFlag == FALSE)
    {   
        // 进行自测 SBP_SELF_TEST_EVT
        osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_SELF_TEST_EVT, 200 );
    }

    return ( events ^ SBP_START_DEVICE_EVT );
  }


  if ( events & SBP_SELF_TEST_EVT )
  {
    static uint8 count = 0;

    if(count%3 == 0)
    {
        sys_config.pwm[3] = 0; // 白色
        sys_config.pwm[2] = 0; // 红色
        sys_config.pwm[1] = 0; // 绿色
        sys_config.pwm[0] = 255; // 蓝色  
    }    
    else if(count%3 == 1)
    {
        sys_config.pwm[3] = 0; // 白色
        sys_config.pwm[2] = 0; // 红色
        sys_config.pwm[1] = 255; // 绿色
        sys_config.pwm[0] = 0; // 蓝色  
    }    
    else if(count%3 == 2)
    {
        sys_config.pwm[3] = 0; // 白色
        sys_config.pwm[2] = 255; // 红色
        sys_config.pwm[1] = 0; // 绿色
        sys_config.pwm[0] = 0; // 蓝色  
    }

    count++;
    if(count < 10)
    {
        osal_set_event( simpleBLEPeripheral_TaskID, SBP_SET_PWM_EVT);
        osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_SELF_TEST_EVT, 800 );
    }
    return (events ^ SBP_SELF_TEST_EVT);
  }



  if ( events & SBP_PERIODIC_EVT )
  {
    // Restart timer
    if ( SBP_PERIODIC_EVT_PERIOD )
    {

    }

    // Perform periodic application task
    //performPeriodicTask();

    return (events ^ SBP_PERIODIC_EVT);
  }


  if ( events & SBP_READ_SENSOR_EVT )
  {
    return (events ^ SBP_READ_SENSOR_EVT);
  }  

  if ( events & KFD_BATTERY_CHECK_EVT )
  {
    // Restart timer
    if ( BATTERY_CHECK_PERIOD )
    {
      osal_start_timerEx( simpleBLEPeripheral_TaskID, KFD_BATTERY_CHECK_EVT, BATTERY_CHECK_PERIOD );
    }

    // perform battery level check
    Batt_MeasLevel( );

    return (events ^ KFD_BATTERY_CHECK_EVT);
  }


  if ( events & SBP_SET_PWM_EVT )
  {
    ti_pwm_set_period(PWM1_P11, sys_config.pwm[0], 300);  
    ti_pwm_set_period(PWM2_P10, sys_config.pwm[1], 300);  
    ti_pwm_set_period(PWM3_P07, sys_config.pwm[2], 300);  
    ti_pwm_set_period(PWM4_P06, sys_config.pwm[3], 300);
    
    return (events ^ SBP_SET_PWM_EVT);
  }



#if defined ( PLUS_BROADCASTER )
  if ( events & SBP_ADV_IN_CONNECTION_EVT )
  {
    uint8 turnOnAdv = TRUE;
    // Turn on advertising while in a connection
    GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &turnOnAdv );

    return (events ^ SBP_ADV_IN_CONNECTION_EVT);
  }
#endif // PLUS_BROADCASTER

  // Discard unknown events
  return 0;
}
예제 #28
0
/*********************************************************************
 * @fn      SensorTag_ProcessEvent
 *
 * @brief   Simple BLE Peripheral Application Task event processor.  This function
 *          is called to process all events for the task.  Events
 *          include timers, messages and any other user defined events.
 *
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events - events to process.  This is a bit map and can
 *                   contain more than one event.
 *
 * @return  events not processed
 */
uint16 SensorTag_ProcessEvent( uint8 task_id, uint16 events )
{
  VOID task_id; // OSAL required parameter that isn't used in this function

  if ( events & SYS_EVENT_MSG )
  {
    uint8 *pMsg;

    if ( (pMsg = osal_msg_receive( sensorTag_TaskID )) != NULL )
    {
      sensorTag_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );

      // Release the OSAL message
      VOID osal_msg_deallocate( pMsg );
    }

    // return unprocessed events
    return (events ^ SYS_EVENT_MSG);
  }

  // Handle system reset (long press on side key)
  if ( events & ST_SYS_RESET_EVT )
  {
    if (sysResetRequest)
    {
      HAL_SYSTEM_RESET();
    }
    return ( events ^ ST_SYS_RESET_EVT );
  }

  if ( events & ST_START_DEVICE_EVT )
  {
    // Start the Device
    VOID GAPRole_StartDevice( &sensorTag_PeripheralCBs );

    // Start Bond Manager
    VOID GAPBondMgr_Register( &sensorTag_BondMgrCBs );

    return ( events ^ ST_START_DEVICE_EVT );
  }

  //////////////////////////
  //    IR TEMPERATURE    //
  //////////////////////////
  if ( events & ST_IRTEMPERATURE_READ_EVT )
  {
    if ( irTempEnabled )
    {
      if (HalIRTempStatus() == TMP006_DATA_READY)
      {
        readIrTempData();
        osal_start_timerEx( sensorTag_TaskID, ST_IRTEMPERATURE_READ_EVT, sensorTmpPeriod-TEMP_MEAS_DELAY );
      }
      else if (HalIRTempStatus() == TMP006_OFF)
      {
        HalIRTempTurnOn();
        osal_start_timerEx( sensorTag_TaskID, ST_IRTEMPERATURE_READ_EVT, TEMP_MEAS_DELAY );
      }
    }
    else
    {
      //Turn off Temperatur sensor
      VOID HalIRTempTurnOff();
      VOID resetCharacteristicValue(IRTEMPERATURE_SERV_UUID,SENSOR_DATA,0,IRTEMPERATURE_DATA_LEN);
      VOID resetCharacteristicValue(IRTEMPERATURE_SERV_UUID,SENSOR_CONF,ST_CFG_SENSOR_DISABLE,sizeof ( uint8 ));
    }

    return (events ^ ST_IRTEMPERATURE_READ_EVT);
  }

  //////////////////////////
  //    Accelerometer     //
  //////////////////////////
  if ( events & ST_ACCELEROMETER_SENSOR_EVT )
  {
    if(accConfig != ST_CFG_SENSOR_DISABLE)
    {
      readAccData();
      osal_start_timerEx( sensorTag_TaskID, ST_ACCELEROMETER_SENSOR_EVT, sensorAccPeriod );
    }
    else
    {
      VOID resetCharacteristicValue( ACCELEROMETER_SERV_UUID, SENSOR_DATA, 0, ACCELEROMETER_DATA_LEN );
      VOID resetCharacteristicValue( ACCELEROMETER_SERV_UUID, SENSOR_CONF, ST_CFG_SENSOR_DISABLE, sizeof ( uint8 ));
    }

    return (events ^ ST_ACCELEROMETER_SENSOR_EVT);
  }

  //////////////////////////
  //      Humidity        //
  //////////////////////////
  if ( events & ST_HUMIDITY_SENSOR_EVT )
  {
    if (humiEnabled)
    {
      HalHumiExecMeasurementStep(humiState);
      if (humiState == 2)
      {
        readHumData();
        humiState = 0;
        osal_start_timerEx( sensorTag_TaskID, ST_HUMIDITY_SENSOR_EVT, sensorHumPeriod );
      }
      else
      {
        humiState++;
        osal_start_timerEx( sensorTag_TaskID, ST_HUMIDITY_SENSOR_EVT, HUM_FSM_PERIOD );
      }
    }
    else
    {
      resetCharacteristicValue( HUMIDITY_SERV_UUID, SENSOR_DATA, 0, HUMIDITY_DATA_LEN);
      resetCharacteristicValue( HUMIDITY_SERV_UUID, SENSOR_CONF, ST_CFG_SENSOR_DISABLE, sizeof ( uint8 ));
    }

    return (events ^ ST_HUMIDITY_SENSOR_EVT);
  }

  //////////////////////////
  //      Magnetometer    //
  //////////////////////////
  if ( events & ST_MAGNETOMETER_SENSOR_EVT )
  {
    if(magEnabled)
    {
      if (HalMagStatus() == MAG3110_DATA_READY)
      {
        readMagData();
      }
      else if (HalMagStatus() == MAG3110_OFF)
      {
        HalMagTurnOn();
      }

      osal_start_timerEx( sensorTag_TaskID, ST_MAGNETOMETER_SENSOR_EVT, sensorMagPeriod );
    }
    else
    {
      HalMagTurnOff();
      resetCharacteristicValue( MAGNETOMETER_SERV_UUID, SENSOR_DATA, 0, MAGNETOMETER_DATA_LEN);
      resetCharacteristicValue( MAGNETOMETER_SERV_UUID, SENSOR_CONF, ST_CFG_SENSOR_DISABLE, sizeof ( uint8 ));
    }

    return (events ^ ST_MAGNETOMETER_SENSOR_EVT);
  }

  //////////////////////////
  //        Barometer     //
  //////////////////////////
  if ( events & ST_BAROMETER_SENSOR_EVT )
  {
    if (barEnabled)
    {
      if (barBusy)
      {
        barBusy = FALSE;
        readBarData();
        osal_start_timerEx( sensorTag_TaskID, ST_BAROMETER_SENSOR_EVT, sensorBarPeriod );
      }
      else
      {
        barBusy = TRUE;
        HalBarStartMeasurement();
        osal_start_timerEx( sensorTag_TaskID, ST_BAROMETER_SENSOR_EVT, BAR_FSM_PERIOD );
      }
    }
    else
    {
      resetCharacteristicValue( BAROMETER_SERV_UUID, SENSOR_DATA, 0, BAROMETER_DATA_LEN);
      resetCharacteristicValue( BAROMETER_SERV_UUID, SENSOR_CONF, ST_CFG_SENSOR_DISABLE, sizeof ( uint8 ));
      resetCharacteristicValue( BAROMETER_SERV_UUID, SENSOR_CALB, 0, BAROMETER_CALI_LEN);
    }

    return (events ^ ST_BAROMETER_SENSOR_EVT);
  }

  //////////////////////////
  //      Gyroscope       //
  //////////////////////////
  if ( events & ST_GYROSCOPE_SENSOR_EVT )
  {
    uint8 status;

    status = HalGyroStatus();

    if(gyroEnabled)
    {
      if (status == HAL_GYRO_STOPPED)
      {
        HalGyroSelectAxes(sensorGyroAxes);
        HalGyroTurnOn();
        osal_start_timerEx( sensorTag_TaskID, ST_GYROSCOPE_SENSOR_EVT, GYRO_STARTUP_TIME);
      }
      else
      {
        if(sensorGyroUpdateAxes)
        {
          HalGyroSelectAxes(sensorGyroAxes);
          sensorGyroUpdateAxes = FALSE;
        }

        if (status == HAL_GYRO_DATA_READY)
        {
          readGyroData();
          osal_start_timerEx( sensorTag_TaskID, ST_GYROSCOPE_SENSOR_EVT, sensorGyrPeriod - GYRO_STARTUP_TIME);
        }
        else
        {
          // Gyro needs to be activated;
          HalGyroWakeUp();
          osal_start_timerEx( sensorTag_TaskID, ST_GYROSCOPE_SENSOR_EVT, GYRO_STARTUP_TIME);
        }
      }
    }
    else
    {
      HalGyroTurnOff();
      resetCharacteristicValue( GYROSCOPE_SERV_UUID, SENSOR_DATA, 0, GYROSCOPE_DATA_LEN);
      resetCharacteristicValue( GYROSCOPE_SERV_UUID, SENSOR_CONF, ST_CFG_SENSOR_DISABLE, sizeof( uint8 ));
    }

    return (events ^ ST_GYROSCOPE_SENSOR_EVT);
  }

#if defined ( PLUS_BROADCASTER )
  if ( events & ST_ADV_IN_CONNECTION_EVT )
  {
    uint8 turnOnAdv = TRUE;
    // Turn on advertising while in a connection
    GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &turnOnAdv );

    return (events ^ ST_ADV_IN_CONNECTION_EVT);
  }
#endif // PLUS_BROADCASTER

  // Discard unknown events
  return 0;
}
예제 #29
0
/*********************************************************************
 * @fn      Biscuit_ProcessEvent
 *
 * @brief   Simple BLE Peripheral Application Task event processor.  This function
 *          is called to process all events for the task.  Events
 *          include timers, messages and any other user defined events.
 *
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events - events to process.  This is a bit map and can
 *                   contain more than one event.
 *
 * @return  events not processed
 */
uint16 Biscuit_ProcessEvent( uint8 task_id, uint16 events )
{

  VOID task_id; // OSAL required parameter that isn't used in this function

  if ( events & SYS_EVENT_MSG )
  {
    uint8 *pMsg;

    if ( (pMsg = osal_msg_receive( biscuit_TaskID )) != NULL )
    {
      biscuit_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );

      // Release the OSAL message
      VOID osal_msg_deallocate( pMsg );
    }

    // return unprocessed events
    return (events ^ SYS_EVENT_MSG);
  }

  if ( events & SBP_START_DEVICE_EVT )
  {
    // Start the Device
    VOID GAPRole_StartDevice( &biscuit_PeripheralCBs );

    // Start Bond Manager
    VOID GAPBondMgr_Register( &biscuit_BondMgrCBs );

    // Set timer for first periodic event
    osal_start_timerEx( biscuit_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD );

    return ( events ^ SBP_START_DEVICE_EVT );
  }
  
  if ( events & SBP_RX_TIME_OUT_EVT )
  {
    uint8 data[20];
    uint8 send;
    while(rxLen != 0)
    {
      if(rxLen <= 20)
      {
        send = rxLen;
        rxLen = 0;
      }
      else
      { 
        send = 20;      
        rxLen -= 20;
      }
      for(uint8 i=0; i<send; i++)
      {
        data[i] = RXBuf[rxTail];
        rxTail++;
        if(rxTail == MAX_RX_LEN)
        {
          rxTail = 0;
        }
      }
      TXRX_SetParameter(TX_DATA_CHAR, send, data);
    }

    return (events ^ SBP_RX_TIME_OUT_EVT);
  }

  if ( events & SBP_PERIODIC_EVT )
  {
    // Restart timer
    if ( SBP_PERIODIC_EVT_PERIOD )
    {
      osal_start_timerEx( biscuit_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD );
    }

    // Perform periodic application task
    performPeriodicTask();

    return (events ^ SBP_PERIODIC_EVT);
  }

  // Discard unknown events
  return 0;
}
예제 #30
0
/*********************************************************************
 * @fn      SimpleBLEPeriph(P0 &= 0xFD)eral_ProcessEvent
 *
 * @brief   Simple BLE Peripheral Application Task event processor.  This function
 *          is called to process all events for the task.  Events
 *          include timers, messages and any other user defined events.
 *
 * @param   task_id  - The OSAL assigned task ID.
 * @param   events - events to process.  This is a bit map and can
 *                   contain more than one event.
 *
 * @return  events not processed
 */
uint16 SimpleBLEPeripheral_ProcessEvent( uint8 task_id, uint16 events )
{

  VOID task_id; // OSAL required parameter that isn't used in this function
  uint8 value = 0;
  if ( events & SYS_EVENT_MSG )
  {
    uint8 *pMsg;

    if ( (pMsg = osal_msg_receive( simpleBLEPeripheral_TaskID )) != NULL )
    {
      simpleBLEPeripheral_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );

      // Release the OSAL message
      VOID osal_msg_deallocate( pMsg );
    }

    // return unprocessed events
    return (events ^ SYS_EVENT_MSG);
  }

  if ( events & SBP_START_DEVICE_EVT )
  {
    // Start the Device
    VOID GAPRole_StartDevice( &simpleBLEPeripheral_PeripheralCBs );

    // Start Bond Manager
    VOID GAPBondMgr_Register( &simpleBLEPeripheral_BondMgrCBs );

    // Set timer for first periodic event
    osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_PERIODIC_EVT, advert_internal * 1000);

    return ( events ^ SBP_START_DEVICE_EVT );
  }

  if ( events & SBP_PERIODIC_EVT )
  {
      if (!gOpenDoorStep)
        performPeriodicTask();
      osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_PERIODIC_EVT, advert_internal * 1000);

    return (events ^ SBP_PERIODIC_EVT);
  }

  if(events & SBP_OPENDOOR_DEVICE_EVT)
  {
    switch(gOpenDoorStep)
    {
    case 1:
      //P0.0 ->0
      P0 &= 0xFE;
      DelayMS(20);
      P0 &= 0xFE;
      gOpenDoorStep++;
      osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_OPENDOOR_DEVICE_EVT, 0 );
      break;
    case 2:
      //P0.1 ->1; P0.2 ->0; keep 2s
      //P01_LOW;
      P01_HIGH;
      DelayMS(20);
      //P02_HIGH;
      P02_LOW;
      DelayMS(20);
//      P0 |= 0x02;
//      DelayMS(20);
//      P0 &= 0xFB;
//      DelayMS(20);
      gOpenDoorStep++;
      osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_OPENDOOR_DEVICE_EVT, 500 );
      break;
    case 3:
      //P0.1 ->0; P0.2 ->0; keep 5s
      P0 &= 0xFD;
      DelayMS(20);
      P0 &= 0xFB;
      DelayMS(20);
      gOpenDoorStep++;
      osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_OPENDOOR_DEVICE_EVT, 3500 );
      break;
    case 4:
      //P0.1 ->0; P0.2 ->1; keep 2s
      P0 &= 0xFD;
      DelayMS(20);
      P0 |= 0x04;
      DelayMS(20);
      gOpenDoorStep++;
      osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_OPENDOOR_DEVICE_EVT, 1000 );
      break;
    case 5:
      //P0.0 ->1
      P0 |= 0x01;
      P01_LOW;
      P02_LOW;
      DelayMS(20);
      gOpenDoorStep =0;
      SimpleProfile_SetParameter( SIMPLEPROFILE_CHAR2, sizeof ( uint8 ), &value );
      break;
    default:
      gOpenDoorStep =0;
      break;
    }
    return (events ^ SBP_OPENDOOR_DEVICE_EVT);
  }

#if defined ( PLUS_BROADCASTER )
  if ( events & SBP_ADV_IN_CONNECTION_EVT )
  {
    uint8 turnOnAdv = TRUE;
    // Turn on advertising while in a connection
    GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &turnOnAdv );

    return (events ^ SBP_ADV_IN_CONNECTION_EVT);
  }
#endif // PLUS_BROADCASTER

  // Discard unknown events
  return 0;
}