Central Test.

Dependencies:   BLE_API mbed nRF51822

Files at this revision

API Documentation at this revision

Comitter:
hmiot
Date:
Fri Jan 20 14:22:56 2017 +0000
Parent:
5:f6b6bf98c686
Commit message:
Working with BLE Light..

Changed in this revision

main.cpp Show annotated file Show diff for this revision Revisions of this file
--- a/main.cpp	Thu Jan 19 12:21:34 2017 +0000
+++ b/main.cpp	Fri Jan 20 14:22:56 2017 +0000
@@ -1,163 +1,97 @@
+/* mbed Microcontroller Library
+ * Copyright (c) 2006-2015 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 #include "mbed.h"
 #include "ble/BLE.h"
 #include "ble/DiscoveredCharacteristic.h"
 #include "ble/DiscoveredService.h"
-#include "ble/GapScanningParams.h"
-#include "ble_radio_notification.h"
-#include "ble_gap.h"
-
-BLE ble;
-Serial pc(USBTX, USBRX);
-
-/*const uint8_t MPU6050_service_uuid[] = {
-    0x45,0x35,0x56,0x80,0x0F,0xD8,0x5F,0xB5,0x51,0x48,0x30,0x27,0x06,0x9B,0x3F,0xD9
-};*/
-const uint8_t MPU6050_service_uuid[] = {
-    0x00,0x00,0xFF,0xE5,0x00,0x00,0x10,0x00,0x80,0x00,0x00,0x80,0x5F,0x9B,0x34,0xFB
-};
-/*const uint8_t MPU6050_Accel_Characteristic_uuid[] = {
-    0x45,0x35,0x56,0x81,0x0F,0xD8,0x5F,0xB5,0x51,0x48,0x30,0x27,0x06,0x9B,0x3F,0xD9
-};*/
-
-const uint8_t MPU6050_Accel_Characteristic_uuid[] = {
-    0x00,0x00,0xFF,0xE6,0x00,0x00,0x10,0x00,0x80,0x00,0x00,0x80,0x5F,0x9B,0x34,0xFB
-};
+#include "ble/Gap.h"
+#include "nRF5xGap.h"
+static const uint16_t UNIT_1_25_MS  = 1250;
+static const uint16_t UNIT_10_MS  = 10000;
 #define MSEC_TO_UNITS(TIME, RESOLUTION) (((TIME) * 1000) / (RESOLUTION))
+#define MIN_CONNECTION_INTERVAL   MSEC_TO_UNITS(7.5, UNIT_1_25_MS)
+#define MAX_CONNECTION_INTERVAL   MSEC_TO_UNITS(30, UNIT_1_25_MS) 
+#define SLAVE_LATENCY             4                            
+#define SUPERVISION_TIMEOUT       MSEC_TO_UNITS(6000, UNIT_10_MS) 
 
-enum
-{
-    UNIT_0_625_MS = 625,                                
-    UNIT_1_25_MS  = 1250,                               
-    UNIT_10_MS    = 10000                               
-};
-
-#define NUMBER_OF_PERIPHERALS 3
+typedef unsigned char byte_char;
 
-#define MIN_CONNECTION_INTERVAL   MSEC_TO_UNITS(7.5, UNIT_1_25_MS)          
-#define MAX_CONNECTION_INTERVAL   MSEC_TO_UNITS(30, UNIT_1_25_MS)           
-#define SLAVE_LATENCY             0                                         
-#define SUPERVISION_TIMEOUT       MSEC_TO_UNITS(4000, UNIT_10_MS) 
+DiscoveredCharacteristic lightCharacteristic;
 
