Joa0712

Conexión WIFI - ESP8266 + Server + AP + WS

Sep 2nd, 2025 (edited)
22
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 3.96 KB | Software | 0 0
  1. // Conexión WIFI del ESP 8266 + Server con página web dinámica mas Access Point + Web Socket
  2.  
  3. #include <ESP8266WiFi.h>
  4. #include <ESP8266WebServer.h>
  5. #include <WebSocketsServer.h>
  6.  
  7. // ====== HW & tiempos ======
  8. #define LED                 LED_BUILTIN   // activo en LOW
  9. #define T_REINTENTO_MS      4000
  10. #define BLINK_CONECTANDO    1000
  11. #define BLINK_DESCONECTADO  500
  12. #define BLINK_CONECTADO     3000
  13.  
  14. // ====== credenciales ======
  15. const char* WIFI_SSID = "Alumnos";
  16. const char* WIFI_PASS = "";
  17.  
  18. // ====== Access Point ======
  19. const char* AP_SSID = "ESP8266_AP";
  20. const char* AP_PASS = "12345678";
  21.  
  22. // ====== estado ======
  23. enum EstadoWifi { DESCONECTADO, CONECTANDO, CONECTADO };
  24. EstadoWifi estado = DESCONECTADO;
  25.  
  26. ESP8266WebServer server(80);
  27. WebSocketsServer webSocket(81);
  28. bool serverIniciado = false;
  29.  
  30. unsigned long tBlink = 0;
  31. unsigned long periodoBlink = BLINK_DESCONECTADO;
  32. bool ledState = false;
  33.  
  34. unsigned long tRetry = 0;
  35.  
  36. // ====== prototipos ======
  37. void Conectar();
  38. void GestionWifi();
  39. void BlinkLed();
  40. void IniciarServerSiConectado();
  41. void IniciarAP();
  42. void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length);
  43.  
  44. // ====== HTTP handlers ======
  45. void handleRoot() {
  46.   String html = "<h2>ESP8266 OK</h2><p>IP STA: " + WiFi.localIP().toString() + "</p>";
  47.   html += "<p>IP AP: " + WiFi.softAPIP().toString() + "</p>";
  48.   html += "<p>SSID STA: " + String(WIFI_SSID) + "</p>";
  49.   server.send(200, "text/html", html);
  50. }
  51.  
  52. void setup() {
  53.   pinMode(LED, OUTPUT);
  54.   digitalWrite(LED, HIGH);        // apagado (inverso)
  55.   Serial.begin(115200);
  56.   Serial.println("Hola");
  57.  
  58.   // Modo mixto: STA + AP
  59.   WiFi.mode(WIFI_AP_STA);
  60.   IniciarAP();
  61.   Conectar();
  62.  
  63.   // Inicializar WebSocket
  64.   webSocket.begin();
  65.   webSocket.onEvent(webSocketEvent);
  66. }
  67.  
  68. void loop() {
  69.   GestionWifi();
  70.   BlinkLed();
  71.   IniciarServerSiConectado();
  72.   if (serverIniciado) server.handleClient();
  73.   webSocket.loop();
  74. }
  75.  
  76. // ====== lógica ======
  77. void Conectar() {
  78.   Serial.printf("Conectando a %s...\n", WIFI_SSID);
  79.   WiFi.begin(WIFI_SSID, WIFI_PASS);
  80.   estado = CONECTANDO;
  81.   periodoBlink = BLINK_CONECTANDO;
  82. }
  83.  
  84. void GestionWifi() {
  85.   wl_status_t st = WiFi.status();
  86.  
  87.   if (st == WL_CONNECTED) {
  88.     if (estado != CONECTADO) {
  89.       estado = CONECTADO;
  90.       periodoBlink = BLINK_CONECTADO;
  91.       Serial.print("Conectado. IP STA: ");
  92.       Serial.println(WiFi.localIP());
  93.     }
  94.     return;
  95.   }
  96.  
  97.   // no conectado
  98.   if (estado != CONECTANDO) {
  99.     estado = DESCONECTADO;
  100.     periodoBlink = BLINK_DESCONECTADO;
  101.   }
  102.  
  103.   if (millis() - tRetry >= T_REINTENTO_MS) {
  104.     tRetry = millis();
  105.     Conectar();
  106.   }
  107. }
  108.  
  109. void BlinkLed() {
  110.   if (millis() - tBlink < periodoBlink) return;
  111.   tBlink = millis();
  112.   ledState = !ledState;
  113.   digitalWrite(LED, ledState ? LOW : HIGH); // LOW enciende
  114. }
  115.  
  116. void IniciarServerSiConectado() {
  117.   if (serverIniciado) return;
  118.  
  119.   server.on("/", handleRoot);
  120.   server.begin();
  121.   serverIniciado = true;
  122.   Serial.println("HTTP listo -> abre http://<IP>/");
  123. }
  124.  
  125. void IniciarAP() {
  126.   WiFi.softAP(AP_SSID, AP_PASS);
  127.   Serial.print("AP Iniciado. SSID: ");
  128.   Serial.print(AP_SSID);
  129.   Serial.print(" | IP: ");
  130.   Serial.println(WiFi.softAPIP());
  131. }
  132.  
  133. // ====== WebSocket ======
  134. void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
  135.   switch(type) {
  136.     case WStype_CONNECTED: {
  137.       Serial.printf("Cliente WS [%u] conectado\n", num);
  138.       webSocket.sendTXT(num, "Conectado al WebSocket!");
  139.       break;
  140.     }
  141.     case WStype_DISCONNECTED: {
  142.       Serial.printf("Cliente WS [%u] desconectado\n", num);
  143.       break;
  144.     }
  145.     case WStype_TEXT: {
  146.       String msg = String((char*)payload);
  147.       Serial.printf("WS [%u] dice: %s\n", num, msg.c_str());
  148.       // Responder con eco
  149.       webSocket.sendTXT(num, "Echo: " + msg);
  150.  
  151.       // Control LED desde WS
  152.       if (msg == "ON") digitalWrite(LED, LOW);
  153.       if (msg == "OFF") digitalWrite(LED, HIGH);
  154.       break;
  155.     }
  156.   }
  157. }
  158.  
Advertisement
Add Comment
Please, Sign In to add comment