/*********************************************************************
 * @fn      DualImageConcept_processStateChangeEvt
 *
 * @brief   Process a pending GAP Role state change event.
 *
 * @param   newState - new state
 *
 * @return  None.
 */
static void DualImageConcept_processStateChangeEvt(gaprole_States_t newState)
{
  switch ( newState )
  {
    case GAPROLE_STARTED:
      {
        uint8_t ownAddress[B_ADDR_LEN];

        GAPRole_GetParameter(GAPROLE_BD_ADDR, ownAddress);

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

    case GAPROLE_CONNECTED:
      {
        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));
      }
      break;

    case GAPROLE_WAITING: 
      Display_print0(dispHandle, 2, 0, "Disconnected");

      // Clear remaining lines
      Display_clearLines(dispHandle, 3, 5);
      break;
      
    case GAPROLE_WAITING_AFTER_TIMEOUT:
      Display_print0(dispHandle, 2, 0, "Timed Out");
      
      // Clear remaining lines
      Display_clearLines(dispHandle, 3, 5);
      break;
      
    case GAPROLE_ERROR:
      break;
      
    default:
      break;
  }
}
Example #2
0
/*********************************************************************
 * @fn      SimpleBLECentral_processRoleEvent
 *
 * @brief   Central role event processing function.
 *
 * @param   pEvent - pointer to event structure
 *
 * @return  none
 */
static void SimpleBLEPeripheralObserver_processRoleEvent(gapPeripheralObserverRoleEvent_t *pEvent)
{
  switch (pEvent->gap.opcode)
  {

    case GAP_DEVICE_INFO_EVENT:
      {
        //Print scan response data otherwise advertising data
        if(pEvent->deviceInfo.eventType == GAP_ADRPT_SCAN_RSP)
        {         
          Display_print1(dispHandle, 4, 0, "Scan Response Addr: %s", Util_convertBdAddr2Str(pEvent->deviceInfo.addr));
          Display_print1(dispHandle, 5, 0, "Scan Response Data: %s", Util_convertBytes2Str(pEvent->deviceInfo.pEvtData, pEvent->deviceInfo.dataLen));
        }
        else
        {
          deviceInfoCnt++;
          Display_print2(dispHandle, 6, 0, "Advertising Addr: %s Advertising Type: %s", Util_convertBdAddr2Str(pEvent->deviceInfo.addr), AdvTypeStrings[pEvent->deviceInfo.eventType]);
          Display_print1(dispHandle, 7, 0, "Advertising Data: %s", Util_convertBytes2Str(pEvent->deviceInfo.pEvtData, pEvent->deviceInfo.dataLen));
        }
        
        ICall_free(pEvent->deviceInfo.pEvtData);
        ICall_free(pEvent);
      }
      break;

    case GAP_DEVICE_DISCOVERY_EVENT:
      {
        // discovery complete
        scanningStarted = FALSE;
        deviceInfoCnt = 0;

        //Display_print0(dispHandle, 7, 0, "GAP_DEVICE_DISC_EVENT");
        Display_print1(dispHandle, 5, 0, "Devices discovered: %d", pEvent->discCmpl.numDevs);
        Display_print0(dispHandle, 4, 0, "Scanning Off");

        ICall_free(pEvent->discCmpl.pDevList);
        ICall_free(pEvent);

      }
      break;

    default:
      break;
  }
}
Example #3
0
/*********************************************************************
 * @fn      SimpleBLEBroadcaster_processStateChangeEvt
 *
 * @brief   Notification from the profile of a state change.
 *
 * @param   newState - new state
 *
 * @return  none
 */
