Gateway con agregar controles mediante firebase

Dependencies:   mbed mbed-http ESP01 Pulse RFDecoder

Revision:
3:5dceee1c49fc
Parent:
2:bc3973471585
Child:
4:8fed3705384e
--- a/main.cpp	Sat May 25 18:08:19 2019 +0000
+++ b/main.cpp	Tue Jun 11 00:24:59 2019 +0000
@@ -1,99 +1,252 @@
-#include "mbed.h"
-#include <string>
-#include "ESP01.h"
-#include "https_request.h"
-#include "mbed_trace.h"
-#include "TCPSocket.h"
-#include "ESP8266Interface.h"
- 
+#include "main.h"
+
 // 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
-
-DigitalOut led_rojo(LED_RED);
-DigitalOut led_verde(LED_GREEN);
-DigitalOut led_azul(LED_BLUE);
-
-#define ON  0;
-#define OFF  1;
+//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
 
 // Global variables
-char snd[255], rcv[1000]; // Strings for sending and receiving commands / data / replies
+char send[250]; // Strings for sending and receiving commands / data send / data receive / command received / status received
+char recv[250];
+char command[TCPCOMMSBYTESMAX];
+char status[TCPSTATSBYTESMAX];
+char controlcode[8];
+
+int main()
+{
+    //Inicializacion de los Perifericos
+    led_azul = OFF;
+    led_rojo = OFF;
+    led_verde = OFF;
+    pc.baud(115200);
 
-void wifiInit(void);
-bool isConnectedToWifi(void);
-void wifiConnect(void);
+
+    //Inicializacion y Conexion al WiFi
+    wifiInit();
+    //wifi.Quit();
+    wifiConnect();
 
-void http_demo(NetworkInterface *net);
+    //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.
+
+
+    //Iniciamos el servidor
+    startServer(SERVER_PORT);
+
 
 
-/* List of trusted root CA certificates
- * currently two: Amazon, the CA for os.mbed.com and Let's Encrypt, the CA for httpbin.org
- *
- * To add more root certificates, just concatenate them.
- */
-const char SSL_CA_PEM[] =  
-    "-----BEGIN CERTIFICATE-----\n"
-    "MIIFmzCCBIOgAwIBAgIRAJRuZHok8dQjAQAAAAApJGwwDQYJKoZIhvcNAQELBQAw\n"
-    "QjELMAkGA1UEBhMCVVMxHjAcBgNVBAoTFUdvb2dsZSBUcnVzdCBTZXJ2aWNlczET\n"
-    "MBEGA1UEAxMKR1RTIENBIDFPMTAeFw0xOTAzMTMyMTMwNTdaFw0yMDAzMTEyMTMw\n"
-    "NTdaMGgxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQH\n"
-    "Ew1Nb3VudGFpbiBWaWV3MRMwEQYDVQQKEwpHb29nbGUgTExDMRcwFQYDVQQDEw5m\n"
-    "aXJlYmFzZWlvLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALkd\n"
-    "/jeM+PrwIYmM6IE28iN7CjKnBWy+tqNrs5z2AJwM5iLgtgcbc+THuXGElTN7zAWB\n"
-    "SKWv+ezAGe5NiTEEUiWgX1z1VFDj85xpz+Cysn/Oi8MtoN6h8yCmYPtXv8YPInw0\n"
-    "JLkSM5e2uuWVwc/tR1Fh+awpiYQFqGm6DvMq6yAYB/nuL3Gyc4XFgRrxje+VQ+g3\n"
-    "oWE+9NVfqu4smFCutSIGlEdRhGdr/m2u+sc+dnBZNoVOqwSyyFyjpAZvMMvuE5Ip\n"
-    "3ovfA1tq57nl9eQw8fcKsdXOeeXYHc1KBUUC7Xb8F/1+upVML8a5GMULpYkClLXt\n"
-    "OKRRfCJa53YynILJdPkCAwEAAaOCAmQwggJgMA4GA1UdDwEB/wQEAwIFoDATBgNV\n"
-    "HSUEDDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAM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uXSqSFT\n"
-    "EDaRGzdj8AKkoDmRkWLcEg/6a/2dfw8VV7fIAlqVxNQwZWZLtIsBGazxZ5xflrVz\n"
-    "I5AHejNR7guDaWAimhkSOlG11W8BzPtdAo/xJ6JyI4K5kPGIXucniVRmQfmojxc=\n"
-    "-----END CERTIFICATE-----\n"
-    "-----BEGIN CERTIFICATE-----\n"
-    "MIIESjCCAzKgAwIBAgINAeO0mqGNiqmBJWlQuDANBgkqhkiG9w0BAQsFADBMMSAw\n"
-    "HgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMjETMBEGA1UEChMKR2xvYmFs\n"
-    "U2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjAeFw0xNzA2MTUwMDAwNDJaFw0yMTEy\n"
-    "MTUwMDAwNDJaMEIxCzAJBgNVBAYTAlVTMR4wHAYDVQQKExVHb29nbGUgVHJ1c3Qg\n"
-    "U2VydmljZXMxEzARBgNVBAMTCkdUUyBDQSAxTzEwggEiMA0GCSqGSIb3DQEBAQUA\n"
-    "A4IBDwAwggEKAoIBAQDQGM9F1IvN05zkQO9+tN1pIRvJzzyOTHW5DzEZhD2ePCnv\n"
-    "UA0Qk28FgICfKqC9EksC4T2fWBYk/jCfC3R3VZMdS/dN4ZKCEPZRrAzDsiKUDzRr\n"
-    "mBBJ5wudgzndIMYcLe/RGGFl5yODIKgjEv/SJH/UL+dEaltN11BmsK+eQmMF++Ac\n"
-    "xGNhr59qM/9il71I2dN8FGfcddwuaej4bXhp0LcQBbjxMcI7JP0aM3T4I+DsaxmK\n"
-    "FsbjzaTNC9uzpFlgOIg7rR25xoynUxv8vNmkq7zdPGHXkxWY7oG9j+JkRyBABk7X\n"
-    "rJfoucBZEqFJJSPk7XA0LKW0Y3z5oz2D0c1tJKwHAgMBAAGjggEzMIIBLzAOBgNV\n"
-    "HQ8BAf8EBAMCAYYwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMBIGA1Ud\n"
-    "EwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFJjR+G4Q68+b7GCfGJAboOt9Cf0rMB8G\n"
-    "A1UdIwQYMBaAFJviB1dnHB7AagbeWbSaLd/cGYYuMDUGCCsGAQUFBwEBBCkwJzAl\n"
-    "BggrBgEFBQcwAYYZaHR0cDovL29jc3AucGtpLmdvb2cvZ3NyMjAyBgNVHR8EKzAp\n"
-    "MCegJaAjhiFodHRwOi8vY3JsLnBraS5nb29nL2dzcjIvZ3NyMi5jcmwwPwYDVR0g\n"
-    "BDgwNjA0BgZngQwBAgIwKjAoBggrBgEFBQcCARYcaHR0cHM6Ly9wa2kuZ29vZy9y\n"
-    "ZXBvc2l0b3J5LzANBgkqhkiG9w0BAQsFAAOCAQEAGoA+Nnn78y6pRjd9XlQWNa7H\n"
-    "TgiZ/r3RNGkmUmYHPQq6Scti9PEajvwRT2iWTHQr02fesqOqBY2ETUwgZQ+lltoN\n"
-    "FvhsO9tvBCOIazpswWC9aJ9xju4tWDQH8NVU6YZZ/XteDSGU9YzJqPjY8q3MDxrz\n"
-    "mqepBCf5o8mw/wJ4a2G6xzUr6Fb6T8McDO22PLRL6u3M4Tzs3A2M1j6bykJYi8wW\n"
-    "IRdAvKLWZu/axBVbzYmqmwkm5zLSDW5nIAJbELCQCZwMH56t2Dvqofxs6BBcCFIZ\n"
-    "USpxu6x6td0V7SvJCCosirSmIatj/9dSSVDQibet8q/7UK4v4ZUN80atnZz1yg==\n"
-    "-----END CERTIFICATE-----\n";
-    
+    while(1) {
+        //Revisamos si hay un dato por TCP disponible
+        if(wifi.TCPDataAvailable(recv)) {
+            pc.printf("%s", recv);
+            int socket = getTCPContent(recv,command,status);
+
+            //Comando para registrar control
+            if(command[0] == NEW_CONTROL_REGISTER) {
+                Timer t;
+                t.start();
+                LEDAMARILLO_ON;
+                while(t.read_ms() < 30000) {
+                    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);
+                        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;
+            }
+
+        }
+
+    }
+}
+
+void wifiInit(void)
+{
+    pc.printf("Gateway Sistema de Control de Cotos\r\n");
+    pc.printf("Resetting WiFi\r\n");
+    wifi.Reset();
+    wait(2);
+    wifi.DisableEcho();
+    pc.printf("Set mode to Station\r\n");
+    wifi.SetMode(STATION);
+    wifi.RcvReply(recv, 1000);
+    pc.printf("%s", recv);
+    wait(2);
+    pc.printf("Configure for multiple sockets\r\n");
+    wifi.SetMultiple();
+    wifi.RcvReply(recv, 1000);
+    pc.printf("%s", recv);
+    wait(2);
+    pc.printf("Enable DHCP\r\n");
+    wifi.EnableDHCP();
+    wifi.RcvReply(recv, 1000);
+    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;
+            }
+            */
+        }
+    }
+}
 
