Beispiel #1
0
/*********************************************************************
 * @fn      HeartRate_battEvt
 *
 * @brief   Event handler for battery service callbacks.
 *
 * @param   event - service event
 *
 * @return  none
 */
static void HeartRate_battEvt(uint8_t event)
{
  if (event == BATT_LEVEL_NOTI_ENABLED)
  {
    // If connected start periodic measurement.
    if (gapProfileState == GAPROLE_CONNECTED)
    {
      Util_startClock(&battPerClock);
    }
  }
  else if (event == BATT_LEVEL_NOTI_DISABLED)
  {
    // Stop periodic measurement.
    Util_stopClock(&battPerClock);
  }
}
Beispiel #2
0
/*********************************************************************
 * @fn      glucoseCtlPntGattMsg()
 *
 * @brief   Handle GATT messages for control point operations.
 *
 * @param   pMsg - GATT message.
 *
 * @return  None.
 */
void glucoseCtlPntGattMsg(gattMsgEvent_t *pMsg)
{ 
  if (pMsg->method == ATT_ERROR_RSP)
  {
     attErrorRsp_t *pRsp = &pMsg->msg.errorRsp;
     
     glucCollClearPending = false;
     LCD_WRITE_STRING("Write Error",  LCD_PAGE0);
     LCD_WRITE_STRING_VALUE("Handle:  ", pRsp->handle, 10, LCD_PAGE1);
     LCD_WRITE_STRING_VALUE("errCode: ", pRsp->errCode, 10, LCD_PAGE2);
  }
  else if (pMsg->method == ATT_WRITE_RSP)
  {
    // start procedure timer
    Util_stopClock(&procTimeoutClock);
    Util_startClock(&procTimeoutClock);
  }
  
  glucCollWritePending = false;
}
Beispiel #3
0
/*********************************************************************
 * @fn      HeartRate_heartRateEvt
 *
 * @brief   event handler for heart rate service callbacks.
 *
 * @param   event - service event
 *
 * @return  none
 */
static void HeartRate_heartRateEvt(uint8_t event)
{
  if (event == HEARTRATE_MEAS_NOTI_ENABLED)
  {
    // If connected start periodic measurement.
    if (gapProfileState == GAPROLE_CONNECTED)
    {
      Util_startClock(&measPerClock);
    }
  }
  else if (event == HEARTRATE_MEAS_NOTI_DISABLED)
  {
    // Stop periodic measurement.
    Util_stopClock(&measPerClock);
  }
  else if (event == HEARTRATE_COMMAND_SET)
  {
    // Reset energy expended.
    heartRateEnergyLvl = 0;
  }
}
/*******************************************************************************
 * @fn      appStateSet
 *
 * @brief   Set the application state
 *
 */
static void appStateSet(uint8_t newState)
{
  if (newState == APP_STATE_OFF)
  {
    appState = APP_STATE_OFF;

    SensorMpu9250_enable(0);
    SensorMpu9250_powerOff();

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

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

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

    if (newState == APP_STATE_ACTIVE)
    {
      // Start scheduled data measurements
      Util_startClock(&periodicClock);
    }
    else
    {
      // Stop scheduled data measurements
      Util_stopClock(&periodicClock);
    }
  }
}
/*********************************************************************
 * @fn      SensorTagKeys_processEvent
 *
 * @brief   SensorTag Keys event processor.
 *
 * @param   none
 *
 * @return  none
 */