static void SimpleBLEBroadcaster_processStateChangeEvt(gaprole_States_t newState)
{
  switch (newState)
  {
    case GAPROLE_STARTED:
      {
        uint8 ownAddress[B_ADDR_LEN];
        
        GAPRole_GetParameter(GAPROLE_BD_ADDR, ownAddress);
        
        // Display device address 
        LCD_WRITE_STRING(Util_convertBdAddr2Str(ownAddress), LCD_PAGE1);
        LCD_WRITE_STRING("Initialized", LCD_PAGE2);
      }
      break;
      
    case GAPROLE_ADVERTISING:
      {
        LCD_WRITE_STRING("Advertising", LCD_PAGE2);        
      }
      break;

    case GAPROLE_WAITING:
      {
        LCD_WRITE_STRING("Waiting", LCD_PAGE2);       
      }
      break;          

    case GAPROLE_ERROR:
      {
        LCD_WRITE_STRING("Error", LCD_PAGE2);         
      }
      break;      
      
    default:
      {
        LCD_WRITE_STRING("", LCD_PAGE2);
      }
      break; 
  }
}
Example #4
0
/*********************************************************************
 * @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;
  }
}
Example #5
0
/*********************************************************************
 * @fn      simpleTopology_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:
 *                 HAL_KEY_SW_2
 *                 HAL_KEY_SW_1
 *
 * @return  none
 */