-//const char Dev_Mac_Addr[15]="5065838DA351";
-DiscoveredCharacteristic accelChar;
-UUID serviceUUID(MPU6050_service_uuid);
-UUID accelUUID(MPU6050_Accel_Characteristic_uuid);
-
-
-static const Gap::ConnectionParams_t m_connection_param =
-{
+static const Gap::ConnectionParams_t m_conn_params ={
     (uint16_t)MIN_CONNECTION_INTERVAL,
     (uint16_t)MAX_CONNECTION_INTERVAL,
     (uint16_t)SLAVE_LATENCY,
     (uint16_t)SUPERVISION_TIMEOUT
 };
-typedef struct {
-    Gap::Handle_t   handle;
-    Gap::Address_t  address;
-    bool    connected;
-    uint8_t*    deviceName;
-} peripheral_t;
-static const char adv_name[] = "LEDBlue-838DA351";
-static peripheral_t gs_peripheral[NUMBER_OF_PERIPHERALS];
 
+GapScanningParams m_scan_params;
+Serial pc(USBTX, USBRX);
+
+static ble_error_t error_status;
 
-uint32_t ble_advdata_parser(uint8_t type, uint8_t advdata_len, uint8_t *p_advdata, uint8_t *len, uint8_t *p_field_data)
-{
-    uint8_t index=0;
-    uint8_t field_length, field_type;
-    pc.printf("advdata_parser1\n\r");
-    pc.printf("type : %d Length : %d\n\r",type, advdata_len);
-    while(index<advdata_len)
-    {pc.printf("advdata_parser loop\n\r");
-        field_length = p_advdata[index];
-        field_type   = p_advdata[index+1];
-        pc.printf("FieldLen : %d\n\r",p_advdata[index]);
-        pc.printf("Field_Type : %d\n\r",p_advdata[index+1]);
-        pc.printf("Fieldtype : %d\n\r",field_type);
-        if(field_type == type)
-        {
-            pc.printf("Copy the data\n\r");
-            //memcpy(p_field_data, &p_advdata[index+2], (field_length-1));
-            p_field_data = &p_advdata[index+2];
-            *len = field_length - 1;
-            return NRF_SUCCESS;
-        }
-        index += field_length;
+void advertisementCallback(const Gap::AdvertisementCallbackParams_t *params) {
+    uint8_t con_status =0;
+   // uint8_t i;
+    Gap::GapState_t con_state;
+     //0x51 for Magic light 
+    //0x5A
+    if (params->peerAddr[0] != 0x51) { // 0x2F for red bear1.5 /* !ALERT! Alter this filter to suit your device. */
+        return; 
     }
-    return NRF_ERROR_NOT_FOUND;
-}
-
-void scanCallback(const Gap::AdvertisementCallbackParams_t *params) {
     pc.printf("adv peerAddr[%02x %02x %02x %02x %02x %02x] rssi %d, isScanResponse %u, AdvertisementType %u\r\n",
            params->peerAddr[5], params->peerAddr[4], params->peerAddr[3], params->peerAddr[2], params->peerAddr[1], params->peerAddr[0],
            params->rssi, params->isScanResponse, params->type);
-           //pc.printf("params->peerAddr : %s \n\r",params->peerAddr);
-      //  char peer_Addr[15];
+           pc.printf("Data Length : %d\r\n",params->advertisingDataLen);
          
-   // pc.printf("params->advertisingData : %02x %02x\n\r",params->advertisingData[0],params->advertisingData[1]);
-    pc.printf("Data Lenght = %d\n\r",params->advertisingDataLen);
-    uint8_t len;
+        con_status = BLE::Instance().gap().connect(params->peerAddr, Gap::ADDR_TYPE_PUBLIC, NULL, NULL);
+        pc.printf("Connection Status : %d\r\n",con_status);
+        con_state = BLE::Instance().gap().getState();
+        pc.printf("Connection state : %d\r\n",con_state);
     
-    uint8_t status;
-    uint8_t stop_status;
-    pc.printf("Connected1\n\r");
-   /* if( NRF_SUCCESS == ble_advdata_parser(BLE_GAP_AD_TYPE_COMPLETE_LOCAL_NAME,
-                             params->advertisingDataLen,
-                        (uint8_t *)params->advertisingData, &len, adv_name))
-   {*/
-    pc.printf("Connected2\n\r");
-    uint8_t i=0;
-       // for(uint8_t i=0; i<3; i++){
-            //if(gs_peripheral[i].connected == false)
-            if (params->peerAddr[0] == 0x51){
-                pc.printf("Connected3\n\r");
-                memcpy(gs_peripheral[i].address, params->peerAddr, sizeof(params->peerAddr)); 
-                gs_peripheral[i].deviceName = (uint8_t*)adv_name;
-                ble.gap().setDeviceName(gs_peripheral[i].deviceName);
-                status = ble.gap().connect(params->peerAddr, BLEProtocol::AddressType::RANDOM_STATIC, &m_connection_param, NULL);
-                pc.printf("Connection Status = %d\n\r",status);
-                pc.printf("stop scan\n\r");
-                stop_status = ble.gap().stopScan();  
-                pc.printf("stop Status = %d\n\r",stop_status);           
-               // break;
-            }
-       // }
-       
-        ble.stopScan();
-   // }
+  //  }
+     BLE::Instance().gap().stopScan();
 }
 
 void serviceDiscoveryCallback(const DiscoveredService *service) {
-    pc.printf("service found...\r\n");    
+    pc.printf("Service Discovery Callback\r\n");
+    if (service->getUUID().shortOrLong() == UUID::UUID_TYPE_SHORT) {
+        pc.printf("S UUID-%x attrs[%u %u]\r\n", service->getUUID().getShortUUID(), service->getStartHandle(), service->getEndHandle());
+    } else {
+        pc.printf("S UUID-");
+        const uint8_t *longUUIDBytes = service->getUUID().getBaseUUID();
+        for (unsigned i = 0; i < UUID::LENGTH_OF_LONG_UUID; i++) {
+            printf("%02x", longUUIDBytes[i]);
+        }
+        pc.printf(" attrs[%u %u]\r\n", service->getStartHandle(), service->getEndHandle());
+    }
 }
 
 void characteristicDiscoveryCallback(const DiscoveredCharacteristic *characteristicP) {
-    pc.printf("characteristicDiscoveryCallback\r\n");
-    
-    accelChar = *characteristicP;
-    
-    for(uint8_t i=0; i<3; i++){
-        if(gs_peripheral[i].connected){
-            ble.gattClient().read(characteristicP->getConnectionHandle(), characteristicP->getValueHandle(), 0);
-        }
-    }
-
-}
-
-void connectionCallback(const Gap::ConnectionCallbackParams_t *params) {
-    pc.printf("GAP_EVT_CONNECTED\r\n");
-    if (params->role == Gap::CENTRAL) {
-
-        for(uint8_t i=0; i<3; i++){
-            if(gs_peripheral[i].connected == false){
-                gs_peripheral[i].handle = params->handle;
-                gs_peripheral[i].connected = true;
-                break;
-            }
-        }
-                
-        ble.gattClient().launchServiceDiscovery(params->handle, serviceDiscoveryCallback, characteristicDiscoveryCallback, serviceUUID, accelUUID);
-        
+    pc.printf("  C UUID-%x valueAttr[%u] props[%x]\r\n", characteristicP->getUUID().getShortUUID(), characteristicP->getValueHandle(), (uint8_t)characteristicP->getProperties().broadcast());
+    uint8_t write_data []={0x56,0xff,0x00,0x00,0x00,0xf0,0xaa};
+    if (characteristicP->getUUID().getShortUUID() == 0xffe9) { /* !ALERT! Alter this filter to suit your device. */
+       lightCharacteristic        = *characteristicP;
+       pc.printf("Matched char UUID\r\n");
+       printf("Value Handle = %d\r\n",characteristicP->getDeclHandle());
+       printf("Value Handle = %d and data size : %d\r\n",characteristicP->getValueHandle(),sizeof(write_data));
+       lightCharacteristic.writeWoResponse(sizeof(write_data), write_data);
+      //error_status = characteristicP->write(sizeof(write_data), write_data);
+       printf("Write Status : %d\r\n",error_status);
     }
 }
 
@@ -165,49 +99,49 @@
     pc.printf("terminated SD for handle %u\r\n", connectionHandle);
 }
 
-void triggerRead(const GattReadCallbackParams *response) {
-    pc.printf("triggerRead.....\r\n");
-    
-    pc.printf("len: %d\r\n", response->len);
-    const uint8_t *data = response->data;
-    pc.printf("data ");
-    for(int i=0; i < response->len; i++){
-        pc.printf("%f ", (float)data[i]);  
+void connectionCallback(const Gap::ConnectionCallbackParams_t *params) {
+    pc.printf("Connection Callback\n\r");
+    if (params->role == Gap::CENTRAL) {
+        pc.printf("Service and characterstics discovery callback\r\n");
+        BLE::Instance().gattClient().onServiceDiscoveryTermination(discoveryTerminationCallback);
+        BLE::Instance().gattClient().launchServiceDiscovery(params->handle, serviceDiscoveryCallback, characteristicDiscoveryCallback, 0xffe5, 0xffe9);
     }
-    pc.printf("\r\n");
-    accelChar.read();
+}
+
+void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params) {
+    pc.printf("disconnected\r\n");
 }
 
-void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params){
-    pc.printf("disconnected\r\n");
+
+/**
+ * Callback triggered when the ble initialization process has finished
+ */
+void bleInitComplete(BLE::InitializationCompleteCallbackContext *params)
+{
+    BLE&        ble   = params->ble;
+
+    pc.printf("Ble Init\n\r");
+    /* Ensure that it is the default instance of BLE */
+    if(ble.getInstanceID() != BLE::DEFAULT_INSTANCE) {
+        return;
+    }
+ 
+    ble.gap().onConnection(connectionCallback);
+    ble.gap().onDisconnection(disconnectionCallback);
     
-    for(uint8_t i=0; i<3; i++){
-        if(gs_peripheral[i].handle == params->handle){
-            gs_peripheral[i].connected = false;
-            gs_peripheral[i].handle = 0xFFFF;
-        }
-    }
-    wait(8.0);
-   // ble.gap().startScan(scanCallback);
+    ble.gap().setScanParams(1000, 800);
+    ble.gap().startScan(advertisementCallback);
 }
 
 int main(void) {
     pc.baud(9600);
     wait(8.0);
-    pc.printf("start\r\n");
-
-    ble.init();
-
-    ble.onConnection(connectionCallback);
-    ble.onDisconnection(disconnectionCallback);
-   // ble.gattClient().onServiceDiscoveryTermination(discoveryTerminationCallback);
-   // ble.gattClient().onDataRead(triggerRead);
-    //ble.gattClient().onDataWrite(triggerToggledWrite);
-    
-    ble.gap().setScanParams(600, 400);
-    ble.gap().startScan(scanCallback);
-    //ble.startAdvertising();
+    pc.printf("Start\n\r");
+    BLE &ble = BLE::Instance();
+   
+    ble.init(bleInitComplete);
+  
     while (true) {
-        ble.waitForEvent();
+               ble.waitForEvent();
     }
-}
\ No newline at end of file
+}