void SensorTagKeys_processEvent(void)
{
  static uint8_t current_keys = 0;

  // Factory reset by six second simultaneous key press
  if (event & SK_EVT_FACTORY_RESET)
  {
      event &= ~SK_EVT_FACTORY_RESET;

      // Indicate that we're entering factory reset
      SensorTagIO_blinkLed(IOID_RED_LED, 10);

      // Apply factory image and reboot
      SensorTagFactoryReset_applyFactoryImage();
  }

  // Disconnect on three seconds press on the power switch (right key)
  if (event & SK_EVT_DISCONNECT)
  {
      event &= ~SK_EVT_DISCONNECT;
      if (gapProfileState == GAPROLE_CONNECTED)
      {
        processGapStateChange();
      }
  }

  // Set the value of the keys state to the Simple Keys Profile;
  // This will send out a notification of the keys state if enabled
  if (current_keys != keys)
  {
    SK_SetParameter(SK_KEY_ATTR, sizeof(uint8_t), &keys);

    // Insert key state into advertising data
    if (gapProfileState == GAPROLE_ADVERTISING)
    {
      SensorTag_updateAdvertisingData(keys);
    }

    // Check if right key was pressed
    if ((current_keys & SK_KEY_RIGHT)!=0 && (keys & SK_KEY_RIGHT)==0)
    {
      if (gapProfileState != GAPROLE_CONNECTED)
      {
        // Not connected; change state immediately (power/right button)
        processGapStateChange();
      }
    }


    // Has a key been pressed ?
    if ((keys & SK_PUSH_KEYS) && (current_keys == 0))
    {
        if (!Util_isActive(&periodicClock))
        {
            Util_startClock(&periodicClock);
            keyTimer = 0;
        }
    }
  }

  current_keys = keys;
}
void userStartClock10ms(void)
{
	Util_startClock(&periodicClock_10ms);
}
/*********************************************************************
 * @fn      RunningSensor_processServiceEvt
 *
 * @brief   Handler RSC service callback.
 *
 * @param   event       - service event
 * @param   newCummVal  - new total distance data if specified by event.  
 *                        0 otherwise.
 *
 * @return  SUCCESS if operation successful. FAILURE, otherwise.
 */
static bStatus_t RunningSensor_processServiceEvt(uint8_t event,
                                                 uint32_t newCummVal)
{
  bStatus_t status = SUCCESS;

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

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

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

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

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

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

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

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

    default:
      // Do nothing.
      break;
  }

  return (status);
}
/*********************************************************************
 * @fn      simpleTopology_processRoleEvent
 *
 * @brief   Multi role event processing function.
 *
 * @param   pEvent - pointer to event structure
 *
 * @return  none
 */