static void simpleTopology_handleKeys(uint8_t shift, uint8_t keys)
{
  (void)shift;  // Intentionally unreferenced parameter
  
  if (LCDmenu == MAIN_MENU)
  {
    if (keys & KEY_LEFT)  //show discovery results
    {
      selectKey = DISCOVERED_DEVICES;
      
      // If discovery has occurred and a device was found
      if (!scanningStarted && scanRes > 0)
      {
        // Increment index of current result (with wraparound)
        scanIdx++;
        if (scanIdx >= scanRes)
        {
          scanIdx = 0;
        }
        
        LCD_WRITE_STRING_VALUE("Device", (scanIdx + 1), 10, LCD_PAGE3);
        LCD_WRITE_STRING(Util_convertBdAddr2Str(devList[scanIdx].addr), LCD_PAGE4);
      }
      return;
    }
    if (keys & KEY_UP)  //Scan for devices
    {
      // Start or stop discovery
      if (gapRoleNumLinks(GAPROLE_AVAILABLE_LINKS) > 0) //if we can connect to another device
      {
        if (!scanningStarted) //if we're not already scanning
        {
          scanningStarted = TRUE;
          scanRes = 0;
          
          LCD_WRITE_STRING("Discovering...", LCD_PAGE3);
          LCD_WRITE_STRING("", LCD_PAGE4);
          LCD_WRITE_STRING("", LCD_PAGE6);
          
          GAPRole_StartDiscovery(DEFAULT_DISCOVERY_MODE,
                                 DEFAULT_DISCOVERY_ACTIVE_SCAN,
                                 DEFAULT_DISCOVERY_WHITE_LIST);      
        }
        else //cancel scanning
        {
          LCD_WRITE_STRING("Discovery Cancelled", LCD_PAGE3);
          GAPRole_CancelDiscovery();
          scanningStarted = FALSE;
        }
      }
      else // can't add more links at this time
      {
        LCD_WRITE_STRING("Can't scan:no links ", LCD_PAGE3);
      }
      return;
    }
    if (keys & KEY_RIGHT)  // turn advertising on / off
    {
      uint8_t adv;
      uint8_t adv_status;
      GAPRole_GetParameter(GAPROLE_ADVERT_ENABLED, &adv_status, NULL);
      if (adv_status) //turn off
      {
        adv = FALSE;
        GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8_t), &adv, NULL);
      }
      else //turn on
      {
        adv = TRUE;
        GAPRole_SetParameter(GAPROLE_ADVERT_ENABLED, sizeof(uint8_t), &adv, NULL);
      }
      return;
    }
    
    if (keys & KEY_SELECT) //connect to a discovered device
    {
      if (selectKey == DISCOVERED_DEVICES)    // connect to a device  
      {
        uint8_t addrType;
        uint8_t *peerAddr;
        
        if (connecting_state == 1) // if already attempting to connect, cancel connection
        {
        	GAPRole_TerminateConnection(0xFFFE);
        	LCD_WRITE_STRING("Connecting stopped.", LCD_PAGE3);
        	connecting_state = 0;
        }
        else //establish new connection
        {
        	// if there is a scan result
        	if (scanRes > 0)
        	{
        		// connect to current device in scan result
        		peerAddr = devList[scanIdx].addr;
        		addrType = devList[scanIdx].addrType;

        		GAPRole_EstablishLink(DEFAULT_LINK_HIGH_DUTY_CYCLE,
                                	DEFAULT_LINK_WHITE_LIST,
									addrType, peerAddr);
        		connecting_state = 1;

        		LCD_WRITE_STRING("Connecting", LCD_PAGE3);
        		LCD_WRITE_STRING(Util_convertBdAddr2Str(peerAddr), LCD_PAGE4);
        	}
        }
      }
      else if (selectKey == CONNECTED_DEVICES) //enter the device menu
      {
        if (multiConnInfo[connIdx].gapRole_ConnectionHandle != INVALID_CONNHANDLE)
        {
          LCDmenu = DEVICE_MENU;
          LCD_WRITE_STRING("Device Menu", LCD_PAGE3);
          LCD_WRITE_STRING(Util_convertBdAddr2Str(multiConnInfo[connIdx].gapRole_devAddr), LCD_PAGE4);
          if (multiConnInfo[connIdx].gapRole_ConnRole == GAP_PROFILE_CENTRAL)
          {
             LCD_WRITE_STRING("Connected as Central", LCD_PAGE5);
             LCD_WRITE_STRING("", LCD_PAGE6);
             LCD_WRITE_STRING("", LCD_PAGE7);
          }
          else //PERIPHERAL
          {
            LCD_WRITE_STRING("Connected as Periph", LCD_PAGE5);
            LCD_WRITE_STRING("", LCD_PAGE6);
            LCD_WRITE_STRING("", LCD_PAGE7);            
          }
          //use this connection for all functionality
          connHandle = multiConnInfo[connIdx].gapRole_ConnectionHandle;
        }
        else // no active connection here
        LCD_WRITE_STRING("No Connection here.", LCD_PAGE3);
      }
      return;
    }
    
    if (keys & KEY_DOWN) //browse connected devices
    {
      LCD_WRITE_STRING("Connected Device:", LCD_PAGE3);
      if (++connIdx >= MAX_NUM_BLE_CONNS) //increment connIdx
      {
        connIdx = 0;
      }   
      if (multiConnInfo[connIdx].gapRole_ConnectionHandle != INVALID_CONNHANDLE) //if there is a connection at this index
      {
        LCD_WRITE_STRING(Util_convertBdAddr2Str(multiConnInfo[connIdx].gapRole_devAddr), LCD_PAGE4);
      }
      else
      {
        LCD_WRITE_STRING("N/A", LCD_PAGE4);
      }
      selectKey = CONNECTED_DEVICES;
    } 
    return;
  }
  
  else if (LCDmenu == DEVICE_MENU)
  {
    if (keys & KEY_UP) //read/whrite char
    {
      if (charHdl[connIdx] != 0)
      {
        uint8_t status;
        
        // Do a read or write as long as no other read or write is in progress
        if (doWrite)
        {
          // Do a write
          attWriteReq_t req;
          
          req.pValue = GATT_bm_alloc(connHandle, ATT_WRITE_REQ, 1, NULL);
          if ( req.pValue != NULL )
          {
            req.handle = charHdl[connIdx];
            req.len = 1;
            req.pValue[0] = charVal;
            req.sig = 0;
            req.cmd = 0;
            
            status = GATT_WriteCharValue(connHandle, &req, selfEntity);
            if ( status != SUCCESS )
            {
              GATT_bm_free((gattMsg_t *)&req, ATT_WRITE_REQ);
            }
          }
        }
        else
        {
          // Do a read
          attReadReq_t req;
          
          req.handle = charHdl[connIdx];
          status = GATT_ReadCharValue(connHandle, &req, selfEntity);
        }
        
        if (status == SUCCESS)
        {
          doWrite = !doWrite;
        }
      }
      return;
    }
    
    if (keys & KEY_RIGHT) //connection update...eventually
    {
      asm("NOP");
      return;
    }
    
    if (keys & KEY_SELECT)
    {
      GAPRole_TerminateConnection(connHandle);
      
      LCD_WRITE_STRING("Disconnecting", LCD_PAGE5);
      LCD_WRITE_STRING("", LCD_PAGE6);
      
      return;
    }

    if (keys & KEY_DOWN) //back to main menu
    {
      LCDmenu = MAIN_MENU;
      LCD_WRITE_STRING("Main Menu", LCD_PAGE3);
      //clear screen
      LCD_WRITE_STRING("", LCD_PAGE4);
      LCD_WRITE_STRING("", LCD_PAGE5);
      LCD_WRITE_STRING("", LCD_PAGE6);
      LCD_WRITE_STRING("", LCD_PAGE7);
      LCD_WRITE_STRING_VALUE("Connected to ", gapRoleNumLinks(GAPROLE_ACTIVE_LINKS) ,10, LCD_PAGE0);
      
      connIdx = 0;
      
      return;
    }
  }
}
/*********************************************************************
 * @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);
}
/*********************************************************************
 * @fn      glucCollCentral_handleKeys
 *
 * @brief   Handles all key events for this device.
 *
 * @param   shift - true if in shift/alt.
 * @param   keys - bit field for key events.
 *
 * @return  none
 */
