Gateway con agregar controles mediante firebase

Dependencies:   mbed mbed-http ESP01 Pulse RFDecoder

Files at this revision

API Documentation at this revision

Comitter:
Thrillex13
Date:
Sun Sep 15 20:56:21 2019 +0000
Parent:
3:5dceee1c49fc
Child:
5:190b19129c4d
Commit message:
- Se cambio la implementacion de registro de controles para hacerlo mediante Firebase y peticiones HTTPS GET y PATCH; - Se optimizo la conexion de la funcion wificonnect

Changed in this revision

ESP01.lib Show annotated file Show diff for this revision Revisions of this file
main.cpp Show annotated file Show diff for this revision Revisions of this file
main.h Show annotated file Show diff for this revision Revisions of this file
mbed-memory-status.lib Show annotated file Show diff for this revision Revisions of this file
mbed_app.json Show annotated file Show diff for this revision Revisions of this file
--- a/ESP01.lib	Tue Jun 11 00:24:59 2019 +0000
+++ b/ESP01.lib	Sun Sep 15 20:56:21 2019 +0000
@@ -1,1 +1,1 @@
-https://os.mbed.com/users/Wosser1sProductions/code/ESP8266/#8c6f56470ba7
+https://os.mbed.com/users/Wosser1sProductions/code/ESP8266/#ef9014a530cf
--- a/main.cpp	Tue Jun 11 00:24:59 2019 +0000
+++ b/main.cpp	Sun Sep 15 20:56:21 2019 +0000
@@ -1,84 +1,93 @@
 #include "main.h"
+#include <string>
 
 // Objects
 Serial pc(USBTX, USBRX);
 ESP01 wifi(PTC17, PTC16, 115200);       //Con este objeto implementamos los metodos que requieren comandos AT del modulo de WIFI
-//ESP8266Interface net(PTC17, PTC16);   //Con este objeto implementamos todas las funciones de red para la creacion de Sockets
+//ESP8266Interface net(PTC17, PTC16);     //Con este objeto implementamos todas las funciones de red para la creacion de Sockets
 RFDecoder decoder = RFDecoder(D2,D3);   //tx rx
+Ticker firebasecheck;
+
 
 // Global variables
-char send[250]; // Strings for sending and receiving commands / data send / data receive / command received / status received
-char recv[250];
+char send[128]; // Strings for sending and receiving commands / data send / data receive / command received / status received
+char recv[128];
 char command[TCPCOMMSBYTESMAX];
 char status[TCPSTATSBYTESMAX];
 char controlcode[8];
 
