Gateway con agregar controles mediante firebase migracion a OS5
Dependencies: mbed-http ESP01 Pulse RFDecoder
main.cpp
- Committer:
- Thrillex13
- Date:
- 2019-06-11
- Revision:
- 3:5dceee1c49fc
- Parent:
- 2:bc3973471585
- Child:
- 4:8fed3705384e
File content as of revision 3:5dceee1c49fc:
#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
RFDecoder decoder = RFDecoder(D2,D3); //tx rx
// Global variables
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);
//Inicializacion y Conexion al WiFi
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.
//Iniciamos el servidor
startServer(SERVER_PORT);
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;
}
*/
}
}
}
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");
for (size_t ix = 0; ix < res->get_headers_length(); ix++) {
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());
}