static void simpleTopology_processRoleEvent(gapMultiRoleEvent_t *pEvent)
{
  switch (pEvent->gap.opcode)
  {
    case GAP_DEVICE_INIT_DONE_EVENT:  
      {
        maxPduSize = pEvent->initDone.dataPktLen;
        
        LCD_WRITE_STRING("Connected to 0", LCD_PAGE0);
        LCD_WRITE_STRING(Util_convertBdAddr2Str(pEvent->initDone.devAddr),
                         LCD_PAGE1);
        LCD_WRITE_STRING("Initialized", LCD_PAGE2);

        DevInfo_SetParameter(DEVINFO_SYSTEM_ID, DEVINFO_SYSTEM_ID_LEN, pEvent->initDone.devAddr);    
      }
      break;

      case GAP_MAKE_DISCOVERABLE_DONE_EVENT:
        {
          if (gapRoleNumLinks(GAPROLE_ACTIVE_LINKS) > 0)
          {
            LCD_WRITE_STRING("Advertising", LCD_PAGE2);
          }
          else
          {
            LCD_WRITE_STRING("Advertising", LCD_PAGE2);
          }
        }
      break;

      case GAP_END_DISCOVERABLE_DONE_EVENT:
        {
          if (gapRoleNumLinks(GAPROLE_AVAILABLE_LINKS) > 0)
          {
            LCD_WRITE_STRING("Ready to Advertise", LCD_PAGE2);
          }
          else
          {
            LCD_WRITE_STRING("Can't Adv : No links", LCD_PAGE2);
          }
        }
      break;      
      
    case GAP_DEVICE_INFO_EVENT:
      {
        // if filtering device discovery results based on service UUID
        if (DEFAULT_DEV_DISC_BY_SVC_UUID == TRUE)
        {
          if (simpleTopology_findSvcUuid(SIMPLEPROFILE_SERV_UUID,
                                           pEvent->deviceInfo.pEvtData,
                                           pEvent->deviceInfo.dataLen))
          {
            simpleTopology_addDeviceInfo(pEvent->deviceInfo.addr,
                                           pEvent->deviceInfo.addrType);
          }
        }
      }
      break;
      
    case GAP_DEVICE_DISCOVERY_EVENT:
      {
        // discovery complete
        scanningStarted = FALSE;

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

        // initialize scan index to last device
        scanIdx = scanRes;
      }
      break;

    case GAP_LINK_ESTABLISHED_EVENT:
      {
        if (pEvent->gap.hdr.status == SUCCESS)
        {
          LCD_WRITE_STRING("Connected!", LCD_PAGE3);
          LCD_WRITE_STRING_VALUE("Connected to ", gapRoleNumLinks(GAPROLE_ACTIVE_LINKS) ,10, LCD_PAGE0);
          
          //update state
          connecting_state = 0;
          //store connection handle
          connHandle = pEvent->linkCmpl.connectionHandle;

          //if we're not advertising, attempt to turn advertising back on
          uint8_t adv;
          GAPRole_GetParameter(GAPROLE_ADVERT_ENABLED, &adv, NULL);
          if (adv == 1) //connected and advertising
          {
            if (gapRoleNumLinks(GAPROLE_AVAILABLE_LINKS) > 0)
            {
              LCD_WRITE_STRING("Advertising", LCD_PAGE2);
            }
            else //no available links
            {
              LCD_WRITE_STRING("Can't adv: no links", LCD_PAGE2);
            }
          }
          else //not currently advertising
          {
            LCD_WRITE_STRING("Ready to Advertise", LCD_PAGE2);
            //attempt to turn advertising back o
            uint8_t advertEnabled = TRUE;        
            uint8_t stat = GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8_t), &advertEnabled, NULL);
            if (stat == bleNoResources) //no more links
            {
              LCD_WRITE_STRING("Can't adv: no links", LCD_PAGE2);
            }
            else if (stat == SUCCESS) //turning advertising back on
            {
              LCD_WRITE_STRING("Advertising", LCD_PAGE2);
            }
            else
            {
              while(1);
            }
          }
          
          // Print last connected device
          LCD_WRITE_STRING("", LCD_PAGE4);
          LCD_WRITE_STRING(Util_convertBdAddr2Str(pEvent->linkCmpl.devAddr), LCD_PAGE5 );                         

          // initiate service discovery
          Util_startClock(&startDiscClock);
        }
        else
        {
          connHandle = GAP_CONNHANDLE_INIT;        
          discState = BLE_DISC_STATE_IDLE;
          
          LCD_WRITE_STRING("Connect Failed", LCD_PAGE4);
          LCD_WRITE_STRING_VALUE("Reason:", pEvent->gap.hdr.status, 10, 
                                 LCD_PAGE3);
        }
      }
      break;

    case GAP_LINK_TERMINATED_EVENT:
      {
        connHandle = GAP_CONNHANDLE_INIT;      
        discState = BLE_DISC_STATE_IDLE;
  
        uint8_t i;
        for (i=0; i < MAX_NUM_BLE_CONNS; i++)
        {
          if (multiConnInfo[i].gapRole_ConnectionHandle == GAPROLE_CONN_JUST_TERMINATED)
          {
            //clear screen, reset discovery info, and return to main menu
            multiConnInfo[i].gapRole_ConnectionHandle = INVALID_CONNHANDLE;
            charHdl[i] = 0;
            LCD_WRITE_STRING_VALUE("Connected to ", gapRoleNumLinks(GAPROLE_ACTIVE_LINKS) ,10, LCD_PAGE0);
            LCD_WRITE_STRING("Disconnected!", LCD_PAGE5);
            LCD_WRITE_STRING("Main Menu", LCD_PAGE3);
            LCDmenu = MAIN_MENU;
          }
          if ((gapRoleNumLinks(GAPROLE_ACTIVE_LINKS) == (MAX_NUM_BLE_CONNS-1))) //now we can advertise again
          {
            LCD_WRITE_STRING("Ready to Advertise", LCD_PAGE2);
          }
        }        
      }
      break;

    case GAP_LINK_PARAM_UPDATE_EVENT:
      {
        LCD_WRITE_STRING_VALUE("Param Update:", pEvent->linkUpdate.status,
                                10, LCD_PAGE2);
      }
      break;
      
    default:
      break;
  }
}
Beispiel #9
0
/*******************************************************************************
 * @fn      SensorTag_processStateChangeEvt
 *
 * @brief   Process a pending GAP Role state change event.
 *
 * @param   newState - new state
 *
 * @return  none
 */
