# WiFi

# Conexiones Station / Access Point

ESP32 Arduino (opens new window)

WiFi (opens new window)

# #include "WiFi.hpp"

#include <WiFi.h>

const char* red = "studiomiranda";
const char* contrasena = "88888888";

void initStation () {
  WiFi.begin(red, contrasena);
  Serial.print("Conectando");
  while (WiFi.status() != WL_CONNECTED)
    {
      delay(500);
      Serial.print(".");
    }
  Serial.println();
  Serial.print("Conectado, dirección IP: ");
  Serial.println(WiFi.localIP());
}

void initAccessPoint () {
  WiFi.softAP("PuntoAcceso", "contrasena");
  Serial.println("Soft Access Point: ");
  Serial.println(WiFi.softAPIP());
}

# Servidor Web Asyncrono

# #include "ESPAsyncWebServer.hpp"

// Bibliotecas
#include <ESPAsyncWebServer.h>

// Configuración
#define Led 2

// Instancia 
AsyncWebServer server(80);

// Variables 
char paginaweb[] PROGMEM = R"=====(
<!DOCTYPE html>
<html>
<body>
<center>
<h1>ESP32 HTML</h1>
<h3> LED </h3>
<button onclick="window.location = 'http://'+location.hostname+'/led/on'">On</button>
<button onclick="window.location = 'http://'+location.hostname+'/led/off'">Off</button>
</center>
</body>
</html>
)=====";

// Funciones
void notFound (AsyncWebServerRequest *request)
  {
    request->send(404, "text/plain", "Página no encontrada");
  }

void servidor () {
  server.on("/", [](AsyncWebServerRequest * request)
  {  
  request->send_P(200, "text/html", paginaweb);
  });

   server.on("/led/on", HTTP_GET, [](AsyncWebServerRequest * request)
  { 
    digitalWrite(Led, HIGH);
  request->send_P(200, "text/html", paginaweb);
  });

  server.on("/led/off", HTTP_GET, [](AsyncWebServerRequest * request)
  { 
    digitalWrite(Led, LOW);
  request->send_P(200, "text/html", paginaweb);
  });

  server.onNotFound(notFound);

  server.begin();
}
pinMode(Led, OUTPUT);

# Servidor Web Asincrono + SPIFFS

# #include "ESPAsyncWebServerSPIFFS.hpp"

// Bibliotecas
#include <ESPAsyncWebServer.h>
#include "SPIFFS.h"

// Configuración
#define Led 2

// Instancia 
AsyncWebServer server(80);

// Funciones
void notFound (AsyncWebServerRequest *request)
  {
    request->send(404, "text/plain", "Página no encontrada");
  }

void servidor () {
  if(!SPIFFS.begin(true)){
    Serial.println("A ocurrido un error al montando SPIFFS");
    return;
    }
  server.on("/", HTTP_GET, [](AsyncWebServerRequest * request){
    request->send(SPIFFS, "/index.html", "text/html");
    });
  server.on("/led/on", HTTP_GET, [](AsyncWebServerRequest * request){ 
    digitalWrite(Led, HIGH);
    request->send(SPIFFS, "/index.html", "text/html");
    });
  server.on("/led/off", HTTP_GET, [](AsyncWebServerRequest * request){ 
    digitalWrite(Led, LOW);
    request->send(SPIFFS, "/index.html", "text/html");
    });
  server.onNotFound(notFound);
  server.begin();
}

# ESPAsyncWebServer.hpp

// Descarga la herramienta Sketch Data Upload
// https://github.com/me-no-dev/arduino-esp32fs-plugin/releases/

// Biblotecas
#include "ESPAsyncWebServer.h"
#include "SPIFFS.h"

#define Led 2

// Instancia / constructor
AsyncWebServer server(80);

// Funciones / métodos
void initESPAsyncWebServer (){
  // Initialize SPIFFS
  if(!SPIFFS.begin(true)){
    Serial.println("A ocurrido un error al montando SPIFFS");
    return;
  }
  server.begin();
  server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {
    request->send(SPIFFS, "/index.html", "text/html");
    });
  server.on("/led/on", HTTP_GET, [](AsyncWebServerRequest * request) { 
    digitalWrite(Led, HIGH);
    request->send(SPIFFS, "/index.html", "text/html");
    });
  server.on("/led/off", HTTP_GET, [](AsyncWebServerRequest * request) { 
    digitalWrite(Led, LOW);
    request->send(SPIFFS, "/index.html", "text/html");
    });
}

# HTML

