//------------------------------------------------------------------------------
//-- BluNodeV1_02
//------------------------------------------------------------------------------

#include "mbed.h"
#include "BLE.h"
#include "UARTService.h"

#include "nrf.h"
#include "nrf_temp.h"
#include "nrf_gpio.h"

#define NEED_CONSOLE_OUTPUT 0 /*  Set this if you need debug messages on the console;
* it will have an impact on code-size and power consumption. */

#if NEED_CONSOLE_OUTPUT
#define DEBUG(...) { printf(__VA_ARGS__); }
#else
#define DEBUG(...)
#endif

//------------------------------------------------------------------------------
//-- Atributtes
//------------------------------------------------------------------------------

UARTService *uartServicePtr;
BLE ble;
Ticker t;
Timeout timeoutTimer;
DigitalOut activeLed(LED1, 1);
DigitalOut connectLed(LED2, 0);
DigitalIn  button1(BUTTON1);  // used to trigger the time report
InterruptIn button1Press(BUTTON1);




//------------------------------------------------------------------------------
//-- Definitions - Parameters
//------------------------------------------------------------------------------

const static char     DEVICE_NAME[] = "Blu_019";
#define     COMPANY_ID  0x3322

#define     BLUCORE_ADV_LENGHT          0x10    // 2 + 1 + 13
#define     BLUCORE_ADV_PAYLOAD_OFFSET  0x03    // 3
#define     BLUCORE_ADV_PAYLOAD_LENGHT  0x0D    // 13
#define     BLUCORE_BLUNODE_TYPE_01     0x01
#define     BLUCORE_COMPANY_ID          0xC7AB


#define     BLUCORE_ADC_IN1             1
#define     BLUCORE_ADC_IN2             2
#define     BLUCORE_ADC_IN3             3
#define     BLUCORE_ADC_IN4             4
#define     BLUCORE_ADC_IN5             5
#define     BLUCORE_ADC_IN6             6
#define     BLUCORE_ADC_IN7             7
#define     BLUCORE_ADC_IN8             8











//------------------------------------------------------------------------------
//-- Definition - Structures
//------------------------------------------------------------------------------

typedef struct {
    uint16_t    CompanyId;
    uint8_t     Type;
    uint8_t     RawData[BLUCORE_ADV_PAYLOAD_LENGHT];

} BLUCORE_DATA_PAYLOAD_Type;

typedef struct {
    uint16_t    CompanyId;
    uint8_t     Type;
    uint8_t     RawData[BLUCORE_ADV_PAYLOAD_LENGHT];
} BluCore_DataPayload_Type;

typedef struct {
    uint16_t    CompanyId;      // 2 bytes
    uint8_t     Type;           // 1 byte
    uint16_t    Counter;        // 2 bytes
    uint16_t    ADC1;           // 2 bytes
    uint16_t    ADC2;           // 2 bytes
    uint16_t    ADC3;           // 2 bytes
    uint16_t    ADC4;           // 2 bytes
    uint8_t     DataTail[3];    // 3 bytes

} BluCore_DataPayload_01_Type;




union BluCore_DataPayload_Base {
    uint8_t raw[BLUCORE_ADV_LENGHT];
    struct {
        uint16_t    CompanyId;
        uint8_t     Type;
        uint16_t    Counter;
        uint16_t    ADC1;
        uint16_t    ADC2;
        uint16_t    ADC3;
        uint16_t    ADC4;
        uint8_t     DataTail[3];
    };
};




















//------------------------------------------------------------------------------
//-- Variables
//------------------------------------------------------------------------------

static int advCount=0;
bool isConnected=false;
int advActivePeriod;
int sleepActivePeriod;

//uint8_t AdvData[] = {(COMPANY_ID & 0xFF), ((COMPANY_ID >> 8) & 0xFF),0x01,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x10,0x11, 0x12,0x13};


BLUCORE_DATA_PAYLOAD_Type AdvData;

BluCore_DataPayload_Type * DataPayload;

static int value0,value1,value2,value3; // stored voltage reading from ADC