static void SensorTag_processStateChangeEvt(gaprole_States_t newState)
{
#ifdef PLUS_BROADCASTER
  static bool firstConnFlag = false;
#endif // PLUS_BROADCASTER

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

      SensorTag_blinkLed(Board_LED2, 5);

      GAPRole_GetParameter(GAPROLE_BD_ADDR, ownAddress);

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

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

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

      DevInfo_SetParameter(DEVINFO_SYSTEM_ID, DEVINFO_SYSTEM_ID_LEN, systemId);
      LCD_WRITES_STATUS("Initialized");
    }
    break;

  case GAPROLE_ADVERTISING:
    // Start the clock
    if (!Util_isActive(&periodicClock))
    {
      Util_startClock(&periodicClock);
    }

    // Make sure key presses are not stuck
    sensorTag_updateAdvertisingData(0);

    LCD_WRITES_STATUS("Advertising");
    break;

  case GAPROLE_CONNECTED:
    {
      // Start the clock
      if (!Util_isActive(&periodicClock))
      {
        Util_startClock(&periodicClock);
      }

      // Turn of LEDs and buzzer
      PIN_setOutputValue(hGpioPin, Board_LED1, Board_LED_OFF);
      PIN_setOutputValue(hGpioPin, Board_LED2, Board_LED_OFF);
      PIN_setOutputValue(hGpioPin, Board_BUZZER, Board_BUZZER_OFF);
#ifdef FEATURE_OAD
      SensorTagConnectionControl_update();
#endif

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

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

  case GAPROLE_CONNECTED_ADV:
    break;

  case GAPROLE_WAITING:
  case GAPROLE_WAITING_AFTER_TIMEOUT:
    SensorTag_resetAllSensors();
    LCD_WRITES_STATUS("Waiting...");
    break;

  case GAPROLE_ERROR:
    SensorTag_resetAllSensors();
    PIN_setOutputValue(hGpioPin,Board_LED1, Board_LED_ON);
    LCD_WRITES_STATUS("Error");
    break;

  default:
    break;
  }

  gapProfileState = newState;
}
Beispiel #10
0
/*********************************************************************
 * @fn      Thermometer_processStateChangeEvt
 *
 * @brief   Notification from the profile of a state change.
 *
 * @param   newState - new state
 *
 * @return  none
 */
static void Thermometer_processStateChangeEvt(gaprole_States_t newState)
{
  // If connected
  if (newState == GAPROLE_CONNECTED)
  {
    // Get connection handle.
    GAPRole_GetParameter(GAPROLE_CONNHANDLE, &thermometer_connHandle);

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

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

    // Stop intermediate timers.
    Util_stopClock(&perIMeasClock);
    Util_stopClock(&perMeasClock);
  
    // Re-initialize state variables.
    servDiscState = DISC_IDLE;
    servDiscPostponed = FALSE;
    
    // Invalidate the connection handle.
    thermometer_connHandle = Time_connHandle = INVALID_CONNHANDLE;
  }
  // If started
  else if (newState == GAPROLE_STARTED)
  {
    // Time module configuration have not been set.
    Time_configDone = FALSE;
    
    // Initialize time clock.
    Time_clockInit();
  }
  
  // Update to new state.
  gapProfileState = newState;
}
Beispiel #11
0
/*********************************************************************
 * @fn      SimpleBLEPeripheral_taskFxn
 *
 * @brief   Application task entry point for the Simple BLE Peripheral.
 *
 * @param   a0, a1 - not used.
 *
 * @return  None.
 */
