ESP32: WebSocket-Minimalbeispiel (ESPAsyncWebserver / PlatformIO)

English Deutsch

Minimale Firmware zur Verwendung von WebSockets auf dem ESP32 mit ESPAsyncWebserver:

main.cpp

main.cpp
#include <Arduino.h>
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <ArduinoJson.h>

AsyncWebServer server(80);
AsyncWebSocket ws("/ws");

AsyncWebSocketClient* wsClient;

void onWsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
  if(type == WS_EVT_CONNECT){
    wsClient = client;
  } else if(type == WS_EVT_DISCONNECT){
    wsClient = nullptr;
  }
}

/**
 * Auf WiFi-Verbindung warten, und falls nicht verbunden, neu starten
 */
void waitForWiFiConnectOrReboot(bool printOnSerial=true) {
  uint32_t notConnectedCounter = 0;
  while (WiFi.status() != WL_CONNECTED) {
      delay(100);
      if(printOnSerial) {
        Serial.println("Wifi connecting...");
      }
      notConnectedCounter++;
      if(notConnectedCounter > 50) { // Board zurücksetzen, wenn nach 5s nicht verbunden
          if(printOnSerial) {
            Serial.println("Resetting due to Wifi not connecting...");
          }
          ESP.restart();
      }
  }
  if(printOnSerial) {
    // WiFi-IP-Adresse ausgeben
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
  }
}


void setup() {
  Serial.begin(115200);
  WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE);
  WiFi.setHostname("ESP-Websocket-Test");

  WiFi.begin("MyWifiSSID", "MyWifiPassword");
  waitForWiFiConnectOrReboot();

  // Webserver starten
  ws.onEvent(onWsEvent);
  server.addHandler(&ws);
  server.begin();
}

uint64_t counter = 0;
void loop() {
  // Wenn Client verbunden ist ...
  if(wsClient != nullptr && wsClient->canSend()) {
    // .. Hallo-Nachricht senden :-)
    wsClient->text("Hello client");
  }

  // 10 ms warten
  delay(10);
}

platformio.ini:

platformio.ini
[env:nodemcu-32s]
platform = espressif32
board = nodemcu-32s
framework = arduino
monitor_speed = 115200
lib_deps =
    ESP Async [email protected]
    [email protected]

Python-Code zum Testen:

ws_test.py
import websocket
ws = websocket.WebSocket()
ws.connect("ws://192.168.1.211/ws")
while True:
    result = ws.recv()
    print(result)

Dies gibt Hello Client viele Male pro Sekunde aus.


Check out similar posts by category: C/C++, ESP8266/ESP32, PlatformIO