static int adcValue1;
static int adcValue2;
static int adcValue3;
static int adcValue4;

static uint16_t blucore_adc_in1_value;
static uint16_t blucore_adc_in2_value;
static uint16_t blucore_adc_in3_value;
static uint16_t blucore_adc_in4_value;
static uint16_t blucore_adc_in5_value;
static uint16_t blucore_adc_in6_value;
static uint16_t blucore_adc_in7_value;
static uint16_t blucore_adc_in8_value;

static uint8_t  blucore_soc_temp;

char dataOu[30];


static uint32_t m_soc_temp;

static uint16_t adv_counter = 0;

static uint16_t m_AdvertisingInterval = 0;

uint16_t m_blu_analogin_read_counter = 0;














//------------------------------------------------------------------------------
//Connection Call Back
//------------------------------------------------------------------------------

void connectionCallback(const Gap::ConnectionCallbackParams_t *params)
{
    //DEBUG("Connected \n");

    connectLed=1;
    isConnected=true;

}
// Disconnection Call Back
void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params)
{
    //DEBUG("Disconnected!\n\r");
    //DEBUG("Restarting the advertising process\n\r");
    ble.startAdvertising();
    activeLed=1;
    connectLed=0;
    isConnected=false;
    advCount=0;
}



//------------------------------------------------------------------------------
//-- Inicialización de canales ADC
//------------------------------------------------------------------------------

//Analog Initialize
void my_analogin_init(void)
{

    NRF_ADC->ENABLE = ADC_ENABLE_ENABLE_Enabled;
    NRF_ADC->CONFIG = (ADC_CONFIG_RES_10bit << ADC_CONFIG_RES_Pos) |                                //Configure Resolution to 10 bits
                      (ADC_CONFIG_INPSEL_AnalogInputOneThirdPrescaling << ADC_CONFIG_INPSEL_Pos) |  //Configure ADC input selection and prescalar settings
                      //Internal reference voltage of 1.2V. Onethird prescaling -> 3.6V
                      (ADC_CONFIG_REFSEL_VBG << ADC_CONFIG_REFSEL_Pos) |                            //ADC reference selection to internal 1.2V VBG
                      (ADC_CONFIG_PSEL_AnalogInput0 << ADC_CONFIG_PSEL_Pos) |                       //Select Pin to be used as ADC input pin -> Disable analog pins
                      (ADC_CONFIG_EXTREFSEL_None << ADC_CONFIG_EXTREFSEL_Pos);                      //Select external reference pin -> No external reference (we use internal reference of 1.2V)
}











//------------------------------------------------------------------------------
//-- Lectura de temperatura interna del CPU
//------------------------------------------------------------------------------

void my_soc_temperature_read(void)
{
    uint8_t result = 0;
    
    NRF_TEMP->TASKS_START = 1;
    while (NRF_TEMP->EVENTS_DATARDY == 0) {}
    NRF_TEMP->EVENTS_DATARDY = 0;
    m_soc_temp = NRF_TEMP->TEMP ;
    NRF_TEMP->TASKS_STOP = 1;
}

uint8_t blucore_soc_temperature_read(void)
{
    uint8_t result = 0;
    
    NRF_TEMP->TASKS_START = 1;
    while (NRF_TEMP->EVENTS_DATARDY == 0) {}
    NRF_TEMP->EVENTS_DATARDY = 0;
    m_soc_temp = NRF_TEMP->TEMP ;
    result = (uint8_t) (( m_soc_temp & 0x000000FF) & 0xFF );
    NRF_TEMP->TASKS_STOP = 1;

    return (result);

}

//------------------------------------------------------------------------------

















//------------------------------------------------------------------------------
//--
//------------------------------------------------------------------------------

