Gateway con agregar controles mediante firebase
Dependencies: mbed mbed-http ESP01 Pulse RFDecoder
Diff: main.cpp
- Revision:
- 4:8fed3705384e
- Parent:
- 3:5dceee1c49fc
--- 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
+}