static void SimpleBLEPeripheral_taskFxn(UArg a0, UArg a1)
{
  // Initialize application
  SimpleBLEPeripheral_init();

  // Application main loop
  for (;;)
  {
    // Waits for a signal to the semaphore associated with the calling thread.
    // Note that the semaphore associated with a thread is signaled when a
    // message is queued to the message receive queue of the thread or when
    // ICall_signal() function is called onto the semaphore.
    ICall_Errno errno = ICall_wait(ICALL_TIMEOUT_FOREVER);

    if (errno == ICALL_ERRNO_SUCCESS)
    {
      ICall_EntityID dest;
      ICall_ServiceEnum src;
      ICall_HciExtEvt *pMsg = NULL;

      if (ICall_fetchServiceMsg(&src, &dest,
                                (void **)&pMsg) == ICALL_ERRNO_SUCCESS)
      {
        uint8 safeToDealloc = TRUE;

        if ((src == ICALL_SERVICE_CLASS_BLE) && (dest == selfEntity))
        {
          ICall_Stack_Event *pEvt = (ICall_Stack_Event *)pMsg;

          // Check for BLE stack events first
          if (pEvt->signature == 0xffff)
          {
            if (pEvt->event_flag & SBP_CONN_EVT_END_EVT)
            {
              // Try to retransmit pending ATT Response (if any)
              SimpleBLEPeripheral_sendAttRsp();
            }
          }
          else
          {
            // Process inter-task message
            safeToDealloc = SimpleBLEPeripheral_processStackMsg((ICall_Hdr *)pMsg);
          }
        }

        if (pMsg && safeToDealloc)
        {
          ICall_freeMsg(pMsg);
        }
      }

      // If RTOS queue is not empty, process app message.
      while (!Queue_empty(appMsgQueue))
      {
        sbpEvt_t *pMsg = (sbpEvt_t *)Util_dequeueMsg(appMsgQueue);
        if (pMsg)
        {
          // Process message.
          SimpleBLEPeripheral_processAppMsg(pMsg);

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

    if (events & SBP_PERIODIC_EVT)
    {
      events &= ~SBP_PERIODIC_EVT;

      Util_startClock(&periodicClock);

      // Perform periodic application task
      SimpleBLEPeripheral_performPeriodicTask();
    }

#ifdef FEATURE_OAD
    while (!Queue_empty(hOadQ))
    {
      oadTargetWrite_t *oadWriteEvt = Queue_dequeue(hOadQ);

      // Identify new image.
      if (oadWriteEvt->event == OAD_WRITE_IDENTIFY_REQ)
      {
        OAD_imgIdentifyWrite(oadWriteEvt->connHandle, oadWriteEvt->pData);
      }
      // Write a next block request.
      else if (oadWriteEvt->event == OAD_WRITE_BLOCK_REQ)
      {
        OAD_imgBlockWrite(oadWriteEvt->connHandle, oadWriteEvt->pData);
      }

      // Free buffer.
      ICall_free(oadWriteEvt);
    }
#endif //FEATURE_OAD
  }
}
Beispiel #12
0
/*********************************************************************
 * @fn      SimpleBLEPeripheral_processStateChangeEvt
 *
 * @brief   Process a pending GAP Role state change event.
 *
 * @param   newState - new state
 *
 * @return  None.
 */
static void SimpleBLEPeripheral_processStateChangeEvt(gaprole_States_t newState)
{
#ifdef PLUS_BROADCASTER
  static bool firstConnFlag = false;
#endif // PLUS_BROADCASTER

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

        GAPRole_GetParameter(GAPROLE_BD_ADDR, ownAddress);

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

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

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

        DevInfo_SetParameter(DEVINFO_SYSTEM_ID, DEVINFO_SYSTEM_ID_LEN, systemId);

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

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

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

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

        advertEnabled = TRUE;

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

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

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

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

        Util_startClock(&periodicClock);

        numActive = linkDB_NumActive();

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

          GAPRole_GetParameter(GAPROLE_CONN_BD_ADDR, peerAddress);

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

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

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

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

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

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

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

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

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

    case GAPROLE_WAITING_AFTER_TIMEOUT:
      SimpleBLEPeripheral_freeAttRsp(bleNotConnected);

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

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

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

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

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

  // Update the state
  //gapProfileState = newState;
}
/*********************************************************************
 * @fn      RunningSensor_processStateChangeEvt
 *
 * @brief   Notification from the profile of a state change.
 *
 * @param   newState - new state
 *
 * @return  none
 */
static void RunningSensor_processStateChangeEvt(gaprole_States_t newState)
{
  // If connected
  if (newState == GAPROLE_CONNECTED)
  {
    // Get the connection handle.
    GAPRole_GetParameter(GAPROLE_CONNHANDLE, &gapConnHandle);

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

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

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

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

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

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

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

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

      whiteListUsed = TRUE;

      sensorUsingWhiteList = FALSE;
    }

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

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

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

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

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

    DevInfo_SetParameter(DEVINFO_SYSTEM_ID, DEVINFO_SYSTEM_ID_LEN, systemId);
  }

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

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

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

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

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

        GAPBondMgr_GetParameter(GAPBOND_BOND_COUNT, &bondCount);

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

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

          sensorUsingWhiteList = TRUE;
        }
      }

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

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

      motion = motionCycle[motionIdx];
    }
  }
}
/*********************************************************************
 * @fn      RunningSensor_taskFxn
 *
 * @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   a0, a1 - not used.
 *
 * @return  none
 */