+string comandofirebase;
+bool firebaseTimeoutExpired = false;
+
+
+
 int main()
 {
+
     //Inicializacion de los Perifericos
     led_azul = OFF;
     led_rojo = OFF;
     led_verde = OFF;
     pc.baud(115200);
 
+    esp01_en.mode(PullUp);
+    esp01_rst.mode(PullUp);
+
 
     //Inicializacion y Conexion al WiFi
+    //wifiInit();
+    //wifi.Quit();
     wifiInit();
-    //wifi.Quit();
     wifiConnect();
 
     //ESP8266Interface *net = new ESP8266Interface(); //Con este objeto implementamos todas las funciones de red para la creacion de Sockets para HTTPS
     //http_demo(net);
     //delete net;   //Necesario destruir el objeto cuando ya no se use para desocupar la interface de wifi.
 
+    ESP8266Interface *net = new ESP8266Interface(); //Con este objeto implementamos todas las funciones de red para la creacion de Sockets para HTTPS
+    //delete net;   //Necesario destruir el objeto cuando ya no se use para desocupar la interface de wifi.
 
-    //Iniciamos el servidor
-    startServer(SERVER_PORT);
-
-
+    //Tarea para revisar si hay algun comando en firebase, esta tarea se ejecuta cada x segundos.
+    firebasecheck.attach(&firebaseCheckTimeout, INTERVALFIREBASECHECK);
 
     while(1) {
-        //Revisamos si hay un dato por TCP disponible
-        if(wifi.TCPDataAvailable(recv)) {
-            pc.printf("%s", recv);
-            int socket = getTCPContent(recv,command,status);
+        if(firebaseTimeoutExpired) {
+            //Leemos la bsae de datos de firebase para revisar si hay algun comando disponible.
+            comandofirebase = getFirebaseCommand(net);
+
+            //Habilitamos el debugeo de la memoria
+            //print_all_thread_info();
+            //print_heap_and_isr_stack_info();
 
-            //Comando para registrar control
-            if(command[0] == NEW_CONTROL_REGISTER) {
+            if(comandofirebase.compare(AGREGARCONTROL) == 0) {
                 Timer t;
+                int tini;
                 t.start();
+                tini = t.read_ms();
+
+                pc.printf("Comando Agregar Control Recibido\r\n");
+                putFirebaseCommand(net, WAITING_RF_CODE, 0);
+                
                 LEDAMARILLO_ON;
-                while(t.read_ms() < 30000) {
+                while((t.read_ms()- tini) < MAXTIMERXCONTROL) {
                     if(decoder.available()) {
                         unsigned long numcode = decoder.getCode();
                         pc.printf("Codigo Recibido %x \n\r", numcode);
-
-                        convertToCharArray(&controlcode[0],numcode);
-
-                        send[0] = CONTROL_REGISTER_INFO;
-                        send[1] = controlcode[4];
-                        send[2] = controlcode[5];
-                        send[3] = controlcode[6];
-                        wifi.SendTCPData(socket,TCPCOMMSBYTESMAX,send);
-                        wifi.SendTCPData(socket,TCPCOMMSBYTESMAX,send);
+                        putFirebaseCommand(net, NEW_CONTROL_RESPONSE, numcode);
                         break;
                     }
                 }
-
                 LEDVERDE_ON;
-                command[0] = 0x00;
-            }
-
-            //Evaluar otros comandos
-            if(command[0] == HEARBEAT_REQUEST) {
-                send[0] = HEARBEAT_RESPONSE;
-                wifi.SendTCPData(socket,TCPCOMMSBYTESMAX,send);
-                wifi.SendTCPData(socket,TCPCOMMSBYTESMAX,send);
-                command[0] = 0x00;
+                firebaseTimeoutExpired = false;
+                comandofirebase = NINGUNCOMANDO;
+            } else {
+                pc.printf("Ningun comando recibido\r\n");
+                firebaseTimeoutExpired = false;
             }
 
         }
 
+
     }
 }
 
@@ -91,59 +100,57 @@
     wifi.DisableEcho();
     pc.printf("Set mode to Station\r\n");
     wifi.SetMode(STATION);
-    wifi.RcvReply(recv, 1000);
+    wifi.RcvReply(recv, 3000);
     pc.printf("%s", recv);
     wait(2);
     pc.printf("Configure for multiple sockets\r\n");
     wifi.SetMultiple();
-    wifi.RcvReply(recv, 1000);
+    wifi.RcvReply(recv, 3000);
     pc.printf("%s", recv);
     wait(2);
+    /*
     pc.printf("Enable DHCP\r\n");
     wifi.EnableDHCP();
-    wifi.RcvReply(recv, 1000);
+    wifi.RcvReply(recv, 1500);
     pc.printf("%s", recv);
     wait(2);
+    */
 }
 
 void wifiConnect(void)
 {
-    Timer t;
-    if(isConnectedToWifi()) {
-        pc.printf("Gateway is already connected to wifi with the following IP address\r\n");
-        wifi.GetIP(recv);
-        pc.printf("%s", recv);
-        led_azul = OFF;
-        led_verde = ON;
-        wait(2);
-    } else {
-        pc.printf("Starting Smart Config\r\n");
-        led_azul = ON;
-        wifi.StartSmartConfig();
-        wifi.RcvReply(recv, 15000);
-        pc.printf("%s", recv);
-        wait(5);
-        t.start();
-        while(!isConnectedToWifi()) {
-            //Timeout para hacer la conexion
-            /*
-            if(t.read_ms() > 30000) {
-                led_azul = OFF;
-                led_rojo = ON;
-                pc.printf("No se pudo conectar al Wifi\r\n");
-                while(1);
-                break;
-            }
-            */
+    char connCheckCounter = 0;
+
+    while(!isConnectedToWifi()) {
+        if(connCheckCounter > MAXWIFICONNCHECKS) {
+            //pc.printf("Starting Smart Config\r\n");
+            led_azul = ON;
+            wifi.StartSmartConfig();
+            wifi.RcvReply(recv, 15000);
+            //pc.printf("%s", recv);
+            wait(5);
+            connCheckCounter=0;
         }
+        connCheckCounter++;
+        pc.printf("Gateway no conectado, intento de reconexion %d\r\n",connCheckCounter);
+        wait(1);
     }
+
+    pc.printf("Gateway is already connected to wifi with the following IP address\r\n");
+    wifi.GetIP(recv);
+    pc.printf("%s", recv);
+    led_azul = OFF;
+    led_verde = ON;
+    wait(2);
+
 }
 
+
 bool isConnectedToWifi(void)
 {
     bool status;
     wifi.GetConnStatusCode(recv);
-    //pc.printf("%s", recv);
+    //pc.printf("El estado de la conexion es %s", recv);
     if(strcmp(recv,"STATUS:2\r")==0) {
         led_azul = OFF;
         led_rojo = OFF;
@@ -158,10 +165,10 @@
 
 void startServer(int port)
 {
-    pc.printf("Iniciando servidor en el puerto %d\r\n",port);
+    //pc.printf("Iniciando servidor en el puerto %d\r\n",port);
     wifi.StartServerMode(port);
     wifi.RcvReply(recv, 1000);
-    pc.printf("%s", recv);
+    //pc.printf("%s", recv);
     //wait(2);
 }
 
@@ -204,6 +211,80 @@
 }
 
 
+string getFirebaseCommand(NetworkInterface *network)
+{
+    TLSSocket* socket = new TLSSocket();
+    string comando = NINGUNCOMANDO;
+
+    nsapi_error_t r;
+    // make sure to check the return values for the calls below (should return NSAPI_ERROR_OK)
+    r = socket->open(network);
+    r = socket->set_root_ca_cert(SSL_CA_PEM);
+    r = socket->connect("https://cotoceiba.firebaseio.com", 443);
+
+
+    //printf("\n----- Conectando con la base de datos de Firebase -----\n");
+    //HttpsRequest* get_req = new HttpsRequest(socket, HTTP_GET, "https://cotoceiba.firebaseio.com/Comandos/AppToGateway/Request/Comando.json?auth=ZpXLLURU9KWmW5t1kzBYD2IuBE0V7wdv5vXwDgsH");
+    HttpsRequest* get_req = new HttpsRequest(socket, HTTP_GET, "https://cotoceiba.firebaseio.com/Comandos/AppToGateway/Request/Comando.json?");
+
+    HttpResponse* get_res = get_req->send();
+    if (!get_res) {
+        printf("HttpGetRequest failed (error code %d)\n", get_req->get_error());
+        comando = NINGUNCOMANDO;
+        //return 1;
+    } else {
+        //printf("\n----- Respuesta de Firebase -----\n");
+        //printf("Status: %d - %s\n", get_res->get_status_code(), get_res->get_status_message().c_str());
+
+        comando = get_res->get_body_as_string();
+        //pc.printf("%s\r\n",comando.c_str());
+        //printf("\nBody (%lu bytes):\n\n%s\n", get_res->get_body_length(), get_res->get_body_as_string().c_str());
+    }
+
+
+    delete get_req;
+    socket->close();
+    delete socket;
+
+    return comando;
+}
+
+void putFirebaseCommand(NetworkInterface *network, char comando, unsigned long numcode)
+{
+    TLSSocket* socket = new TLSSocket();
+    char body[100];
+
+    nsapi_error_t r;
+    // make sure to check the return values for the calls below (should return NSAPI_ERROR_OK)
+    r = socket->open(network);
+    r = socket->set_root_ca_cert(SSL_CA_PEM);
+    r = socket->connect("https://cotoceiba.firebaseio.com", 443);
+
+    //printf("\n----- Enviando datos a la base de datos de Firebase -----\n");
+    HttpsRequest* post_req = new HttpsRequest(socket, HTTP_PATCH, "https://cotoceiba.firebaseio.com/Comandos/GatewayToApp/Response.json?auth=ZpXLLURU9KWmW5t1kzBYD2IuBE0V7wdv5vXwDgsH");
+    post_req->set_header("Content-Type", "application/json");
+
+    sprintf(body, "{\"Comando\":\"%d\",\"Valor1\":\"%X\"}",comando,numcode);
+    HttpResponse* post_res = post_req->send(body, strlen(body));
+
+    if (!post_res) {
+        printf("HttpPatchRequest failed (error code %d)\n", post_req->get_error());
+    }
+
+//    printf("\n----- HTTPS PATCH response -----\n");
+//    dump_response(post_res);
+    socket->close();
+    delete socket;
+    delete post_req;
+}
+
+void firebaseCheckTimeout()
+{
+    firebaseTimeoutExpired = true;
+
+}
+
+
 void http_demo(NetworkInterface *network)
 {
     TLSSocket* socket = new TLSSocket();
@@ -254,4 +335,4 @@
         printf("\t%s: %s\n", res->get_headers_fields()[ix]->c_str(), res->get_headers_values()[ix]->c_str());
     }
     printf("\nBody (%lu bytes):\n\n%s\n", res->get_body_length(), res->get_body_as_string().c_str());
-}
\ No newline at end of file
+}
--- a/main.h	Tue Jun 11 00:24:59 2019 +0000
+++ b/main.h	Sun Sep 15 20:56:21 2019 +0000
@@ -7,6 +7,7 @@
 #include "https_request.h"
 #include "ESP8266Interface.h"
 #include "RFDecoder.h"
+#include "mbed_memory_status.h"
 
 #define ON  0
 #define OFF  1
@@ -16,11 +17,24 @@
 
 #define LEDS_OFF                led_azul = OFF; led_verde = OFF; led_rojo = OFF;
 
+//Configuraciones del Sistema
 #define SERVER_PORT             5558
-#define MAX_NUM_OF_CONNECTIONS  2
 #define TCPCOMMSBYTESMAX        10
 #define TCPSTATSBYTESMAX        5
-#define MAXTIMERXCONTROL        30000       //Tiempo maximo para recibir el codigo del control de 433MHz en milisegundos
+#define MAXTIMERXCONTROL        40000       //Tiempo maximo para recibir el codigo del control de 433MHz en milisegundos
+#define INTERVALFIREBASECHECK   15.0
+#define MAXWIFICONNCHECKS       3
+
+//Comandos de Firebase
+//Los comandos provenientes de la app al Gateway son de tipo String.
+#define NINGUNCOMANDO           "02"
+#define AGREGARCONTROL          "10"    //La funcion .compare solo acepta String
+
+// Las respuestas del Gateway a la App debe ser tipo CHAR
+#define WAITING_RF_CODE         10
+#define NEW_CONTROL_RESPONSE    11
+
+
 
 //Codigos de Status de TCP
 #define COMMANDREC              0x01        //Se recibio un comando valido por TCP
@@ -102,7 +116,10 @@
 //Port Definition
 DigitalOut led_rojo(LED_RED);
 DigitalOut led_verde(LED_GREEN);
-DigitalOut led_azul(LED_BLUE);    
+DigitalOut led_azul(LED_BLUE);
+
+DigitalIn esp01_en(D4);
+DigitalIn esp01_rst(D5);
 
 //Function Prototypes
 void wifiInit(void);
@@ -114,6 +131,9 @@
 
 void dump_response(HttpResponse* res);
 void http_demo(NetworkInterface *net);
+string getFirebaseCommand(NetworkInterface *network);
+void putFirebaseCommand(NetworkInterface *network, char comando, unsigned long numcode);
+void firebaseCheckTimeout(void);
 
 
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed-memory-status.lib	Sun Sep 15 20:56:21 2019 +0000
@@ -0,0 +1,1 @@
+https://github.com/nuket/mbed-memory-status/#57ed299aa9b3f1c2dcd46777f874e95e38e98df4
--- a/mbed_app.json	Tue Jun 11 00:24:59 2019 +0000
+++ b/mbed_app.json	Sun Sep 15 20:56:21 2019 +0000
@@ -10,7 +10,9 @@
         "MBEDTLS_USER_CONFIG_FILE=\"mbedtls_entropy_config.h\"",
         "MBEDTLS_TEST_NULL_ENTROPY",
         "MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES",
-        "MBED_HEAP_STATS_ENABLED=1"
+        "MBED_STACK_STATS_ENABLED=1",
+        "MBED_HEAP_STATS_ENABLED=1",
+        "MBED_CONF_PLATFORM_ERROR_FILENAME_CAPTURE_ENABLED=1"
     ],
     "target_overrides": {
         "*": {