void my_analogin_read_u16A0(void)
{

    NRF_ADC->CONFIG   &= ~ADC_CONFIG_PSEL_Msk;                                                    // Check if Analog input pin has been selected
    NRF_ADC->CONFIG   |= ADC_CONFIG_PSEL_AnalogInput2 << ADC_CONFIG_PSEL_Pos;                      //Check if Analog Input pin has been selected
    NRF_ADC->TASKS_START = 1;
    while (((NRF_ADC->BUSY & ADC_BUSY_BUSY_Msk) >> ADC_BUSY_BUSY_Pos) == ADC_BUSY_BUSY_Busy) {}   //Produce ADC value only when ADC is not busy
    value0 = (uint16_t) NRF_ADC -> RESULT;

    //DEBUG("A0 Value = %i \n\r",value0);
}


void my_analogin_read_u16A1(void)
{

    NRF_ADC->CONFIG   &= ~ADC_CONFIG_PSEL_Msk;                                                    // Check if Analog input pin has been selected
    NRF_ADC->CONFIG   |= ADC_CONFIG_PSEL_AnalogInput3 << ADC_CONFIG_PSEL_Pos;                      //Check if Analog Input pin has been selected
    NRF_ADC->TASKS_START = 1;
    while (((NRF_ADC->BUSY & ADC_BUSY_BUSY_Msk) >> ADC_BUSY_BUSY_Pos) == ADC_BUSY_BUSY_Busy) {}   //Produce ADC value only when ADC is not busy
    value1 = (uint16_t) NRF_ADC -> RESULT;
    DEBUG("A1 Value = %i \n\r",value1);
}


void my_analogin_read_u16A2(void)
{

    NRF_ADC->CONFIG   &= ~ADC_CONFIG_PSEL_Msk;                                                    // Check if Analog input pin has been selected
    NRF_ADC->CONFIG   |= ADC_CONFIG_PSEL_AnalogInput4 << ADC_CONFIG_PSEL_Pos;                      //Check if Analog Input pin has been selected
    NRF_ADC->TASKS_START = 1;
    while (((NRF_ADC->BUSY & ADC_BUSY_BUSY_Msk) >> ADC_BUSY_BUSY_Pos) == ADC_BUSY_BUSY_Busy) {}   //Produce ADC value only when ADC is not busy
    value2 = (uint16_t) NRF_ADC -> RESULT;
    DEBUG("A2 Value = %i \n\r",value2);
}


void my_analogin_read_u16A3(void)
{

    NRF_ADC->CONFIG   &= ~ADC_CONFIG_PSEL_Msk;                                                    // Check if Analog input pin has been selected
    NRF_ADC->CONFIG   |= ADC_CONFIG_PSEL_AnalogInput5 << ADC_CONFIG_PSEL_Pos;                      //Check if Analog Input pin has been selected
    NRF_ADC->TASKS_START = 1;
    while (((NRF_ADC->BUSY & ADC_BUSY_BUSY_Msk) >> ADC_BUSY_BUSY_Pos) == ADC_BUSY_BUSY_Busy) {}   //Produce ADC value only when ADC is not busy
    value3 = (uint16_t) NRF_ADC -> RESULT;
    DEBUG("A3 Value = %i \n\r",value3);
}




//------------------------------------------------------------------------------
//-- lectura de valor canal ADC (1...8)
//------------------------------------------------------------------------------