static void glucCollCentral_handleKeys(uint8_t shift, uint8_t keys)
{
  (void)shift;  // Intentionally unreferenced parameter

  if (keys & KEY_UP)
  {
    // Start or stop discovery
    if (glucCollState != BLE_STATE_CONNECTED)
    {
      if (!glucCollScanning)
      {
        glucCollScanning = TRUE;
        glucCollScanRes = 0;
        
        LCD_WRITE_STRING("Discovering...", LCD_PAGE0);
        LCD_WRITE_STRING("", LCD_PAGE1);
        LCD_WRITE_STRING("", LCD_PAGE2);
        
        GAPCentralRole_StartDiscovery(DEFAULT_DISCOVERY_MODE,
                                      DEFAULT_DISCOVERY_ACTIVE_SCAN,
                                      DEFAULT_DISCOVERY_WHITE_LIST);      
      }
      else
      {
        GAPCentralRole_CancelDiscovery();
      }
    }
    else if (glucCollState == BLE_STATE_CONNECTED &&
             glucCollCharHdls == true &&
             glucCollWritePending == false)
    {
      uint8_t status;
#if GLUCOSE_FILTER_ENABLED
     // Request number of records
      status = glucoseCtlPntWriteFilter(CTL_PNT_OP_GET_NUM, CTL_PNT_OPER_RANGE,
                                        DEFAULT_FILTER_TYPE, pFilter1, pFilter2);      
#else
      // Request number of records
      status = glucoseCtlPntWrite(CTL_PNT_OP_GET_NUM, CTL_PNT_OPER_ALL);
#endif      
      
      if(status == 0)
      {
        glucCollWritePending = true;
      }
    }

    return;
  }

  if (keys & KEY_LEFT)
  {
    // Display discovery results
    if (glucCollState != BLE_STATE_CONNECTED && !glucCollScanning && 
        glucCollScanRes > 0)
    {
        // Increment index of current result (with wraparound)
        glucCollScanIdx++;

        if (glucCollScanIdx >= glucCollScanRes)
        {
          glucCollScanIdx = 0;
        }

        LCD_WRITE_STRING_VALUE("Device", glucCollScanIdx + 1,
                                10, LCD_PAGE0);
        LCD_WRITE_STRING(Util_convertBdAddr2Str(glucCollDevList[glucCollScanIdx].addr),
                          LCD_PAGE1);
        LCD_WRITE_STRING("", LCD_PAGE2);
    }
    else if (glucCollState == BLE_STATE_CONNECTED)
    {
      if(glucoseCtlPntWrite(CTL_PNT_OP_ABORT, CTL_PNT_OPER_NULL) == 0)
      {
        glucCollWritePending = false;
      }
    }

    return;
  }

  if (keys & KEY_RIGHT)
  {
    // Request all records
    if (glucCollState == BLE_STATE_CONNECTED &&
        glucCollCharHdls == true &&
        glucCollWritePending == false)
    { 
      uint8_t status;
#if GLUCOSE_FILTER_ENABLED
      status = glucoseCtlPntWriteFilter(CTL_PNT_OP_REQ, CTL_PNT_OPER_RANGE, 
                                        DEFAULT_FILTER_TYPE, pFilter1, pFilter2);
#else
      status = glucoseCtlPntWrite(CTL_PNT_OP_REQ, CTL_PNT_OPER_ALL);
#endif

      if(status == SUCCESS)
      {
        glucCollWritePending = true;
      }
    }

    return;
  }
  
  if (keys & KEY_SELECT)
  {
    uint8_t addrType;
    uint8_t *peerAddr;
    
    // Connect or disconnect
    if (glucCollState == BLE_STATE_IDLE)
    {
      // if there is a scan result
      if (glucCollScanRes > 0)
      {
        // connect to current device in scan result
        peerAddr = glucCollDevList[glucCollScanIdx].addr;
        addrType = glucCollDevList[glucCollScanIdx].addrType;

        glucCollState = BLE_STATE_CONNECTING;

        GAPCentralRole_EstablishLink(DEFAULT_LINK_HIGH_DUTY_CYCLE,
                                     DEFAULT_LINK_WHITE_LIST,
                                     addrType, peerAddr);
  
        LCD_WRITE_STRING("Connecting", LCD_PAGE0);
        LCD_WRITE_STRING(Util_convertBdAddr2Str(peerAddr), LCD_PAGE1); 
        LCD_WRITE_STRING("", LCD_PAGE2);
      }
    }
    else if (glucCollState == BLE_STATE_CONNECTING ||
             glucCollState == BLE_STATE_CONNECTED)
    {
      // disconnect
      glucCollState = BLE_STATE_DISCONNECTING;

      GAPCentralRole_TerminateLink(glucCollConnHandle);

      LCD_WRITE_STRING("Disconnecting", LCD_PAGE0); 
      LCD_WRITE_STRING("", LCD_PAGE1);
      LCD_WRITE_STRING("", LCD_PAGE2);
    }
    
    return;
  }
  
  if (keys & KEY_DOWN)
  {
    // Clear stored records
    if (glucCollState == BLE_STATE_CONNECTED &&
        glucCollCharHdls == true &&
        glucCollWritePending == false)
    { 
      uint8_t status;      
#if GLUCOSE_FILTER_ENABLED
      status = glucoseCtlPntWriteFilter(CTL_PNT_OP_CLR, CTL_PNT_OPER_RANGE,
                                        DEFAULT_FILTER_TYPE, pFilter1, pFilter2);
#else         
      status = glucoseCtlPntWrite(CTL_PNT_OP_CLR, CTL_PNT_OPER_ALL);
#endif

      if(status == 0)
      {
        glucCollWritePending = true;
        glucCollClearPending = true;
      }
    }
    else if (glucCollState != BLE_STATE_CONNECTED)
    {
      // erase all bonds
      GAPBondMgr_SetParameter(GAPBOND_ERASE_ALLBONDS, 0, NULL);
      LCD_WRITE_STRING("Erasing bonds", LCD_PAGE0);
      LCD_WRITE_STRING("", LCD_PAGE1);
      LCD_WRITE_STRING("", LCD_PAGE2);

      // initiate service discovery again
      glucCollCharHdls = false;
    }
  }
}
/*******************************************************************************
 * @fn      SensorTagDisplay_showStatus
 *
 * @brief   Display main status parameters on the display.
 *
 *          - device name
 *          - device address
 *          - firmware revision
 *          - GAP connection status
 *
 * @param   none
 *
 * @return  none
 */
