Gateway con agregar controles mediante firebase migracion a OS5
Dependencies: mbed-http ESP01 Pulse RFDecoder
main.cpp
00001 #include "main.h" 00002 #include <string> 00003 00004 // Objects 00005 Serial pc(USBTX, USBRX); 00006 ESP01 wifi(PTC17, PTC16, 115200); //Con este objeto implementamos los metodos que requieren comandos AT del modulo de WIFI 00007 //ESP8266Interface net(PTC17, PTC16); //Con este objeto implementamos todas las funciones de red para la creacion de Sockets 00008 RFDecoder decoder = RFDecoder(D2,D3); //tx rx 00009 Ticker firebasecheck; 00010 00011 00012 // Global variables 00013 char send[128]; // Strings for sending and receiving commands / data send / data receive / command received / status received 00014 char recv[128]; 00015 char command[TCPCOMMSBYTESMAX]; 00016 char status[TCPSTATSBYTESMAX]; 00017 char controlcode[8]; 00018 00019 string comandofirebase; 00020 bool firebaseTimeoutExpired = false; 00021 00022 00023 00024 int main() 00025 { 00026 00027 //Inicializacion de los Perifericos 00028 led_azul = OFF; 00029 led_rojo = OFF; 00030 led_verde = OFF; 00031 pc.baud(115200); 00032 00033 esp01_en.mode(PullUp); 00034 esp01_rst.mode(PullUp); 00035 00036 00037 //Inicializacion y Conexion al WiFi 00038 //wifiInit(); 00039 //wifi.Quit(); 00040 wifiInit(); 00041 wifiConnect(); 00042 00043 //ESP8266Interface *net = new ESP8266Interface(); //Con este objeto implementamos todas las funciones de red para la creacion de Sockets para HTTPS 00044 //http_demo(net); 00045 //delete net; //Necesario destruir el objeto cuando ya no se use para desocupar la interface de wifi. 00046 00047 ESP8266Interface *net = new ESP8266Interface(); //Con este objeto implementamos todas las funciones de red para la creacion de Sockets para HTTPS 00048 //delete net; //Necesario destruir el objeto cuando ya no se use para desocupar la interface de wifi. 00049 00050 //Tarea para revisar si hay algun comando en firebase, esta tarea se ejecuta cada x segundos. 00051 firebasecheck.attach(&firebaseCheckTimeout, INTERVALFIREBASECHECK); 00052 00053 while(1) { 00054 if(firebaseTimeoutExpired) { 00055 //Leemos la bsae de datos de firebase para revisar si hay algun comando disponible. 00056 comandofirebase = getFirebaseCommand(net); 00057 00058 //Habilitamos el debugeo de la memoria 00059 //print_all_thread_info(); 00060 //print_heap_and_isr_stack_info(); 00061 00062 if(comandofirebase.compare(AGREGARCONTROL) == 0) { 00063 Timer t; 00064 int tini; 00065 t.start(); 00066 tini = t.read_ms(); 00067 00068 pc.printf("Comando Agregar Control Recibido\r\n"); 00069 putFirebaseCommand(net, WAITING_RF_CODE, 0); 00070 00071 LEDAMARILLO_ON; 00072 while((t.read_ms()- tini) < MAXTIMERXCONTROL) { 00073 if(decoder.available()) { 00074 unsigned long numcode = decoder.getCode(); 00075 pc.printf("Codigo Recibido %x \n\r", numcode); 00076 putFirebaseCommand(net, NEW_CONTROL_RESPONSE, numcode); 00077 break; 00078 } 00079 } 00080 LEDVERDE_ON; 00081 firebaseTimeoutExpired = false; 00082 comandofirebase = NINGUNCOMANDO; 00083 } else { 00084 pc.printf("Ningun comando recibido\r\n"); 00085 firebaseTimeoutExpired = false; 00086 } 00087 00088 } 00089 00090 00091 } 00092 } 00093 00094 void wifiInit(void) 00095 { 00096 pc.printf("Gateway Sistema de Control de Cotos\r\n"); 00097 pc.printf("Resetting WiFi\r\n"); 00098 wifi.Reset(); 00099 wait(2); 00100 wifi.DisableEcho(); 00101 pc.printf("Set mode to Station\r\n"); 00102 wifi.SetMode(STATION); 00103 wifi.RcvReply(recv, 3000); 00104 pc.printf("%s", recv); 00105 wait(2); 00106 pc.printf("Configure for multiple sockets\r\n"); 00107 wifi.SetMultiple(); 00108 wifi.RcvReply(recv, 3000); 00109 pc.printf("%s", recv); 00110 wait(2); 00111 /* 00112 pc.printf("Enable DHCP\r\n"); 00113 wifi.EnableDHCP(); 00114 wifi.RcvReply(recv, 1500); 00115 pc.printf("%s", recv); 00116 wait(2); 00117 */ 00118 } 00119 00120 void wifiConnect(void) 00121 { 00122 char connCheckCounter = 0; 00123 00124 while(!isConnectedToWifi()) { 00125 if(connCheckCounter > MAXWIFICONNCHECKS) { 00126 //pc.printf("Starting Smart Config\r\n"); 00127 led_azul = ON; 00128 wifi.StartSmartConfig(); 00129 wifi.RcvReply(recv, 15000); 00130 //pc.printf("%s", recv); 00131 wait(5); 00132 connCheckCounter=0; 00133 } 00134 connCheckCounter++; 00135 pc.printf("Gateway no conectado, intento de reconexion %d\r\n",connCheckCounter); 00136 wait(1); 00137 } 00138 00139 pc.printf("Gateway is already connected to wifi with the following IP address\r\n"); 00140 wifi.GetIP(recv); 00141 pc.printf("%s", recv); 00142 led_azul = OFF; 00143 led_verde = ON; 00144 wait(2); 00145 00146 } 00147 00148 00149 bool isConnectedToWifi(void) 00150 { 00151 bool status; 00152 wifi.GetConnStatusCode(recv); 00153 //pc.printf("El estado de la conexion es %s", recv); 00154 if(strcmp(recv,"STATUS:2\r")==0) { 00155 led_azul = OFF; 00156 led_rojo = OFF; 00157 led_verde = ON; 00158 status=true; 00159 } else { 00160 status=false; 00161 } 00162 return status; 00163 00164 } 00165 00166 void startServer(int port) 00167 { 00168 //pc.printf("Iniciando servidor en el puerto %d\r\n",port); 00169 wifi.StartServerMode(port); 00170 wifi.RcvReply(recv, 1000); 00171 //pc.printf("%s", recv); 00172 //wait(2); 00173 } 00174 00175 int getTCPContent(char* espdata, char* command, char* status) 00176 { 00177 char i=0; 00178 char offset=0; 00179 char socket=0; 00180 00181 if((espdata[2]=='+') && (espdata[3]=='I') && (espdata[4]=='P') && (espdata[5]=='D')) { 00182 //Obtenemos en socket de conexion 00183 socket = espdata[7]-'0'; 00184 //Buscamos el caracter : para de ahi iniciar el mensaje 00185 for(i=0; i<250; i++) { 00186 if(espdata[i]==':') { 00187 offset = i+1; 00188 break; 00189 } 00190 } 00191 00192 for(i=0; (i<TCPCOMMSBYTESMAX); i++) { 00193 command[i] = espdata[i+offset]; 00194 } 00195 00196 command[TCPCOMMSBYTESMAX] = '\0'; 00197 00198 status[0] = COMMANDREC; 00199 } 00200 00201 return socket; 00202 } 00203 00204 void convertToCharArray(char *arr, unsigned long number) 00205 { 00206 int i = 0; 00207 00208 for (i = 0; i < 8; ++i) { 00209 arr[i] = (char)((((unsigned long) number) >> (56 - (8*i))) & 0xFFu); 00210 } 00211 } 00212 00213 00214 string getFirebaseCommand(NetworkInterface *network) 00215 { 00216 TLSSocket* socket = new TLSSocket(); 00217 string comando = NINGUNCOMANDO; 00218 00219 nsapi_error_t r; 00220 // make sure to check the return values for the calls below (should return NSAPI_ERROR_OK) 00221 r = socket->open(network); 00222 r = socket->set_root_ca_cert(SSL_CA_PEM); 00223 r = socket->connect("https://cotoceiba.firebaseio.com", 443); 00224 00225 00226 //printf("\n----- Conectando con la base de datos de Firebase -----\n"); 00227 //HttpsRequest* get_req = new HttpsRequest(socket, HTTP_GET, "https://cotoceiba.firebaseio.com/Comandos/AppToGateway/Request/Comando.json?auth=ZpXLLURU9KWmW5t1kzBYD2IuBE0V7wdv5vXwDgsH"); 00228 HttpsRequest* get_req = new HttpsRequest(socket, HTTP_GET, "https://cotoceiba.firebaseio.com/Comandos/AppToGateway/Request/Comando.json?"); 00229 00230 HttpResponse* get_res = get_req->send(); 00231 if (!get_res) { 00232 printf("HttpGetRequest failed (error code %d)\n", get_req->get_error()); 00233 comando = NINGUNCOMANDO; 00234 //return 1; 00235 } else { 00236 //printf("\n----- Respuesta de Firebase -----\n"); 00237 //printf("Status: %d - %s\n", get_res->get_status_code(), get_res->get_status_message().c_str()); 00238 00239 comando = get_res->get_body_as_string(); 00240 //pc.printf("%s\r\n",comando.c_str()); 00241 //printf("\nBody (%lu bytes):\n\n%s\n", get_res->get_body_length(), get_res->get_body_as_string().c_str()); 00242 } 00243 00244 00245 delete get_req; 00246 socket->close(); 00247 delete socket; 00248 00249 return comando; 00250 } 00251 00252 void putFirebaseCommand(NetworkInterface *network, char comando, unsigned long numcode) 00253 { 00254 TLSSocket* socket = new TLSSocket(); 00255 char body[100]; 00256 00257 nsapi_error_t r; 00258 // make sure to check the return values for the calls below (should return NSAPI_ERROR_OK) 00259 r = socket->open(network); 00260 r = socket->set_root_ca_cert(SSL_CA_PEM); 00261 r = socket->connect("https://cotoceiba.firebaseio.com", 443); 00262 00263 //printf("\n----- Enviando datos a la base de datos de Firebase -----\n"); 00264 HttpsRequest* post_req = new HttpsRequest(socket, HTTP_PATCH, "https://cotoceiba.firebaseio.com/Comandos/GatewayToApp/Response.json?auth=ZpXLLURU9KWmW5t1kzBYD2IuBE0V7wdv5vXwDgsH"); 00265 post_req->set_header("Content-Type", "application/json"); 00266 00267 sprintf(body, "{\"Comando\":\"%d\",\"Valor1\":\"%X\"}",comando,numcode); 00268 HttpResponse* post_res = post_req->send(body, strlen(body)); 00269 00270 if (!post_res) { 00271 printf("HttpPatchRequest failed (error code %d)\n", post_req->get_error()); 00272 } 00273 00274 // printf("\n----- HTTPS PATCH response -----\n"); 00275 // dump_response(post_res); 00276 socket->close(); 00277 delete socket; 00278 delete post_req; 00279 } 00280 00281 void firebaseCheckTimeout() 00282 { 00283 firebaseTimeoutExpired = true; 00284 00285 } 00286 00287 00288 void http_demo(NetworkInterface *network) 00289 { 00290 TLSSocket* socket = new TLSSocket(); 00291 00292 nsapi_error_t r; 00293 // make sure to check the return values for the calls below (should return NSAPI_ERROR_OK) 00294 r = socket->open(network); 00295 r = socket->set_root_ca_cert(SSL_CA_PEM); 00296 r = socket->connect("https://cotoceiba.firebaseio.com", 443); 00297 00298 printf("\n----- HTTPS GET request -----\n"); 00299 00300 HttpsRequest* get_req = new HttpsRequest(socket, HTTP_GET, "https://cotoceiba.firebaseio.com/Condominos/94.json?auth=ZpXLLURU9KWmW5t1kzBYD2IuBE0V7wdv5vXwDgsH"); 00301 00302 HttpResponse* get_res = get_req->send(); 00303 if (!get_res) { 00304 printf("HttpRequest failed (error code %d)\n", get_req->get_error()); 00305 //return 1; 00306 } 00307 printf("\n----- HTTPS GET response -----\n"); 00308 dump_response(get_res); 00309 delete get_req; 00310 00311 printf("\n----- HTTPS POST request -----\n"); 00312 00313 HttpsRequest* post_req = new HttpsRequest(socket, HTTP_POST, "https://cotoceiba.firebaseio.com/Condominos/52.json?auth=ZpXLLURU9KWmW5t1kzBYD2IuBE0V7wdv5vXwDgsH"); 00314 post_req->set_header("Content-Type", "application/json"); 00315 00316 const char body[] = "{\"nombre\":\"Posteado por Wifi Perros\",\"numcasa\":\"64\"}"; 00317 00318 HttpResponse* post_res = post_req->send(body, strlen(body)); 00319 if (!post_res) { 00320 printf("HttpRequest failed (error code %d)\n", post_req->get_error()); 00321 //return 1; 00322 } 00323 00324 printf("\n----- HTTPS POST response -----\n"); 00325 dump_response(post_res); 00326 delete post_req; 00327 } 00328 00329 void dump_response(HttpResponse* res) 00330 { 00331 printf("Status: %d - %s\n", res->get_status_code(), res->get_status_message().c_str()); 00332 00333 printf("Headers:\n"); 00334 for (size_t ix = 0; ix < res->get_headers_length(); ix++) { 00335 printf("\t%s: %s\n", res->get_headers_fields()[ix]->c_str(), res->get_headers_values()[ix]->c_str()); 00336 } 00337 printf("\nBody (%lu bytes):\n\n%s\n", res->get_body_length(), res->get_body_as_string().c_str()); 00338 }
Generated on Wed Jul 13 2022 01:32:03 by 1.7.2