uint16_t blu_analogin_read(int adcChannel)
{
    uint16_t result = 0;

    if (adcChannel > 0 && adcChannel < 9) {

        NRF_ADC->CONFIG   &= ~ADC_CONFIG_PSEL_Msk;
        
        switch (adcChannel) {
            case 1:
                NRF_ADC->CONFIG   |= ADC_CONFIG_PSEL_AnalogInput0 << ADC_CONFIG_PSEL_Pos;
                break;
            case 2:
                NRF_ADC->CONFIG   |= ADC_CONFIG_PSEL_AnalogInput1 << ADC_CONFIG_PSEL_Pos;
                break;
            case 3:
                NRF_ADC->CONFIG   |= ADC_CONFIG_PSEL_AnalogInput2 << ADC_CONFIG_PSEL_Pos;
                break;
            case 4:
                NRF_ADC->CONFIG   |= ADC_CONFIG_PSEL_AnalogInput3 << ADC_CONFIG_PSEL_Pos;
                break;
            case 5:
                NRF_ADC->CONFIG   |= ADC_CONFIG_PSEL_AnalogInput4 << ADC_CONFIG_PSEL_Pos;
                break;
            case 6:
                NRF_ADC->CONFIG   |= ADC_CONFIG_PSEL_AnalogInput5 << ADC_CONFIG_PSEL_Pos;
                break;
            case 7:
                NRF_ADC->CONFIG   |= ADC_CONFIG_PSEL_AnalogInput6 << ADC_CONFIG_PSEL_Pos;
                break;
            case 8:
                NRF_ADC->CONFIG   |= ADC_CONFIG_PSEL_AnalogInput7 << ADC_CONFIG_PSEL_Pos;
                break;
            default:
                break;
        }

        NRF_ADC->TASKS_START = 1;

        while (((NRF_ADC->BUSY & ADC_BUSY_BUSY_Msk) >> ADC_BUSY_BUSY_Pos) == ADC_BUSY_BUSY_Busy) { }

        result = (uint16_t) NRF_ADC -> RESULT;

    }

    return (result);

}







//------------------------------------------------------------------------------
//--
//------------------------------------------------------------------------------

void advReset(void)
{



// Demo AdvDataPayload

    AdvData.CompanyId = BLUCORE_COMPANY_ID;
    AdvData.Type = BLUCORE_BLUNODE_TYPE_01;
    AdvData.RawData[0]  = (adv_counter >> 8)&0xFF;
    AdvData.RawData[1]  = adv_counter & 0xFF;
    AdvData.RawData[2]  = 0xA1;
    AdvData.RawData[3]  = 0xB1;
    AdvData.RawData[4]  = 0xA2;
    AdvData.RawData[5]  = 0xB2;
    AdvData.RawData[6]  = 0xA3;
    AdvData.RawData[7]  = 0xB3;
    AdvData.RawData[8]  = 0xA4;
    AdvData.RawData[9]  = 0xB4;
    AdvData.RawData[10] = 0x11;
    AdvData.RawData[11] = 0x12;
    AdvData.RawData[12] = (uint8_t) (( m_soc_temp & 0x000000FF) & 0xFF );

    /*
    AdvData[0]  = 0x22; // 0xCA;
    AdvData[1]  = 0x33; // 0xFE

    AdvData[2]  = 0x01;

    AdvData[3]  = 0xA1;
    AdvData[4]  = 0xA2;
    AdvData[5]  = 0xA3;
    AdvData[6]  = 0xA4;
    AdvData[7]  = 0xA4;
    AdvData[8]  = 0xA6;
    AdvData[9]  = 0xA7;
    AdvData[10] = 0xA8;
    AdvData[11] = 0xA9;
    AdvData[12] = 0x10;
    AdvData[13] = 0x11;
    AdvData[14] = 0x12;
    AdvData[15] = 0x13;
    */







//AdvData[3]=(value1  & 0xFF);
//AdvData[2]=((value1 >> 8) & 0xFF);

//AdvData[5]=(value2  & 0xFF);
//AdvData[4]=((value2 >> 8) & 0xFF);

//AdvData[7]=(value3  & 0xFF);
//AdvData[6]=((value3 >> 8) & 0xFF);

//AdvData[9]=(value0  & 0xFF);
//AdvData[8]=((value0 >> 8) & 0xFF);



//AdvData[10] = (uint8_t) (( m_soc_temp & 0xFF000000) >> 24) & 0xFF;
//AdvData[11] = (uint8_t) (( m_soc_temp & 0x00FF0000) >> 16) & 0xFF;
//AdvData[12] = (uint8_t) (( m_soc_temp & 0x0000FF00) >> 8) & 0xFF;
//AdvData[13] = (uint8_t) (( m_soc_temp & 0x000000FF) & 0xFF );

    ble.stopAdvertising();
    ble.clearAdvertisingPayload();
    ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED);
    ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
    ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
    ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));

    uint8_t payload[BLUCORE_ADV_LENGHT] = {
        (AdvData.CompanyId>>8)&0xFF,
        AdvData.CompanyId & 0xFF,
        AdvData.Type,
        AdvData.RawData[0],
        AdvData.RawData[1],
        AdvData.RawData[2],
        AdvData.RawData[3],
        AdvData.RawData[4],
        AdvData.RawData[5],
        AdvData.RawData[6],
        AdvData.RawData[7],
        AdvData.RawData[8],
        AdvData.RawData[9],
        AdvData.RawData[10],
        AdvData.RawData[11],
        AdvData.RawData[12]
    };




    //adv_counter
    DataPayload->CompanyId = BLUCORE_COMPANY_ID;
    DataPayload->Type = BLUCORE_BLUNODE_TYPE_01;
    DataPayload->RawData[0]  = (adv_counter >> 8)&0xFF;
    DataPayload->RawData[1]  = adv_counter & 0xFF;
    DataPayload->RawData[2]  = 0x00;
    DataPayload->RawData[3]  = 0x00;
    DataPayload->RawData[4]  = 0x11;
    DataPayload->RawData[5]  = 0x11;
    DataPayload->RawData[6]  = 0x22;
    DataPayload->RawData[7]  = 0x22;
    DataPayload->RawData[8]  = 0x33;
    DataPayload->RawData[9]  = 0x33;
    DataPayload->RawData[10] = 0x00;
    DataPayload->RawData[11] = 0x00;
    DataPayload->RawData[12] = (uint8_t) (( m_soc_temp & 0x000000FF) & 0xFF );