-void dump_response(HttpResponse* res) {
+bool isConnectedToWifi(void)
+{
+    bool status;
+    wifi.GetConnStatusCode(recv);
+    //pc.printf("%s", recv);
+    if(strcmp(recv,"STATUS:2\r")==0) {
+        led_azul = OFF;
+        led_rojo = OFF;
+        led_verde = ON;
+        status=true;
+    } else {
+        status=false;
+    }
+    return status;
+
+}
+
+void startServer(int port)
+{
+    pc.printf("Iniciando servidor en el puerto %d\r\n",port);
+    wifi.StartServerMode(port);
+    wifi.RcvReply(recv, 1000);
+    pc.printf("%s", recv);
+    //wait(2);
+}
+
+int getTCPContent(char* espdata, char* command, char* status)
+{
+    char i=0;
+    char offset=0;
+    char socket=0;
+
+    if((espdata[2]=='+') && (espdata[3]=='I') && (espdata[4]=='P') && (espdata[5]=='D')) {
+        //Obtenemos en socket de conexion
+        socket = espdata[7]-'0';
+        //Buscamos el caracter : para de ahi iniciar el mensaje
+        for(i=0; i<250; i++) {
+            if(espdata[i]==':') {
+                offset = i+1;
+                break;
+            }
+        }
+
+        for(i=0; (i<TCPCOMMSBYTESMAX); i++) {
+            command[i] = espdata[i+offset];
+        }
+
+        command[TCPCOMMSBYTESMAX] = '\0';
+
+        status[0] = COMMANDREC;
+    }
+
+    return socket;
+}
+
+void convertToCharArray(char *arr, unsigned long number)
+{
+    int i = 0;
+
+    for (i = 0; i < 8; ++i) {
+        arr[i] = (char)((((unsigned long) number) >> (56 - (8*i))) & 0xFFu);
+    }
+}
+
+
+void http_demo(NetworkInterface *network)
+{
+    TLSSocket* socket = new TLSSocket();
+
+    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----- HTTPS GET request -----\n");
+
+    HttpsRequest* get_req = new HttpsRequest(socket, HTTP_GET, "https://cotoceiba.firebaseio.com/Condominos/94.json?auth=ZpXLLURU9KWmW5t1kzBYD2IuBE0V7wdv5vXwDgsH");
+
+    HttpResponse* get_res = get_req->send();
+    if (!get_res) {
+        printf("HttpRequest failed (error code %d)\n", get_req->get_error());
+        //return 1;
+    }
+    printf("\n----- HTTPS GET response -----\n");
+    dump_response(get_res);
+    delete get_req;
+
+    printf("\n----- HTTPS POST request -----\n");
+
+    HttpsRequest* post_req = new HttpsRequest(socket, HTTP_POST, "https://cotoceiba.firebaseio.com/Condominos/52.json?auth=ZpXLLURU9KWmW5t1kzBYD2IuBE0V7wdv5vXwDgsH");
+    post_req->set_header("Content-Type", "application/json");
+
+    const char body[] = "{\"nombre\":\"Posteado por Wifi Perros\",\"numcasa\":\"64\"}";
+
+    HttpResponse* post_res = post_req->send(body, strlen(body));
+    if (!post_res) {
+        printf("HttpRequest failed (error code %d)\n", post_req->get_error());
+        //return 1;
+    }
+
+    printf("\n----- HTTPS POST response -----\n");
+    dump_response(post_res);
+    delete post_req;
+}
+
+void dump_response(HttpResponse* res)
+{
     printf("Status: %d - %s\n", res->get_status_code(), res->get_status_message().c_str());
 
     printf("Headers:\n");
@@ -101,143 +254,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());
-}
- 
-int main() {
-    led_azul = OFF;
-    led_rojo = OFF;
-    led_verde = OFF;
-    
-    pc.baud(115200);
-    wifi.Quit();
-    wifiInit();
-    wifiConnect();
-    
-    
-    
-    //NextToDo: Crear un servidor y a la vez hacer get y post
-    
-    ESP8266Interface net(PTC17, PTC16);     //Con este objeto implementamos todas las funciones de red para la creacion de Sockets
-    
-    http_demo(&net);
-    
-    wifi.StartServerMode(333);
-    wifi.RcvReply(rcv, 1000);
-    pc.printf("%s", rcv);
-    wait(20);
-    
-    http_demo(&net);
-    
-    
-    
-    
-
-    while(1);
-}
-
-void wifiInit(void){
-    pc.printf("Gateway Sistema de Control de Cotos\r\n");
-    pc.printf("Resetting WiFi\r\n");
-    wifi.Reset();
-    wait(2);
-    wifi.DisableEcho();
-    pc.printf("Set mode to Station+AP\r\n");
-    wifi.SetMode(BOTH);
-    wifi.RcvReply(rcv, 1000);
-    pc.printf("%s", rcv);
-    wait(2);
-    pc.printf("Configure for multiple sockets\r\n");
-    wifi.SetMultiple();
-    wifi.RcvReply(rcv, 1000);
-    pc.printf("%s", rcv);
-    wait(2);
-    pc.printf("Enable DHCP\r\n");
-    wifi.EnableDHCP();
-    wifi.RcvReply(rcv, 1000);
-    pc.printf("%s", rcv);
-    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(rcv);
-        pc.printf("%s", rcv);
-        led_azul = OFF;
-        led_verde = ON;
-        wait(2);      
-    }else{
-        t.start();
-        pc.printf("Starting Smart Config\r\n");
-        led_azul = ON;
-        wifi.StartSmartConfig();
-        wifi.RcvReply(rcv, 15000);
-        pc.printf("%s", rcv);
-        wait(5);
-        while(!isConnectedToWifi()){
-            if(t.read_ms() > 30000) {
-                led_azul = OFF;
-                led_rojo = ON;
-                pc.printf("No se pudo conectar al Wifi");
-                break;
-            }          
-        }          
-    }   
-}
-
-bool isConnectedToWifi(void){
-    bool status;
-    wifi.GetConnStatusCode(rcv);
-    //pc.printf("%s", rcv);
-    if(strcmp(rcv,"STATUS:2\r")==0){
-        led_azul = OFF;
-        led_rojo = OFF;
-        led_verde = ON;
-        status=true;
-    }else{
-        status=false;
-    }
-    return status;
-    
-}
-
-void http_demo(NetworkInterface *network){
-    TLSSocket* socket = new TLSSocket();
- 
-    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----- HTTPS GET request -----\n");
-
-        HttpsRequest* get_req = new HttpsRequest(socket, HTTP_GET, "https://cotoceiba.firebaseio.com/Condominos/94.json?auth=ZpXLLURU9KWmW5t1kzBYD2IuBE0V7wdv5vXwDgsH");
-
-        HttpResponse* get_res = get_req->send();
-        if (!get_res) {
-            printf("HttpRequest failed (error code %d)\n", get_req->get_error());
-            //return 1;
-        }
-        printf("\n----- HTTPS GET response -----\n");
-        dump_response(get_res);
-        delete get_req;     
-        
-        printf("\n----- HTTPS POST request -----\n");
-
-        HttpsRequest* post_req = new HttpsRequest(socket, HTTP_POST, "https://cotoceiba.firebaseio.com/Condominos/52.json?auth=ZpXLLURU9KWmW5t1kzBYD2IuBE0V7wdv5vXwDgsH");
-        post_req->set_header("Content-Type", "application/json");
-
-        const char body[] = "{\"nombre\":\"Posteado por Wifi Perros\",\"numcasa\":\"64\"}";
-
-        HttpResponse* post_res = post_req->send(body, strlen(body));
-        if (!post_res) {
-            printf("HttpRequest failed (error code %d)\n", post_req->get_error());
-            //return 1;
-        }
-
-        printf("\n----- HTTPS POST response -----\n");
-        dump_response(post_res);
-        delete post_req;
 }
\ No newline at end of file