Gustavo Belduma / Mbed 2 deprecated nRF51822_SimpleControls

Dependencies:   BLE_API mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 /*
00002 Copyright (c) 2012-2014 RedBearLab
00003 
00004 Permission is hereby granted, free of charge, to any person obtaining a copy of this software
00005 and associated documentation files (the "Software"), to deal in the Software without restriction,
00006 including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
00007 and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
00008 subject to the following conditions:
00009 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
00010 
00011 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
00012 INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
00013 PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
00014 FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
00015 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
00016 
00017 */
00018 
00019 #include "mbed.h"
00020 #include "ble/BLE.h"
00021 #include "GattCallbackParamTypes.h"
00022 
00023 #define BLE_UUID_TXRX_SERVICE            0x0000 /**< The UUID of the Nordic UART Service. */
00024 #define BLE_UUID_TX_CHARACTERISTIC       0x0002 /**< The UUID of the TX Characteristic. */
00025 #define BLE_UUIDS_RX_CHARACTERISTIC      0x0003 /**< The UUID of the RX Characteristic. */
00026 
00027 #define TXRX_BUF_LEN                     20
00028 
00029 #define DIGITAL_OUT_7                    P0_17  //D7
00030 #define DIGITAL_OUT_8                    P0_19  //D8
00031 #define DIGITAL_OUT_11                   P0_12  //D11
00032 #define DIGITAL_OUT_4                    P0_21  //D4
00033 
00034 #define DIGITAL_IN_PIN                   P0_5   //A4
00035 
00036 #define PWM_PIN                          P0_16  //D6
00037 #define ANALOG_IN_PIN                    P0_6   //A5
00038 
00039 // Declarando los pines
00040 //static int32_t send_config = 0;
00041 static int32_t enviar_config_01 = 0;
00042 
00043 // variables semaforos que me permiten identificar si se debe o no enviar las tramas de configuracion de cada sensor.
00044 static int32_t sen_analog_in_5 = 0;
00045 static int32_t sen_digital_in_7 = 0;
00046 static int32_t act_analog_out_6 = 0;
00047 static int32_t act_analog_out_4 = 0;
00048 static int32_t act_analog_out_7 = 0;
00049 
00050 // Variables semaforo que me permiten identificar si se debe enviar la respuesta de confirmacion
00051 static int32_t resp_analog_out_6 = 0;
00052 static int32_t resp_digital_out_4 = 0;
00053 static int32_t resp_digital_out_7 = 0;
00054 
00055 BLE ble;
00056 
00057 // Digital IN
00058 DigitalIn       BUTTON(DIGITAL_IN_PIN);
00059 
00060 // Digital OUT
00061 DigitalOut      LED_SET_D7(DIGITAL_OUT_7);
00062 DigitalOut      LED_SET_D8(DIGITAL_OUT_8);
00063 DigitalOut      LED_SET_D11(DIGITAL_OUT_11);
00064 DigitalOut      LED_SET_D4(DIGITAL_OUT_4);
00065 
00066 // Analog IN
00067 AnalogIn        ANALOG(ANALOG_IN_PIN);
00068 
00069 // Analog OUT
00070 PwmOut          PWM(PWM_PIN);
00071 
00072 // Permite imprimir mensajes en la consola
00073 Serial pc(USBTX, USBRX);
00074 
00075 static uint8_t analog_enabled = 0;
00076 static uint8_t old_state = 0;
00077 
00078 // The Nordic UART Service
00079 static const uint8_t uart_base_uuid[] = {0x71, 0x3D, 0, 0, 0x50, 0x3E, 0x4C, 0x75, 0xBA, 0x94, 0x31, 0x48, 0xF1, 0x8D, 0x94, 0x1E};
00080 static const uint8_t uart_tx_uuid[]   = {0x71, 0x3D, 0, 3, 0x50, 0x3E, 0x4C, 0x75, 0xBA, 0x94, 0x31, 0x48, 0xF1, 0x8D, 0x94, 0x1E};
00081 static const uint8_t uart_rx_uuid[]   = {0x71, 0x3D, 0, 2, 0x50, 0x3E, 0x4C, 0x75, 0xBA, 0x94, 0x31, 0x48, 0xF1, 0x8D, 0x94, 0x1E};
00082 static const uint8_t uart_base_uuid_rev[] = {0x1E, 0x94, 0x8D, 0xF1, 0x48, 0x31, 0x94, 0xBA, 0x75, 0x4C, 0x3E, 0x50, 0, 0, 0x3D, 0x71};
00083 
00084 // Trama de Configuracion de los Pines (a).
00085 static const uint8_t di_conf  [] = {0xC01,0xA1, 20, 0xA0, 40, 0xD1, 10, 0xD0, 90};        // length: 9
00086 
00087 uint8_t txPayload[TXRX_BUF_LEN] = {0,};
00088 uint8_t rxPayload[TXRX_BUF_LEN] = {0,};
00089 
00090 GattCharacteristic  txCharacteristic (uart_tx_uuid, txPayload, 1, TXRX_BUF_LEN, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE);
00091 GattCharacteristic  rxCharacteristic (uart_rx_uuid, rxPayload, 1, TXRX_BUF_LEN, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY);
00092 GattCharacteristic *uartChars[] = {&txCharacteristic, &rxCharacteristic};
00093 GattService         uartService(uart_base_uuid, uartChars, sizeof(uartChars) / sizeof(GattCharacteristic *));
00094 
00095 // https://developer.mbed.org/forum/repo-61676-BLE_GAP_Example-community/topic/17193/
00096 void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *)
00097 {
00098     BLE& ble = BLE::Instance(BLE::DEFAULT_INSTANCE);
00099     pc.printf("Disconnected \r\n");
00100     pc.printf("Restart advertising \r\n");
00101     ble.startAdvertising();
00102     LED_SET_D11 = 0;
00103     analog_enabled = 0;         //  Deja que envie lecturas el PT 1000
00104 
00105     sen_analog_in_5 = 0;
00106     sen_digital_in_7 = 0;
00107     act_analog_out_6 = 0;
00108     act_analog_out_4 = 0;
00109     act_analog_out_7 = 0;
00110 
00111     enviar_config_01 = 0;
00112 }
00113 // Ingresa por este metdo unicamente la primera vez que se conecta al mote.
00114 // Tomado desde: https://developer.mbed.org/teams/Bluetooth-Low-Energy/code/BLE_LEDBlinker/file/dc392bde2b3c/main.cpp
00115 void connectionCallback(const Gap::ConnectionCallbackParams_t *)
00116 {
00117     pc.printf("connectionCallback \r\n");
00118     LED_SET_D11 = 1;                //  Enciendo led que indica que alguien se conecto
00119     enviar_config_01 = 1;
00120     //send_config = 1;
00121 }
00122 
00123 // Recepta las caracteristicas que se desea escribir en el mote.
00124 void WrittenHandler(const GattWriteCallbackParams *Handler)
00125 {
00126     pc.printf("WrittenHandler(const GattWriteCallbackParams *Handler) \r\n");
00127     uint8_t buf[TXRX_BUF_LEN];
00128     uint16_t bytesRead, index;
00129 
00130     if (Handler->handle == txCharacteristic.getValueAttribute().getHandle()) {
00131         ble.readCharacteristicValue(txCharacteristic.getValueAttribute().getHandle(), buf, &bytesRead);
00132         memset(txPayload, 0, TXRX_BUF_LEN);
00133         memcpy(txPayload, buf, TXRX_BUF_LEN);
00134 
00135         //por dixys
00136         //pc.printf("Buffer recibido desde Android: \r\n");
00137 
00138         for(index=0; index<bytesRead; index++)
00139             pc.putc(buf[index]);
00140 
00141         //pc.printf("Leemos la trama: \r\n");
00142         //for(index=0; index<bytesRead; index++) {
00143         //    pc.printf("buf[%02x]: %02x\r\n", index, buf[index]);
00144 
00145         //}
00146         //pc.printf("Fin de la Lectura: \r\n");
00147 
00148         // Desde el telefono desactiva el envio de tramas de las siguientes tramas.
00149         if (buf[0] == 0xDC && buf[1] == 0xC1) {              //  Dato Configuracion
00150             enviar_config_01 = buf[2];      // Debe ser cero, hace que ya no se vuelva a enviar la conf general del mote
00151             sen_analog_in_5 = 1;            // habilita al Sensor PT1000, para que envie su configuracion
00152         }
00153         //  PT 1000
00154         if (buf[0] == 0xDC && buf[1] == 0x05 && buf[2] == 0xAA && buf[3] == 20) {
00155             sen_analog_in_5 = buf[4];       // Hace que ya no se vuelva a enviar este tipo de configuracion
00156             sen_digital_in_7 = 1;           //  habilita al Sensor de Luz, para que envie su configuracion
00157         }
00158         //  sensor de luz
00159         if (buf[0] == 0xDC && buf[1] == 0x05 && buf[2] == 0xDD && buf[3] == 10) {
00160             sen_digital_in_7 = buf[4];      // Hace que ya no se vuelva a enviar este tipo de configuracion
00161             act_analog_out_6 = 1;           //  habilita al atuador PWD, para que envie su configuracion
00162         }
00163 
00164         //  PWD
00165         if (buf[0] == 0xDC && buf[1] == 0xA && buf[2] == 0xAA && buf[3] == 40) {
00166             act_analog_out_6 = buf[4];      // Hace que ya no se vuelva a enviar este tipo de configuracion
00167             act_analog_out_4 = 1;           //  habilita al atuador Bomba, para que envie su configuracion
00168         }
00169         //  Actuador la Bomba
00170         if (buf[0] == 0xDC && buf[1] == 0xA && buf[2] == 0x0A && buf[3] == 80) {
00171             act_analog_out_4 = buf[4];      // Hace que ya no se vuelva a enviar este tipo de configuracion
00172             act_analog_out_7 = 1;           //  habilita al atuador Foco, para que envie su configuracion
00173 
00174         }
00175         //  Actuador Foco
00176         if (buf[0] == 0xDC && buf[1] == 0xA && buf[2] == 0x0A && buf[3] == 10) {
00177             act_analog_out_7 = buf[4];       // Hace que ya no se vuelva a enviar este tipo de configuracion
00178         }
00179 
00180         //  Maneja las Tramas de confirmacion
00181         //  PWD
00182         if (buf[0] == 0xBB && buf[1] == 0xA0 && buf[2] == 40) {
00183             resp_analog_out_6 = buf[3];      // Hace que ya no se vuelva a enviar este tipo de configuracion
00184         }
00185         //  Actuador la Bomba
00186         if (buf[0] == 0xBB && buf[1] == 0xD0 && buf[2] == 80) {
00187             resp_digital_out_4 = buf[3];      // Hace que ya no se vuelva a enviar este tipo de configuracion
00188 
00189         }
00190         //  Actuador Foco
00191         if (buf[0] == 0xBB && buf[1] == 0xD0 && buf[2] == 10) {
00192             resp_digital_out_7 = buf[3];
00193         }
00194 
00195         // Verifico si es una trama de Escitura.
00196         if(buf[0] == 0xEE) {
00197             // Verifico si es un signal Digital Out
00198             if(buf[2] == 0xD0) {
00199                 if(buf[3] == 0x07) {
00200                     if (buf[4] == 0x01) {
00201                         LED_SET_D7 = 1;
00202                     } else {
00203                         LED_SET_D7 = 0;
00204                     }
00205                     resp_digital_out_7 = buf[1];        //  Paquete id
00206                 }
00207 
00208                 if(buf[3] == 0x04 ) {
00209                     if (buf[4] == 0x01) {
00210                         LED_SET_D4 = 1;
00211                         analog_enabled = 1;
00212                     } else {
00213                         LED_SET_D4 = 0;
00214                         analog_enabled = 0;
00215                     }
00216                     resp_digital_out_4 = buf[1];        //  Paquete id
00217                 }
00218                 // Verifico si es un signal Analog out
00219             } else if(buf[2] == 0xA0) {
00220                 if(buf[3] == 0x06) {
00221                     float value = (float)buf[4]/255;
00222                     PWM = value;
00223                     pc.printf("PWM = %f  \r\n", value);
00224                     resp_analog_out_6 = buf[1];        //  Paquete id
00225                 }
00226             }
00227 
00228         } else if(buf[0] == 0xA0) {
00229             if(buf[1] == 0x01) {
00230                 analog_enabled = 1;
00231                 //por dixys
00232                 pc.printf("ANALOG ENABLE \r\n");
00233             } else {
00234                 analog_enabled = 0;
00235                 // lo vamos a poner fio enable para hacer pruebas luego lo quitamos
00236                 //por dixys
00237                 pc.printf("ANALOG DISAABLE \r\n");
00238                 pc.printf("valor : %d", analog_enabled);
00239             } 
00240         } else if(buf[0] == 0x02) {
00241             float value = (float)buf[1]/255;
00242             PWM = value;
00243             //por dixys
00244             pc.printf("PWM = %f  \r\n", value);
00245         } else if(buf[0] == 0x03) {
00246             //MYSERVO.write(buf[1]);
00247             //por dixys
00248             pc.printf("SERVO buffer  \r\n");
00249         } else if(buf[0] == 0x04) {
00250             analog_enabled = 0;
00251             PWM = 0;
00252             //MYSERVO.write(0);
00253             LED_SET_D7 = 0;
00254             old_state = 0;
00255             //por dixys
00256             pc.printf("opcion 4 \r\n");
00257         }
00258     }
00259 }
00260 
00261 /*
00262 * Desde este metodo envia las tramas al Gateway.
00263 */
00264 void m_status_check_handle(void)
00265 {
00266     uint8_t tiempo_entre_envio_conf = 200;
00267     uint8_t buf[6], conf_02[5];
00268     conf_02[0] = (0xC02);               //  Codigo que indica que la configuracion sera por cada Pin.
00269 
00270     if (analog_enabled) { // if analog reading enabled
00271         // Read and send out
00272         float s = ANALOG;
00273         uint16_t value = s*1024;
00274         buf[0] = (0xDD);                    //  Codigo
00275         buf[1] = (0x00);                    //  paquete id
00276         buf[2] = (0xA1);                    //  A1| A0| D1| D0
00277         buf[3] = (20);                      //  Posicion
00278         buf[4] = (value >> 8);                   //  Valor
00279         buf[5] = (value);                   //  Valor
00280         
00281         //pc.printf("buf[4]: %d\r\n", buf[4]);
00282         //pc.printf("buf[5]: %d\r\n", buf[5]);
00283         
00284         //pc.printf("value pt 1000: %d\r\n", value);  // Imprimo en terminal lo que esta enviando desde el mote.
00285 
00286         ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), buf, 6);    // Para el RTD
00287     }
00288 
00289     // If digital in changes, report the state
00290     if (BUTTON != old_state) {
00291         old_state = BUTTON;
00292         buf[0] = (0xDD);                    //  Codigo de Lecturas de Datos.
00293         buf[1] = (0x00);                    //  Paquete
00294         buf[2] = (0xD1);                    //  A1| A0| D1| D0
00295         buf[3] = (10);                      //  Posicion
00296         
00297         if (BUTTON == 1) {                  //  Estado natural (no pulsado)
00298             pc.printf("BUTTON == 0\r\n");
00299             LED_SET_D7 = 0;
00300             buf[4] = 0;                     //  Apagado
00301         } else {                            //  Pulsado
00302             pc.printf("BUTTON == 1 \r\n");
00303             LED_SET_D7 = 1;
00304             buf[4] = 1;                     //  Encendido
00305         }
00306         ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), buf, 5);
00307     }
00308 
00309     //pc.printf("enviar_config %d \r\n", enviar_config_01);
00310     if (enviar_config_01 == 1) {
00311         //  Envia la configuracion Genaral del Mote.
00312         pc.printf("enviar_config_01 %d \r\n", enviar_config_01);
00313         ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), di_conf, 9);
00314     }
00315 
00316     //  Envia la configuracion del PT 1000.
00317     if (sen_analog_in_5 == 1) {
00318         conf_02[1] = (0x05);                 //  Categoria puede ser: A (Actuador) | 5 (Sensor)
00319         conf_02[2] = (0xAA);                 //  Tipo de Signal AA | DD
00320         conf_02[3] = (37);                   //  Codigo del Ted
00321         conf_02[4] = (20);                   //  Posicion que ocupa en el mote
00322 
00323         pc.printf("Configuracion Detallada por Pin PT1000\r\n");
00324         ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), conf_02, 5);
00325     }
00326 
00327     //  Envia la configuracion del sensor de luz.
00328     if (sen_digital_in_7 == 1) {
00329         conf_02[1] = (0x05);                 //  Categoria puede ser: A (Actuador) | 5 (Sensor)
00330         conf_02[2] = (0xDD);                 //  Tipo de Signal AA | DD
00331         conf_02[3] = (30);                    //  Codigo del Ted
00332         conf_02[4] = (10);                   //  Posicion que ocupa en el mote
00333 
00334         pc.printf("Configuracion Detallada por sensor de luz\r\n");
00335         ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), conf_02, 5);
00336     }
00337 
00338     //  Envia la configuracion del PWD.
00339     if (act_analog_out_6 == 1) {
00340         conf_02[1] = (0xA);                 //  Categoria puede ser: A (Actuador) | 5 (Sensor)
00341         conf_02[2] = (0xAA);                 //  Tipo de Signal AA | DD
00342         conf_02[3] = (0);                    //  Codigo del Ted
00343         conf_02[4] = (40);                   //  Posicion que ocupa en el mote
00344 
00345         pc.printf("Configuracion Detallada por PWD\r\n");
00346         ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), conf_02, 5);
00347     }
00348 
00349     //  Envia la configuracion del Actuador la Bomba.
00350     if (act_analog_out_4 == 1) {
00351         conf_02[1] = (0xA);                 //  Categoria puede ser: A (Actuador) | 5 (Sensor)
00352         conf_02[2] = (0x0A);                //  Tipo de Signal AA | DD
00353         conf_02[3] = (0);                   //  Codigo del Ted
00354         conf_02[4] = (80);                  //  Posicion que ocupa en el mote
00355 
00356         pc.printf("Configuracion Detallada por Actuador la Bomba \r\n");
00357         ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), conf_02, 5);
00358     }
00359 
00360     //  Envia la configuracion del Actuador Foco.
00361     if (act_analog_out_7 == 1) {
00362         conf_02[1] = (0xA);                 //  Categoria puede ser: A (Actuador) | 5 (Sensor)
00363         conf_02[2] = (0x0A);                 //  Tipo de Signal AA | DD
00364         conf_02[3] = (0);                    //  Codigo del Ted
00365         conf_02[4] = (10);                   //  Posicion que ocupa en el mote
00366 
00367         pc.printf("Configuracion Detallada por Actuador Foco \r\n");
00368         ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), conf_02, 5);
00369     }
00370 
00371     // Envia las tramas de confirmacion hacia el gateway.
00372     if (resp_analog_out_6 != 0) {
00373         // Envia trama de lectura
00374         buf[0] = (0xDD);                    //  Codigo
00375         buf[1] = resp_analog_out_6;         //  paquete id
00376         buf[2] = (0xA0);                    //  A1| A0| D1| D0
00377         buf[3] = (40);                      //  Posicion
00378         buf[4] = PWM;                       //  Valor
00379         pc.printf("resp_analog_out_6 %d\r\n", resp_analog_out_6);  // Imprimo en terminal lo que esta enviando desde el mote.
00380 
00381         ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), buf, 5);    // Para el RTD
00382     }
00383 
00384     if (resp_digital_out_4 != 0) {
00385         // Envia trama de lectura
00386         buf[0] = (0xDD);                    //  Codigo
00387         buf[1] = resp_digital_out_4;         //  paquete id
00388         buf[2] = (0xD0);                    //  A1| A0| D1| D0
00389         buf[3] = (80);                      //  Posicion
00390         buf[4] = LED_SET_D4;                       //  Valor
00391         pc.printf("resp_digital_out_4 %d\r\n", resp_digital_out_4);  // Imprimo en terminal lo que esta enviando desde el mote.
00392 
00393         ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), buf, 5);    // Para el RTD
00394     }
00395 
00396     if (resp_digital_out_7 != 0) {
00397         // Envia trama de lectura
00398         buf[0] = (0xDD);                    //  Codigo
00399         buf[1] = resp_digital_out_7;         //  paquete id
00400         buf[2] = (0xD0);                    //  A1| A0| D1| D0
00401         buf[3] = (10);                      //  Posicion
00402         buf[4] = LED_SET_D7;                       //  Valor
00403         pc.printf("resp_digital_out_7 %d\r\n", resp_digital_out_7);  // Imprimo en terminal lo que esta enviando desde el mote.
00404 
00405         ble.updateCharacteristicValue(rxCharacteristic.getValueAttribute().getHandle(), buf, 5);    // Para el RTD
00406     }
00407 
00408     wait_ms(100);
00409 }
00410 
00411 int main(void)
00412 {
00413     Ticker ticker;
00414     ticker.attach_us(m_status_check_handle, 200000);
00415 
00416     ble.init();
00417     ble.onDisconnection(disconnectionCallback);
00418     ble.onConnection(connectionCallback);
00419     ble.onDataWritten(WrittenHandler);
00420 
00421     pc.baud(9600);
00422     pc.printf("SimpleChat Init \r\n");
00423     //pc.attach( uartCB , pc.RxIrq);
00424 
00425     // setup advertising
00426     ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED);
00427     ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
00428     ble.accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME,
00429                                      (const uint8_t *)"Biscuit", sizeof("Biscuit") - 1);   // Original:  Biscuit
00430     ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS,
00431                                      (const uint8_t *)uart_base_uuid_rev, sizeof(uart_base_uuid));
00432     // 100ms; in multiples of 0.625ms.
00433     ble.setAdvertisingInterval(160);
00434 
00435     ble.addService(uartService);
00436 
00437     ble.startAdvertising();
00438 
00439     pc.printf("Advertising Start \r\n");
00440 
00441     //por dixys
00442     // para probar, luego quitar. Esto hace que cada ticker se envie un dato analogico via BLE
00443     analog_enabled = 0;
00444 
00445     while(1) {
00446         ble.waitForEvent();
00447     }
00448 }