//uint8_t dpayload[BLUCORE_ADV_LENGHT];
//memcpy(dpayload, DataPayload, sizeof(dpayload));



    uint8_t dpayload[BLUCORE_ADV_LENGHT] = {
        (DataPayload->CompanyId>>8)& 0xFF,
        DataPayload->CompanyId & 0xFF,
        DataPayload->Type,
        DataPayload->RawData[0],
        DataPayload->RawData[1],
        DataPayload->RawData[2],
        DataPayload->RawData[3],
        DataPayload->RawData[4],
        DataPayload->RawData[5],
        DataPayload->RawData[6],
        DataPayload->RawData[7],
        DataPayload->RawData[8],
        DataPayload->RawData[9],
        DataPayload->RawData[10],
        DataPayload->RawData[11],
        DataPayload->RawData[12]
    };





    /*    [0],
        DataPayload->RawData[1],
        DataPayload.RawData[2],
        DataPayload.RawData[3],
        DataPayload->RawData[4],
        DataPayload->RawData[5],
        DataPayload->RawData[6],
        DataPayload->RawData[7],
        DataPayload->RawData[8],
        DataPayload->RawData[9],
        DataPayload->RawData[10],
        DataPayload->RawData[11],
        DataPayload->RawData[12]
    };
    */



    ble.accumulateAdvertisingPayload(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA, payload, sizeof(payload));

    ble.setAdvertisingInterval(300);
    ble.startAdvertising();
}

//------------------------------------------------------------------------------




















//------------------------------------------------------------------------------
//-- Callback function: Lectura de canales ADC
//------------------------------------------------------------------------------

void my_analogin_read(void)
{
    if(!isConnected) {
        
        m_blu_analogin_read_counter++;
        
        advCount++;
        adv_counter++;
        wait_ms(100);
        
        //my_analogin_read_u16A0();
        blucore_adc_in1_value = blu_analogin_read(BLUCORE_ADC_IN1);
        
        wait_ms(100);
        
        //my_analogin_read_u16A1();
        blucore_adc_in2_value = blu_analogin_read(BLUCORE_ADC_IN2);
        
        wait_ms(100);
        //my_analogin_read_u16A2();
        blucore_adc_in3_value = blu_analogin_read(BLUCORE_ADC_IN3);
        
        wait_ms(100);
        //my_analogin_read_u16A3();
        blucore_adc_in4_value = blu_analogin_read(BLUCORE_ADC_IN4);
        
        wait_ms(100);
        
        
        blucore_soc_temp = blucore_soc_temperature_read();
        
        wait_ms(100);
        advReset();
    }
}

//------------------------------------------------------------------------------





















//------------------------------------------------------------------------------
//--
//------------------------------------------------------------------------------

void onDataWritten(const GattWriteCallbackParams *params)
{
    if ((uartServicePtr != NULL) && (params->handle == uartServicePtr->getTXCharacteristicHandle())) {
        uint16_t bytesRead = params->len;
        DEBUG("received %u bytes\n\r", bytesRead);
        if (strncmp("param1=",(const char *)params->data,7)==0) {
            sscanf((const char *)params->data,"param1=%i",&advActivePeriod);
            sprintf(dataOu,"Adver=%i sec\n",advActivePeriod);
            DEBUG("%s",dataOu);
            ble.updateCharacteristicValue(uartServicePtr->getRXCharacteristicHandle(),(const uint8_t *)dataOu , 20);

        } else if (strncmp("param2=",(const char *)params->data,7)==0) {
            sscanf((const char *)params->data,"param2=%i",&sleepActivePeriod);
            sprintf(dataOu,"Sleep=%i sec\n",sleepActivePeriod);
            DEBUG("%s",dataOu);
            ble.updateCharacteristicValue(uartServicePtr->getRXCharacteristicHandle(),(const uint8_t *)dataOu, 20);

        } else if (strncmp("scan",(const char *)params->data,4)==0) {
            DEBUG("Scanning\n");

            my_analogin_read_u16A0();
            sprintf(dataOu,"A0=%i \n",value0);

            DEBUG("%s",dataOu);
            ble.updateCharacteristicValue(uartServicePtr->getRXCharacteristicHandle(),(const uint8_t *)dataOu, 20);
            wait(5);
            my_analogin_read_u16A1();
            sprintf(dataOu,"A1=%i \n",value1);
            DEBUG("%s",dataOu);
            ble.updateCharacteristicValue(uartServicePtr->getRXCharacteristicHandle(),(const uint8_t *)dataOu, 20);
            wait(5);
            my_analogin_read_u16A2();
            sprintf(dataOu,"A2=%i \n",value2);
            DEBUG("%s",dataOu);

            ble.updateCharacteristicValue(uartServicePtr->getRXCharacteristicHandle(),(const uint8_t *)dataOu, 20);
            wait(5);
            my_analogin_read_u16A3();
            sprintf(dataOu,"A3=%i \n",value3);
            DEBUG("%s",dataOu);
            ble.updateCharacteristicValue(uartServicePtr->getRXCharacteristicHandle(),(const uint8_t *)dataOu, 20);


        }



    }
}

//------------------------------------------------------------------------------





















//------------------------------------------------------------------------------
//-- Función de EVENTO PressButton 1
//------------------------------------------------------------------------------

void advActiveFunc (void)
{
    //DEBUG("\n BT WAKE UP!!");
    activeLed=1;
    timeoutTimer.detach();
    advCount=0;

    t.attach(my_analogin_read,1);

}

//------------------------------------------------------------------------------




















//------------------------------------------------------------------------------
//--
//------------------------------------------------------------------------------

void SleepFunc(void)
{
    t.attach(my_analogin_read,1); //repeatedly read analog every second.
    //DEBUG("\nWAKE UP!!");
    activeLed=1;


}







//------------------------------------------------------------------------------
//--
//------------------------------------------------------------------------------

void BLE_Shutdown()
{
    ble.stopAdvertising();
    ble.clearAdvertisingPayload();
}






//------------------------------------------------------------------------------
//-- Funciones BluCore
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
//-- Inicialización de datos del advertisng
//------------------------------------------------------------------------------