void RunningSensor_taskFxn(UArg a0, UArg a1)
{
  // Initialize the application.
  RunningSensor_init();
  
  // Application main loop.
  for (;;)
  {
    // Waits for a signal to the semaphore associated with the calling thread.
    // Note that the semaphore associated with a thread is signaled when a
    // message is queued to the message receive queue of the thread or when
    // ICall_signal() function is called onto the semaphore.
    ICall_Errno errno = ICall_wait(ICALL_TIMEOUT_FOREVER);

    if (errno == ICALL_ERRNO_SUCCESS)
    {
      ICall_EntityID dest;
      ICall_ServiceEnum src;
      ICall_HciExtEvt *pMsg = NULL;
      
      if (ICall_fetchServiceMsg(&src, &dest, 
                                (void **)&pMsg) == ICALL_ERRNO_SUCCESS)
      {
        if ((src == ICALL_SERVICE_CLASS_BLE) && (dest == selfEntity))
        {
          // Process inter-task message.
          RunningSensor_processStackMsg((ICall_Hdr *)pMsg);
        }
                
        if (pMsg)
        {
          ICall_freeMsg(pMsg);
        }
      }

      // If RTOS queue is not empty, process app message.
      while (!Queue_empty(appMsgQueue))
      {
        rscEvt_t *pMsg = (rscEvt_t *)Util_dequeueMsg(appMsgQueue);
        if (pMsg)
        {
          // Process message.
          RunningSensor_processAppMsg(pMsg);
          
          // Free the space from the message.
          ICall_free(pMsg);
        }
      }
    }

    if (events)
    { 
      // Running sensor periodic event.
      if (events & RSC_PERIODIC_EVT)
      {
        events &= ~RSC_PERIODIC_EVT;
        
        // Perform periodic sensor's periodic task.
        RunningSensor_periodicTask();
      }

      // Parameter update event.
      if (events & RSC_CONN_PARAM_UPDATE_EVT)
      {
        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);

#if USING_NEGLECT_TIMEOUT
        // Assuming service discovery complete, start neglect timer.
        Util_startClock(&neglectClock);
#endif //USING_NEGLECT_TIMEOUT
      }

#if USING_NEGLECT_TIMEOUT
      // Neglect timer expired.
      if (events & RSC_NEGLECT_TIMEOUT_EVT)
      {
        events &= ~RSC_NEGLECT_TIMEOUT_EVT;
        
        // No user input, terminate connection.
        GAPRole_TerminateConnection();
      }
#endif //USING_NEGLECT_TIMEOUT
      
      // Soft reset event.
      if (events & RSC_RESET_EVT)
      {
        events &= ~RSC_RESET_EVT;
        
        RunningSensor_handleResetEvt();
      }
    }
  }
}
Beispiel #16
0
/*******************************************************************************
 * @fn      SensorTag_taskFxn
 *
 * @brief   Application task entry point for the SensorTag
 *
 * @param   a0, a1 (not used)
 *
 * @return  none
 */
