Team HUB / Mbed 2 deprecated nRF51822_Fresh

Dependencies:   BLE_API mbed nRF51822

Fork of nRF51822_Updated by Nicholas Hazen

main.cpp

Committer:
feralwookie7
Date:
2015-08-05
Revision:
5:5e55081e4d7a
Parent:
4:2f9c7d53a099
Child:
6:6e0eedc8e0a9

File content as of revision 5:5e55081e4d7a:

/*

Copyright (c) 2012-2014 RedBearLab

Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
and associated documentation files (the "Software"), to deal in the Software without restriction, 
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, 
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, 
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE 
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

/*
 *    The application works with the BLEController iOS/Android App.
 *    Type something from the Terminal to send
 *    to the BLEController App or vice verse.
 *    Characteristics received from App will print on Terminal.
 */
 
#include "mbed.h"
#include "ble/BLE.h"


#define BLE_UUID_TXRX_SERVICE            0x0000 /**< The UUID of the Nordic UART Service. */
#define BLE_UUID_TX_CHARACTERISTIC       0x0002 /**< The UUID of the TX Characteristic. */
#define BLE_UUIDS_RX_CHARACTERISTIC      0x0003 /**< The UUID of the RX Characteristic. */

#define TXRX_BUF_LEN                     20 //maximum payload: 20 bytes per packet

#define MIN_CONN_INTERVAL 6 //lowest possible connection interval (6 * 1.25 = 7.5ms)
#define MAX_CONN_INTERVAL 6
#define SLAVE_LATENCY 0 //lowest possible
#define CONN_SUP_TIMEOUT 6000 //default; changing this value has not been shown to make a difference in data transfer rate

BLE ble;

Serial pc(USBTX, USBRX);


// The Nordic UART Service
static const uint8_t uart_base_uuid[] = {0x71, 0x3D, 0, 0, 0x50, 0x3E, 0x4C, 0x75, 0xBA, 0x94, 0x31, 0x48, 0xF1, 0x8D, 0x94, 0x1E};
static const uint8_t uart_tx_uuid[]   = {0x71, 0x3D, 0, 3, 0x50, 0x3E, 0x4C, 0x75, 0xBA, 0x94, 0x31, 0x48, 0xF1, 0x8D, 0x94, 0x1E};
static const uint8_t uart_rx_uuid[]   = {0x71, 0x3D, 0, 2, 0x50, 0x3E, 0x4C, 0x75, 0xBA, 0x94, 0x31, 0x48, 0xF1, 0x8D, 0x94, 0x1E};
static const uint8_t uart_base_uuid_rev[] = {0x1E, 0x94, 0x8D, 0xF1, 0x48, 0x31, 0x94, 0xBA, 0x75, 0x4C, 0x3E, 0x50, 0, 0, 0x3D, 0x71};


uint8_t txPayload[TXRX_BUF_LEN] = {0,};
uint8_t rxPayload[TXRX_BUF_LEN] = {0,};

static uint8_t rx_buf[TXRX_BUF_LEN];
static uint8_t rx_len=0;

uint8_t packet1[]  =  {0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34};
uint8_t packet2[]  =  {0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48};
uint8_t packet3[]  =  {0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c};

int i = 0;
int currentTrial = 0;
int totalTrials = 100;

Timer t;
float times[100];

DigitalOut myled(LED1); //corresponds to pin 13 on nRF51822

GattCharacteristic  txCharacteristic (uart_tx_uuid, txPayload, 1, TXRX_BUF_LEN, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE);//GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE | 

GattCharacteristic  rxCharacteristic (uart_rx_uuid, rxPayload, 1, TXRX_BUF_LEN, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY);

GattCharacteristic *uartChars[] = {&txCharacteristic, &rxCharacteristic};

GattService         uartService(uart_base_uuid, uartChars, sizeof(uartChars) / sizeof(GattCharacteristic *));


void writePackets(void);

void disconnectionCallback(Gap::Handle_t handle, Gap::DisconnectionReason_t reason)
{
    //pc.printf("Disconnected \r\n");
    //pc.("Restart advertising \r\n");
    ble.startAdvertising();
}

