Advertisement
Guest User

IDB05A1 - Heart rate read

a guest
Jan 19th, 2016
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 9.19 KB | None | 0 0
  1. /* mbed Microcontroller Library
  2.  * Copyright (c) 2006-2015 ARM Limited
  3.  *
  4.  * Licensed under the Apache License, Version 2.0 (the "License");
  5.  * you may not use this file except in compliance with the License.
  6.  * You may obtain a copy of the License at
  7.  *
  8.  *     http://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  * Unless required by applicable law or agreed to in writing, software
  11.  * distributed under the License is distributed on an "AS IS" BASIS,
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  * See the License for the specific language governing permissions and
  14.  * limitations under the License.
  15.  */
  16.  
  17. #include "mbed.h"
  18. #include "ble/Gap.h"
  19. #include "ble/BLE.h"
  20. #include "ble/DiscoveredCharacteristic.h"
  21. #include "ble/DiscoveredService.h"
  22. #include "ble/GapAdvertisingParams.h"
  23.  
  24.  
  25. #define PRINTF(...) printf(__VA_ARGS__)
  26.  
  27. BLE  ble;
  28. DigitalOut led1(LED1);
  29.  
  30.  
  31. bool _connected = false;
  32.  
  33. DiscoveredCharacteristic hrmCharacteristic;
  34. static volatile bool  triggerHrmCharacteristic = false;
  35. //PROTOTYPES
  36. void PrintScanResult(const Gap::AdvertisementCallbackParams_t *params);
  37. void periodicCallback(void);
  38. void connectToDevice(const Gap::Address_t peerAddr);
  39.  
  40. void serviceDiscoveryCallback(const DiscoveredService *service);
  41. void characteristicDiscoveryCallback(const DiscoveredCharacteristic *characteristicP);
  42. void discoveryTerminationCallback(Gap::Handle_t connectionHandle);
  43.  
  44.  
  45. void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params) {
  46.     _connected = false;
  47.     PRINTF("disconnected\r\n");
  48. }
  49.  
  50. void periodicCallback(void)
  51. {
  52.     led1 = !led1; /* Do blinky on LED1 while we're waiting for BLE events */
  53.     /* Note that the periodicCallback() executes in interrupt context, so it is safer to do
  54.      * heavy-weight sensor polling from the main thread. */
  55.     triggerHrmCharacteristic = true;
  56. }
  57.  
  58. void PrintScanResult(const Gap::AdvertisementCallbackParams_t *params)
  59. {
  60.      for(int8_t i = 5; i>=0; i--)
  61.     {
  62.        PRINTF("%02x",params->peerAddr[i] );
  63.        if(i != 0)PRINTF("-");
  64.     }
  65.     PRINTF("\r\n");
  66.    
  67.     PRINTF("RSSI: %d\r\n",params->rssi );
  68.    
  69.     if(params->isScanResponse){
  70.         PRINTF("isScanResponse=true\r\n");
  71.     } else {
  72.         PRINTF("isScanResponse=false\r\n");
  73.     }
  74.    
  75.     switch(params->type)
  76.     {
  77.      case GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED:
  78.                                         PRINTF("ADV_CONNECTABLE_UNDIRECTED\r\n");
  79.                                         break;
  80.      case GapAdvertisingParams::ADV_CONNECTABLE_DIRECTED:
  81.                                         PRINTF("ADV_CONNECTABLE_DIRECTED\r\n");
  82.                                         break;
  83.      case GapAdvertisingParams::ADV_SCANNABLE_UNDIRECTED:
  84.                                         PRINTF("ADV_SCANNABLE_UNDIRECTED\r\n");
  85.                                         break;
  86.      case GapAdvertisingParams::ADV_NON_CONNECTABLE_UNDIRECTED:
  87.                                         PRINTF("ADV_NON_CONNECTABLE_UNDIRECTED\r\n");
  88.                                         break;  
  89.          
  90.     }
  91.    
  92.     PRINTF("advertisingDataLen: %d\r\n",params->advertisingDataLen );
  93.    
  94.     PRINTF("advertisingData: ");
  95.     for(int i=0; i < params->advertisingDataLen; i++)
  96.     {
  97.         PRINTF("%02x",params->advertisingData[i]);
  98.         if(i != params->advertisingDataLen - 1)PRINTF("-");
  99.     }
  100.     PRINTF("\r\n");
  101. }
  102.  
  103.  
  104. void scanResultReceived(const Gap::AdvertisementCallbackParams_t *params)
  105. {
  106.     PRINTF("\r\nscanResultReceived\r\n");
  107.    
  108.     //print advertsing values
  109.    PrintScanResult(params);
  110.    
  111.    PRINTF("scan result ... try connect\r\n");
  112.    connectToDevice(params->peerAddr);
  113. }
  114.  
  115. void connectToDevice(const Gap::Address_t peerAddr)
  116. {
  117.    ble_error_t  ret = ble.gap().connect(peerAddr, Gap::ADDR_TYPE_PUBLIC, NULL, NULL);
  118.    
  119.    if(ret == BLE_ERROR_NONE) {
  120.            PRINTF("SUCCESS: connect\r\n");
  121.           } else {
  122.                  PRINTF("ERROR : connect\r\n");
  123.                  }
  124. }
  125.  
  126. void serviceDiscoveryCallback(const DiscoveredService *service) {
  127.     PRINTF("Service discovery callback\r\n");
  128.    
  129.     if (service->getUUID().shortOrLong() == UUID::UUID_TYPE_SHORT) {
  130.         PRINTF("S UUID-%x attrs[%u %u]\r\n", service->getUUID().getShortUUID(), service->getStartHandle(), service->getEndHandle());
  131.     } else {
  132.         printf("S UUID-");
  133.         const uint8_t *longUUIDBytes = service->getUUID().getBaseUUID();
  134.         for (unsigned i = 0; i < UUID::LENGTH_OF_LONG_UUID; i++) {
  135.             printf("%02x", longUUIDBytes[i]);
  136.         }
  137.         PRINTF(" attrs[%u %u]\r\n", service->getStartHandle(), service->getEndHandle());
  138.     }
  139. }
  140.  
  141. void characteristicDiscoveryCallback(const DiscoveredCharacteristic *characteristicP) {
  142.     PRINTF("Characteristic discovery callback\r\n");
  143.    
  144.     PRINTF("  C UUID-%x valueAttr[%u] props[%x]\r\n", characteristicP->getUUID().getShortUUID(), characteristicP->getValueHandle(), (uint8_t)characteristicP->getProperties().broadcast());
  145.     //TODO: use hear rate characteristic
  146.     if (characteristicP->getUUID().getShortUUID() == 0x2A00) {
  147.         hrmCharacteristic = *characteristicP;
  148.         triggerHrmCharacteristic = true;
  149.        PRINTF("device name characteristic found\r\n");
  150.     }
  151. }
  152.  
  153. void discoveryTerminationCallback(Gap::Handle_t connectionHandle) {
  154.     PRINTF("terminated SD for handle %u\r\n", connectionHandle);
  155. }
  156.  
  157. void timeoutCallback(Gap::TimeoutSource_t param) {
  158.    
  159.     switch(param)
  160.     {
  161.         case Gap::TIMEOUT_SRC_ADVERTISING:
  162.                                     PRINTF("Timeout: Advertising\r\n");
  163.                                     break;
  164.         case Gap::TIMEOUT_SRC_SECURITY_REQUEST:
  165.                                     PRINTF("Timeout: Security access\r\n");
  166.                                     break;
  167.         case Gap::TIMEOUT_SRC_SCAN:
  168.                                     PRINTF("Timeout: Scan\r\n");
  169.                                     break;
  170.         case Gap::TIMEOUT_SRC_CONN:
  171.                                     PRINTF("Timeout: Conn\r\n");
  172.                                     break;
  173.     }
  174. }
  175.  
  176. void connectionCallback(const Gap::ConnectionCallbackParams_t *params) {
  177.     if (params->role == Gap::CENTRAL) {
  178.         PRINTF("Launch service discovery\r\n");
  179.         //TODO: use heart rate service
  180.         ble.gattClient().onServiceDiscoveryTermination(discoveryTerminationCallback);
  181.         ble.gattClient().launchServiceDiscovery(params->handle, serviceDiscoveryCallback, characteristicDiscoveryCallback, 0x1800, 0x2A00);
  182.         _connected = true;
  183.      //   ble.gattClient().launchServiceDiscovery(params->handle, serviceDiscoveryCallback, characteristicDiscoveryCallback, GattService::UUID_HEART_RATE_SERVICE, GattCharacteristic::UUID_HEART_RATE_MEASUREMENT_CHAR); //BLE_UUID_UNKNOWN
  184.     }
  185.     else {
  186.         PRINTF("No central role\r\n");
  187.     }
  188. }
  189.  
  190.  
  191. void readCallback(const GattReadCallbackParams *response)
  192. {
  193.     PRINTF("readCallback\r\n");
  194.    
  195.     if (response->handle == hrmCharacteristic.getValueHandle()) {
  196.             PRINTF("readCallback: handle %u, offset %u, len %u\r\n", response->handle, response->offset, response->len);
  197.             for (unsigned index = 0; index < response->len; index++) {
  198.                 PRINTF("%c[%02x]", response->data[index], response->data[index]);
  199.             }
  200.             PRINTF("\r\n");
  201.         }
  202. }
  203.  
  204. /**
  205.  * This function is called when the ble initialization process has failled
  206.  */
  207. void onBleInitError(BLE &ble, ble_error_t error)
  208. {
  209.     PRINTF("BLE init error");
  210. }
  211.  
  212. /**
  213.  * Callback triggered when the ble initialization process has finished
  214.  */
  215. void bleInitComplete(BLE::InitializationCompleteCallbackContext *params)
  216. {
  217.    
  218.     PRINTF("init complete\r\n");
  219.    
  220.     BLE&        ble   = params->ble;
  221.     ble_error_t error = params->error;
  222.  
  223.     if (error != BLE_ERROR_NONE) {
  224.         /* In case of error, forward the error handling to onBleInitError */
  225.         PRINTF("Error init\r\n");
  226.         onBleInitError(ble, error);
  227.         return;
  228.     }
  229.  
  230.     /* Ensure that it is the default instance of BLE */
  231.     if(ble.getInstanceID() != BLE::DEFAULT_INSTANCE) {
  232.         PRINTF("Error default instance\r\n");
  233.         return;
  234.     }
  235.  
  236.    ble.onTimeout(timeoutCallback);
  237.    ble.onConnection(connectionCallback);
  238.    ble.onDisconnection(disconnectionCallback);
  239.    ble.gattClient().onDataRead(readCallback);
  240.    
  241.     ble.gap().setScanParams(300, 300);
  242.     ble.gap().startScan(scanResultReceived);
  243.     PRINTF("scan started...\r\n");
  244.  
  245.    
  246.     // infinite loop
  247.     while (1) {
  248.         // check for trigger from periodicCallback()
  249.          if (triggerHrmCharacteristic && !ble.gattClient().isServiceDiscoveryActive() && _connected) {
  250.            
  251.             triggerHrmCharacteristic = false;
  252.             PRINTF("START READ\r\n");
  253.             hrmCharacteristic.read();
  254.            
  255.         } else {
  256.             ble.waitForEvent(); // low power wait for event
  257.         }
  258.     }
  259.  
  260.    
  261.    
  262.    
  263. }
  264.  
  265. int main(void)
  266. {
  267.     PRINTF("started...\r\n");
  268.    
  269.     led1 = 1;
  270.     Ticker ticker;
  271.     ticker.attach(periodicCallback, 1); // blink LED every second
  272.    
  273.     _connected = false;
  274.    
  275.     PRINTF("start init...\r\n");
  276.    
  277.     ble.init(bleInitComplete);  
  278. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement