Minimal firmware to use WebSockets on the ESP32 using ESPAsyncWebserver:
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; } } /** * Wait for WiFi connection, and, if not connected, reboot */ 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) { // Reset board if not connected after 5s if(printOnSerial) { Serial.println("Resetting due to Wifi not connecting..."); } ESP.restart(); } } if(printOnSerial) { // Print wifi IP addess 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(); // Start webserver ws.onEvent(onWsEvent); server.addHandler(&ws); server.begin(); } uint64_t counter = 0; void loop() { // If client is connected ... if(wsClient != nullptr && wsClient->canSend()) { // .. send hello message :-) wsClient->text("Hello client"); } // Wait 10 ms delay(10); }
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 for testing:
import websocket ws = websocket.WebSocket() ws.connect("ws://192.168.1.211/ws") while True: result = ws.recv() print(result)
This will print Hello Client
many times a second.