void WrittenHandler(const GattWriteCallbackParams *Handler)
{   
    uint8_t buf[TXRX_BUF_LEN];
    uint16_t bytesRead, index;
    
    if (Handler->handle == txCharacteristic.getValueAttribute().getHandle()) 
    {
        //myled = 1;
        //pc.("T b4 pckt received: %f\r\n", t.read()); //time before packet received in seconds
        ble.readCharacteristicValue(txCharacteristic.getValueAttribute().getHandle(), buf, &bytesRead);
        
        ble.readCharacteristicValue(txCharacteristic.getValueAttribute().getHandle(), buf, &bytesRead);
        //t.stop();
        myled = 0;
        times[currentTrial] = t.read();
        //pc.printf("%f\r\n", t.read()); //Total time in seconds

        bytesRead = 20;
        memset(txPayload, 0, TXRX_BUF_LEN);
        memcpy(txPayload, buf, TXRX_BUF_LEN);
        //pc.("WriteHandler \r\n");
        //pc.("Length: ");
        //pc.putc(bytesRead);
        //pc.("\r\n");
        //pc.("Data: ");
        /*for(index=0; index<bytesRead; index++) {
            //pc.putc((char)txPayload[index]);
        }
        //pc.("\r\n");
        
        //t.reset();
        //pc.("T RESET \r\n");*/
        currentTrial++;
        
        if(currentTrial < totalTrials)
        {
            //pc.("CT < TT \r\n"); //Current trial less than total trials
            //wait(1);
            
            writePackets();
        }
        else
        {
            float difference = 0.0;
            
            for(int j = 0; j<totalTrials; j++)
            {
                if(j == 0)
                {
                    pc.printf("%5.3f\r\n", times[j]);
                }
                    else
                    {
                        difference = times[j] - times[j - 1];
                        pc.printf("%5.3f\r\n", difference);
                    }
            }
            /*float total = 0.0, avg = 0.0;
            for(int m = 0; m<totalTrials; m++)
            {
                total = total + times[m];
            }
                
            avg = total/100.0;
            pc.printf("AVG: %5.3f\r\n", avg);
            //pc.("Done. %d trials completed.\r\n", currentTrial);*/
        }  
    }
}

void uartCB(void)
{   
    while(pc.readable())    
    {
        rx_buf[rx_len++] = pc.getc();    
        if(rx_len>=20 || rx_buf[rx_len-1]=='\0' || rx_buf[rx_len-1]=='\n')
        {
            ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), rx_buf, rx_len); 
            //pc.("RecHandler \r\n");
            //pc.("Length: ");
            pc.putc(rx_len);
            //pc.("\r\n");
            rx_len = 0;
            break;
        }
    }
}

void writePackets(void)
{
    /*
    while(pc.readable())
    {
        rx_buf[rx_len++] = pc.getc();
        if(rx_len>=20 || rx_buf[rx_len-1]=='\0' || rx_buf[rx_len-1]=='\n')
        {
            ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), rx_buf, rx_len);
            pc.("RecHandler \r\n");
            pc.("Length: ");
            pc.putc(rx_len);
            pc.("\r\n");
            rx_len = 0;
            break;
        }
    }
    */

    //pc.("Updating Characteristic... \r\n");

    if(currentTrial < 1)
    {
    wait(1); //trials have shown that the code will not run without a delay before the first trial
    t.start();
    }
    //t.start();
    //pc.("T START \r\n");

    myled = 1;
    ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), packet1, 20);
    //myled = 0;
    //pc.("T after pckt 1 sent: %f\r\n", t.read());
    //myled = 1;
    ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), packet2, 20);
    //myled = 0;
    //pc.("T after pckt 2 sent: %f\r\n", t.read());
    //myled = 1;
    ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), packet3, 20);
    //myled = 0;
    //pc.("T after pckt 3 sent: %f\r\n", t.read());
    
    currentTrial++;
    
    if 
    
    myled = 0;
    times[currentTrial] = t.read();
}

int main(void)
{
    ble.init();
    ble.onDisconnection(disconnectionCallback);
    ble.onDataWritten(WrittenHandler);  
    
    pc.baud(460800);
    //pc.("SimpleChat Init \r\n");
    
    pc.attach( uartCB , pc.RxIrq);
   // setup advertising 
    ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED);
    ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
    ble.accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME,
                                    (const uint8_t *)"Megatron", sizeof("Megatron") - 1);
    ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS,
                                    (const uint8_t *)uart_base_uuid_rev, sizeof(uart_base_uuid));
    // 100ms; in multiples of 0.625ms. 
    ble.setAdvertisingInterval(160);

    ble.addService(uartService);
    
    ble.startAdvertising(); 
    //pc.("Advertising Start \r\n");
    
   while(1) 
    {
        //wait(1);
        //pc.("BEFORE BLE WAIT 4 EVENTS \r\n");
        ble.waitForEvent();
        //pc.("AFTER BLE WAIT 4 EVENTS \r\n");
        if(i == 0) 
        {
            //pc.("LAST IF STATEMENT TRUE \r\n");
            writePackets();
            i++;
        }
    }
}