<!DOCTYPE html>
<html>
<body>
<center>
<h1>ESP32 HTML</h1>
<h3> LED </h3>
<button onclick="window.location = 'http://'+location.hostname+'/led/on'">On</button>
<button onclick="window.location = 'http://'+location.hostname+'/led/off'">Off</button>
</center>
</body>
</html>

# WebSocket

# Importar bibliotecas

#include <WebSocketsServer.h>
#define Led 2

void notFound(AsyncWebServerRequest *request)
{
  request->send(404, "text/plain", "¡Página no encontrada!");
}

# Instancia y Función/es (recibir datos)

WebSocketsServer websockets(81);

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {

  switch (type) 
  {
    case WStype_DISCONNECTED:
      Serial.printf("[%u] ¡Desconectado!\n", num);
      break;
    case WStype_CONNECTED: {
        IPAddress ip = websockets.remoteIP(num);
        Serial.printf("[%u] Conectado en %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);

        websockets.sendTXT(num, "Conectado en servidor:");
      }
      break;
    case WStype_TEXT:
      Serial.printf("[%u] Recibe el texto: %s\n", num, payload);
      String mensaje = String((char*)( payload));
      Serial.println(mensaje);

      if(mensaje == "Led esta en OFF"){
        digitalWrite(Led,LOW);
      }

      if(mensaje == "Led esta en ON"){
        digitalWrite(Led,HIGH);
      }
  }
}

# WebSocketsServer.hpp

// Bibliotecas
#include <WebSocketsServer.h>
#include <ArduinoJson.h>
#include <Ticker.h>

// Configuración
#define Led 2

void enviarDatosSensorWebsockets ();

// Instancia / constructor
WebSocketsServer websockets(81);
Ticker timer;

// Funciones / Métodos
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
  switch (type) {
    case WStype_DISCONNECTED:
      Serial.printf("[%u] ¡Desconectado!\n", num);
      break;
    case WStype_CONNECTED: {
        IPAddress ip = websockets.remoteIP(num);
        Serial.printf("[%u] Conectado en %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);
      }
      break;
    case WStype_TEXT:
      Serial.printf("[%u] Texto: %s\n", num, payload);
      String mensaje = String((char*)( payload));
      Serial.println(mensaje);
      DynamicJsonDocument doc(200); // documento (capacidad)
      DeserializationError error = deserializeJson(doc, mensaje);
        if (error) {
        Serial.print("deserializeJson() failed: ");
        Serial.println(error.c_str());
        return;
        }  
      int estadoLed = doc["Led"]; // el estado será de 0 o 1
      digitalWrite(Led,estadoLed);
      }
}

void enviarDatosSensorWebsockets () {
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  float t = data.temperature;
  float h = data.humidity;
  if (isnan(h) || isnan(t) ) {
    Serial.println(F("Fallo de lectura en sensor DHT!"));
    return;
    }
  String JSON_Data = "{\"temp\":";
         JSON_Data += t;
         JSON_Data += ",\"hum\":";
         JSON_Data += h;
         JSON_Data += "}";       
   Serial.println(JSON_Data);
   websockets.broadcastTXT(JSON_Data);  // envia datos a todos los clientes conectados
}
  
void initWebSocketsServer () {
  websockets.begin();
  websockets.onEvent(webSocketEvent);
  timer.attach(5,enviarDatosSensorWebsockets); 
}

# Función (enviar datos)

// Función envío datos por websocket en formato Json
void enviarDatosSensor() {
   String JSON_Data = "{\"temperatura\":";
          JSON_Data += temperatura;
          JSON_Data += ",\"humedad\":";
          JSON_Data += humedad;
          JSON_Data += ",\"termostato\":";
          JSON_Data += termostato;
          JSON_Data += ",\"rele\":";
          JSON_Data += rele;
          JSON_Data += "}";
   Serial.println(JSON_Data);
   websockets.broadcastTXT(JSON_Data);  // envia datos a todos los clientes conectados
}

# void setup()

  Serial.begin(115200);
  pinMode(Led, OUTPUT);
  
  WiFi.softAP("PuntoAcceso", "");
  Serial.println("softAP");
  Serial.println("");
  Serial.println(WiFi.softAPIP());

  if(!SPIFFS.begin(true)){
    Serial.println("A ocurrido un error al montar SPIFFS");
    return;
  }
  
  server.on("/", HTTP_GET, [](AsyncWebServerRequest * request)
  { 
   request->send(SPIFFS, "/index.html", "text/html");
  });

  server.onNotFound(notFound);

  server.begin();
  websockets.begin();
  websockets.onEvent(webSocketEvent);

# void loop()

 websockets.loop();
 enviarDatosSensor();