void SensorTagDisplay_showStatus(void)
{
    if (handle != NULL)
    {
        uint8_t buf[24];
        char *gapStatusStr;

        // Make sure display is blank
        Display_clear(handle);

        // Line 0: device info
        DevInfo_GetParameter(DEVINFO_MODEL_NUMBER, buf);
        Display_print0(handle, DISPLAY_LINE_DEV_INFO, 0, (const char*)buf);

        // Line 1: board address
        GAPRole_GetParameter(GAPROLE_BD_ADDR, buf);
        Display_print0(handle, DISPLAY_LINE_BOARD_ADDR,
                       1, Util_convertBdAddr2Str(buf));

        // Line 2: firmware revision
        DevInfo_GetParameter(DEVINFO_FIRMWARE_REV, buf);
        Display_print0(handle, DISPLAY_LINE_FWREV, 1, "FW rev.");
        buf[5] = '\0'; // Display max 5 characters (leave out date part)
        Display_print0(handle, DISPLAY_LINE_FWREV, 10, (const char*)buf);

        // Line 11: GAP connection status
        switch (gapProfileState)
        {
        case GAPROLE_INIT:
            gapStatusStr = "Init";
            break;
        case GAPROLE_STARTED:
            gapStatusStr = "Started";
            break;
        case GAPROLE_ADVERTISING:
            gapStatusStr = "Advertising";
            break;
        case GAPROLE_ADVERTISING_NONCONN:
            gapStatusStr = "Advertising-nc";
            break;
        case GAPROLE_WAITING:
            gapStatusStr = "Waiting";
            break;
        case GAPROLE_WAITING_AFTER_TIMEOUT:
            gapStatusStr = "Waiting-tout";
            break;
        case GAPROLE_CONNECTED:
            gapStatusStr = "Connected";
            break;
        case GAPROLE_CONNECTED_ADV:
            gapStatusStr = "Connected-adv";
            break;
        case GAPROLE_ERROR:
            gapStatusStr = "Error";
            break;
        default:
            gapStatusStr = "Unknown";
            break;
        }
        Display_print0(handle, DISPLAY_LINE_GAP, 2, gapStatusStr);
    }
}
Example #9
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;
}
Example #10
0
/*********************************************************************
 * @fn      SimplePropBeacon_processStateChangeEvt
 *
 * @brief   Process a pending GAP Role state change event.
 *
 * @param   newState - new state
 *
 * @return  None.
 */
static void SimplePropBeacon_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
        Display_print0(dispHandle, 1, 0, Util_convertBdAddr2Str(ownAddress));
        Display_print0(dispHandle, 2, 0, "Initialized");

        // Start advertising
        SimplePropBeacon_startRegularAdv();
      }
      break;

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

    case GAPROLE_ADVERTISING_NONCONN:
      {
        SimplePropBeacon_freeAttRsp(bleNotConnected);
        Display_print0(dispHandle, 2, 0, "Advertising Proprietary Beacon");
        Display_print0(dispHandle, 3, 0, "");

        break;
      }

    case GAPROLE_CONNECTED:
      {
        linkDBInfo_t linkInfo;
        uint8_t numActive = 0;
        
        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));
        }
      }
      break;

    case GAPROLE_WAITING:

    case GAPROLE_WAITING_AFTER_TIMEOUT:
      SimplePropBeacon_freeAttRsp(bleNotConnected);
      SimplePropBeacon_startRegularAdv();
      break;

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

    default:
      Display_clearLine(dispHandle, 2);
      break;
  }
}
Example #11
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;
}