All-in-one web-socket library for the ESP32.
MicroEspSocket is based on a modified version of arduinoWebSockets.
The library manages both client TES_Client
and server TES_Server
.
- Automatic management of connected clients
- Event-based logic
- WiFi and web-socket handling in a single place
lib_deps =
. . .
https://github.com/Fattorino/ToroEspSocket.git#3.0.0
- Download the latest .zip from the release page;
- Copy the MicroEspSockets folder into the lib folder of your PlatformIO project;
#include <ToroEspSocketServer>
or/end#include <ToroEspSocketClient>
#include <Arduino.h>
#include <ToroEspSocketServer.h>
TES_Server tesServer;
void onDemoEvent(int index, String msg)
{
Serial.printf("[DEMO] From client %d, got ==> ", index);
Serial.println(msg);
}
void setup()
{
Serial.begin(9600);
uint maxDeviceConnected = 8;
tesServer.start_wifi("apName", "apPassword", maxDeviceConnected);
tesServer.start_ws(81);
tesServer.addEventListener("demoEvent", onDemoEvent);
Serial.println("\nStarted!!");
}
ulong auxMillis = 0;
void loop()
{
tesServer.loop();
if (millis() > auxMillis + 5000) // Sending demo messages every five seconds
{
auxMillis = millis();
tesServer.broadcastMsg("demoEvent", "Demo message to all clients");
}
}
#include <Arduino.h>
#include <ToroEspSocketClient.h>
TES_Client tesClient("clientGroup");
void onDemoEvent(String msg)
{
Serial.print("[DEMO] msg ==> ");
Serial.println(msg);
tesClient.sendMsg("demoEvent", "Client response!");
}
void setup()
{
Serial.begin(9600);
tesClient.connect_to_wifi("apName", "apPassword");
tesClient.start_ws("192.168.4.1", 81);
tesClient.addEventListener("demoEvent", onDemoEvent);
Serial.println("\nStarted!!");
}
void loop()
{
tesClient.loop();
}
- Every five seconds, the server will broadcast a message with the tag
demoEvent
to every TES_Client connected; - Clients receive the message, the tag
demoEvent
gets decoded so the related functiononDemoEvent
gets called; - The client sends a message with the tag
demoEvent
to the server; - The server receives the message, the tag
demoEvent
gets decoded so the related functiononDemoEvent
gets called; - Inside the function
onDemoEvent
(server side), the content of the message gets printed.