void blunode_adv_Init()
{
    /* DEMO DATA */

    AdvData.CompanyId = 0x3322;
    AdvData.Type = 0x01;

    AdvData.RawData[0]  = 0xA1;
    AdvData.RawData[1]  = 0xA2;
    AdvData.RawData[2]  = 0xA3;
    AdvData.RawData[3]  = 0xA4;
    AdvData.RawData[4]  = 0xA5;
    AdvData.RawData[5]  = 0xA6;
    AdvData.RawData[6]  = 0xA7;
    AdvData.RawData[7]  = 0xA8;
    AdvData.RawData[8]  = 0xA9;
    AdvData.RawData[9]  = 0x10;
    AdvData.RawData[10] = 0x11;
    AdvData.RawData[11] = 0x12;
    AdvData.RawData[12] = 0x13;

    uint8_t payload[sizeof(AdvData)] = {
        (AdvData.CompanyId>>8)&0xFF,
        AdvData.CompanyId & 0xFF,
        AdvData.Type,
        AdvData.RawData[0],
        AdvData.RawData[1],
        AdvData.RawData[2],
        AdvData.RawData[3],
        AdvData.RawData[4],
        AdvData.RawData[5],
        AdvData.RawData[6],
        AdvData.RawData[7],
        AdvData.RawData[8],
        AdvData.RawData[9],
        AdvData.RawData[10],
        AdvData.RawData[11],
        AdvData.RawData[12]
    };


    DataPayload->CompanyId = BLUCORE_COMPANY_ID;
    DataPayload->Type = BLUCORE_BLUNODE_TYPE_01;
    DataPayload->RawData[0]  = 1;
    DataPayload->RawData[1]  = 2;
    DataPayload->RawData[2]  = 3;
    DataPayload->RawData[3]  = 4;
    DataPayload->RawData[4]  = 5;
    DataPayload->RawData[5]  = 6;
    DataPayload->RawData[6]  = 7;
    DataPayload->RawData[7]  = 8;
    DataPayload->RawData[8]  = 9;
    DataPayload->RawData[9]  = 10;
    DataPayload->RawData[10] = 11;
    DataPayload->RawData[11] = 12;
    DataPayload->RawData[12] = 13;

    m_AdvertisingInterval = 600;

    ble.onDisconnection(disconnectionCallback);
    ble.onDataWritten(onDataWritten);
    ble.onConnection(connectionCallback);

    /* setup advertising */
    ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED);
    ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
    ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));


    ble.accumulateAdvertisingPayload(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA, payload, sizeof(payload));

    //ble.accumulateAdvertisingPayload(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA, (uint8_t *) DataPayload, sizeof(DataPayload));



    // 20 ms adv. interval
    ble.setAdvertisingInterval(20);



}



//------------------------------------------------------------------------------
//-- Inicio de advertising
//------------------------------------------------------------------------------

void blunode_adv_start()
{
    ble.startAdvertising();



}

//------------------------------------------------------------------------------
























//------------------------------------------------------------------------------
//-- Main: BluNode
//------------------------------------------------------------------------------

int main(void)
{

    /* Inicialización de la medición de temperatura interna */

    nrf_temp_init();

    /* Inicialización stack BLE */

    ble.init();

    /* Inicialización de advertising */

    blunode_adv_Init();

    /* Inicialización de medición análoga */

    my_analogin_init(); //Initialize ADC settings


    /* Inicialización de servicios UART */
    
    UARTService uartService(ble);
    uartServicePtr = &uartService;



    button1Press.fall(&advActiveFunc);


    blunode_adv_start();
    
    
    
    advActivePeriod   = 10;
    sleepActivePeriod = 30;
    t.attach(my_analogin_read,1); //second.
    advActivePeriod = 1;








    /* Infinite Loop*/

    while(true) {
        ble.waitForEvent();

        if (advCount > advActivePeriod) {

            wait_ms(50);
            t.detach ();
            activeLed=0;

            BLE_Shutdown();

            //sleepCall.attach(SleepFunc,sleepActivePeriod);
            
            // Wait 60 sec.
            //sleepCall.attach(SleepFunc,30);
            timeoutTimer.attach(SleepFunc,30);
timeoutTimer.attach(SleepFunc,30);
            
            advCount=0;
        }

    }
}

//------------------------------------------------------------------------------