static void SensorTag_taskFxn(UArg a0, UArg a1)
{
  // Initialize application
  SensorTag_init();

  // Application main loop
  for (;;)
  {
    // Waits for a signal to the semaphore associated with the calling thread.
    // Note that the semaphore associated with a thread is signalled when a
    // message is queued to the message receive queue of the thread or when
    // ICall_signal() function is called onto the semaphore.
    ICall_Errno errno = ICall_wait(ICALL_TIMEOUT_FOREVER);

    if (errno == ICALL_ERRNO_SUCCESS)
    {
      ICall_EntityID dest;
      ICall_ServiceEnum src;
      ICall_HciExtEvt *pMsg = NULL;

      if (ICall_fetchServiceMsg(&src, &dest,
                                (void **)&pMsg) == ICALL_ERRNO_SUCCESS)
      {
        if ((src == ICALL_SERVICE_CLASS_BLE) && (dest == selfEntity))
        {
          // Process inter-task message
          SensorTag_processStackMsg((ICall_Hdr *)pMsg);
        }

        if (pMsg)
        {
          ICall_freeMsg(pMsg);
        }
      }

      // If RTOS queue is not empty, process app message.
      while (!Queue_empty(appMsgQueue))
      {
        stEvt_t *pMsg = (stEvt_t *)Util_dequeueMsg(appMsgQueue);
        if (pMsg)
        {
          // Process message.
          SensorTag_processAppMsg(pMsg);

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

      // Process new data if available
      SensorTagKeys_processEvent();
      SensorTagOpt_processSensorEvent();
      SensorTagMov_processSensorEvent();
    }

    if (!!(events & ST_PERIODIC_EVT))
    {
      events &= ~ST_PERIODIC_EVT;

      if (gapProfileState == GAPROLE_CONNECTED
          || gapProfileState == GAPROLE_ADVERTISING)
      {
        Util_startClock(&periodicClock);
      }

      // Perform periodic application task
      if (gapProfileState == GAPROLE_CONNECTED)
      {
        SensorTag_performPeriodicTask();
      }

      // Blink green LED when advertising
      if (gapProfileState == GAPROLE_ADVERTISING)
      {
        SensorTag_blinkLed(Board_LED2,1);
        #ifdef FEATURE_LCD
        SensorTag_displayBatteryVoltage();
        #endif
      }
    }

    #ifdef FEATURE_OAD
    while (!Queue_empty(hOadQ))
    {
      oadTargetWrite_t *oadWriteEvt = Queue_dequeue(hOadQ);

      // Identify new image.
      if (oadWriteEvt->event == OAD_WRITE_IDENTIFY_REQ)
      {
        OAD_imgIdentifyWrite(oadWriteEvt->connHandle,
                             oadWriteEvt->pData);
      }
      // Write a next block request.
      else if (oadWriteEvt->event == OAD_WRITE_BLOCK_REQ)
      {
        OAD_imgBlockWrite(oadWriteEvt->connHandle,
                          oadWriteEvt->pData);
      }

      // Free buffer.
      ICall_free(oadWriteEvt);
    }
    #endif //FEATURE_OAD
  } // task loop
}
Beispiel #17
0
/*********************************************************************
 * @fn      trainingTag_taskFxn
 *
 * @brief   Application task entry point for the Simple BLE Peripheral.
 *
 * @param   a0, a1 - not used.
 *
 * @return  None.
 */
static void trainingTag_taskFxn(UArg a0, UArg a1)
{
  // Initialize application
  trainingTag_init();

  // Application main loop
  for (;;)
  {
    // Waits for a signal to the semaphore associated with the calling thread.
    // Note that the semaphore associated with a thread is signaled when a
    // message is queued to the message receive queue of the thread or when
    // ICall_signal() function is called onto the semaphore.
    ICall_Errno errno = ICall_wait(ICALL_TIMEOUT_FOREVER);

    if (errno == ICALL_ERRNO_SUCCESS)
    {
      ICall_EntityID dest;
      ICall_ServiceEnum src;
      ICall_HciExtEvt *pMsg = NULL;

      if (ICall_fetchServiceMsg(&src, &dest,
                                (void **)&pMsg) == ICALL_ERRNO_SUCCESS)
      {
        if ((src == ICALL_SERVICE_CLASS_BLE) && (dest == selfEntity))
        {
          // Process inter-task message
          trainingTag_processStackMsg((ICall_Hdr *)pMsg);
        }

        if (pMsg)
        {
          ICall_freeMsg(pMsg);
        }
      }

      // If RTOS queue is not empty, process app message.
      if (!Queue_empty(appMsgQueue))
      {
        tTagEvt_t *pMsg = (tTagEvt_t *)Util_dequeueMsg(appMsgQueue);
        if (pMsg)
        {
          // Process message.
          trainingTag_processAppMsg(pMsg);

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

    if (events & TTG_PERIODIC_EVT)
    {
      events &= ~TTG_PERIODIC_EVT;

      Util_startClock(&periodicClock);

      // Perform periodic application task
      trainingTag_performPeriodicTask();
    }
  }
}
/*********************************************************************
 * @fn      glucCollCentral_processRoleEvent
 *
 * @brief   Central event callback function.
 *
 * @param   pEvent - pointer to event structure
 *
 * @return  TRUE if safe to deallocate event message, FALSE otherwise.
 */
static uint8_t glucCollCentral_processRoleEvent(gapCentralRoleEvent_t *pEvent)
{
  switch (pEvent->gap.opcode)
  {
    case GAP_DEVICE_INIT_DONE_EVENT:  
      {
        LCD_WRITE_STRING("Gluc. Collector", LCD_PAGE0);
        LCD_WRITE_STRING(Util_convertBdAddr2Str(pEvent->initDone.devAddr), 
                         LCD_PAGE1);
      }
      break;

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

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

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

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

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

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

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

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

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

        // stop procedure timer
        Util_stopClock(&procTimeoutClock);

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

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

    default:
      break;
  }

  return (TRUE);
}
Beispiel #19
0
/*********************************************************************
 * @fn      trainingTag_processStateChangeEvt
 *
 * @brief   Process a pending GAP Role state change event.
 *
 * @param   newState - new state
 *
 * @return  None.
 */
static void trainingTag_processStateChangeEvt(gaprole_States_t newState)
{
  switch ( newState )
  {
    case GAPROLE_STARTED:
      {
        uint8_t ownAddress[B_ADDR_LEN];
        uint8_t systemId[DEVINFO_SYSTEM_ID_LEN];

        GAPRole_GetParameter(GAPROLE_BD_ADDR, ownAddress);

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

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

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

        DevInfo_SetParameter(DEVINFO_SYSTEM_ID, DEVINFO_SYSTEM_ID_LEN, systemId);

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

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

    case GAPROLE_CONNECTED:
      {
        uint8_t peerAddress[B_ADDR_LEN];

        GAPRole_GetParameter(GAPROLE_CONN_BD_ADDR, peerAddress);

        Util_startClock(&periodicClock);

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

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

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

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

    case GAPROLE_WAITING:
      Util_stopClock(&periodicClock);

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

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

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

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

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

  // Update the state
  //gapProfileState = newState;
}
/*******************************************************************************
 * @fn      userAppPro
 *
 * @brief   user Application event process
 *
 * @param   evnet
 *
 * @return  none
 */
void userAppPro(void)
{
	if (userEvents & USER_10MS_EVT)
	{
		userEvents &= ~USER_10MS_EVT;
		
		Util_startClock(&periodicClock_10ms);
		
		KEY_Scan_10ms();
		
		ChangeTime10mSec();

		Pollint100mSec();
	}

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

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

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

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

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

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

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

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

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

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

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

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

    default:
      // Do nothing.
      break;
  }
}