- Notifications
You must be signed in to change notification settings - Fork0
Asynchronous HTTP and WebSocket Server Library for (ESP32_S2/S3/C3 + LwIP ENC28J60). Now supporting using CString to save heap to send very large data and with examples to demo how to use beginChunkedResponse() to send large html in chunks
License
khoih-prog/AsyncWebServer_ESP32_SC_ENC
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
- Table of contents
- Important Note
- Why do we need this AsyncWebServer_ESP32_SC_ENC library
- Changelog
- Prerequisites
- Installation
- Important things to remember
- Principles of operation
- Request Variables
- Responses
- Redirect to another URL
- Basic response with HTTP Code
- Basic response with HTTP Code and extra headers
- Basic response with string content
- Basic response with string content and extra headers
- Respond with content coming from a Stream
- Respond with content coming from a Stream and extra headers
- Respond with content coming from a Stream containing templates
- Respond with content coming from a Stream containing templates and extra headers
- Respond with content using a callback
- Respond with content using a callback and extra headers
- Respond with content using a callback containing templates
- Respond with content using a callback containing templates and extra headers
- Chunked Response
- Chunked Response containing templates
- Print to response
- ArduinoJson Basic Response
- ArduinoJson Advanced Response
- Param Rewrite With Matching
- Using filters
- Bad Responses
- Async WebSocket Plugin
- Async Event Source Plugin
- Remove handlers and rewrites
- Setting up the server
- How to connect ENC28J60 to ESP32_S2/S3/C3
- Examples
- 1. Async_AdvancedWebServer
- 2. Async_AdvancedWebServer_MemoryIssues_SendArduinoString
- 3. Async_AdvancedWebServer_MemoryIssues_Send_CString
- 4. Async_AdvancedWebServer_SendChunked
- 5. Async_HelloServer
- 6. Async_HelloServer2
- 7. Async_HttpBasicAuth
- 8. AsyncMultiWebServer_ESP32_ENC
- 9. Async_PostServer
- 10. Async_RegexPatterns_ESP32_ENC
- 11. AsyncSimpleServer_ESP32_ENC
- 12. AsyncWebServer_SendChunked
- 13. Async_WebSocketsServer
- 14. MQTTClient_Auth
- 15. MQTTClient_Basic
- 16. MQTT_ThingStream
- Example Async_AdvancedWebServer
- Debug Terminal Output Samples
- 1. AsyncMultiWebServer_ESP32_ENC on ESP32S3_DEV with ESP32_S3_ENC28J60
- 2. Async_AdvancedWebServer_MemoryIssues_Send_CString on ESP32S3_DEV with ESP32_S3_ENC28J60
- 3. Async_AdvancedWebServer_SendChunked on ESP32S3_DEV with ESP32_S3_ENC28J60
- 4. AsyncWebServer_SendChunked on ESP32S3_DEV with ESP32_S3_ENC28J60
- 5. Async_WebSocketsServer on ESP32S3_DEV with ESP32_S3_ENC28J60
- 6. Async_HTTPBasicAuth on ESP32S3_DEV with ESP32_S3_ENC28J60
- 7. Async_AdvancedWebServer_SendChunked on ESP32S2_DEV with ESP32_S2_ENC28J60
- 8. Async_AdvancedWebServer_SendChunked on ESP32C3_DEV with ESP32_C3_ENC28J60
- Debug
- Troubleshooting
- Issues
- TO DO
- DONE
- Contributions and Thanks
- Contributing
- License
- Copyright
The library permits usingCString to save heap to sendvery large data.
Check themarvelleous PRs of@salasidis inPortenta_H7_AsyncWebServer library
- request->send(200, textPlainStr, jsonChartDataCharStr); - Without using String Class - to save heap #8
- All memmove() removed - string no longer destroyed #11
and these new examples
- Async_AdvancedWebServer_MemoryIssues_Send_CString
- Async_AdvancedWebServer_MemoryIssues_SendArduinoString
If using Arduino String, to send a buffer around 30 KBytes, the usedMax Heap is around144,988 bytes
If using CString in regular memory, with the same 30 KBytes, the usedMax Heap is around114,024 bytes, saving around a buffer size (30 KBytes)
This is very critical in use-cases where sendingvery large data is necessary, withoutheap-allocation-error.
- The traditional function used to send
Arduino Stringis
voidsend(int code,const String& contentType = String(),const String& content = String());
such as
request->send(200, textPlainStr, ArduinoStr);
The required additional HEAP is about3 times of the String size
- To use
CStringwith copying while sending. Use function
voidsend(int code,const String& contentType,constchar *content,bool nonDetructiveSend =true);// RSMOD
such as
request->send(200, textPlainStr, cStr);
The required additional HEAP is also about2 times of the CString size because ofunnecessary copies of the CString in HEAP. Avoid thisunefficient way.
- To use
CStringwithout copying while sending. Use function
voidsend(int code,const String& contentType,constchar *content,bool nonDetructiveSend =true);// RSMOD
such as
request->send(200, textPlainStr, cStr,false);
The required additional HEAP is about1 times of the CString size. This way is the best andmost efficient way to use by avoiding ofunnecessary copies of the CString in HEAP
Why do we need thisAsyncWebServer_ESP32_SC_ENC library
This library is based on, modified from:
to apply the better and fasterasynchronous feature of thepowerfulESPAsyncWebServer Library into(ESP32_S2/S3/C3 + LwIP ENC28J60).
- Using asynchronous network means that you can handlemore than one connection at the same time
- You are called once the request is ready and parsed
- When you send the response, you areimmediately ready to handle other connections while the server is taking care of sending the response in the background
- Speed is OMG
- Easy to use API, HTTP Basic and Digest MD5 Authentication (default), ChunkedResponse
- Easily extensible to handleany type of content
- Supports Continue 100
- Async WebSocket plugin offering different locations without extra servers or ports
- Async EventSource (Server-Sent Events) plugin to send events to the browser
- URL Rewrite plugin for conditional and permanent url rewrites
- ServeStatic plugin that supports cache, Last-Modified, default index and more
- Simple template processing engine to handle templates
- ESP32_S3 boards using
LwIP ENC28J60 Ethernet - ESP32_S2 boards using
LwIP ENC28J60 Ethernet - ESP32_C3 boards using
LwIP ENC28J60 Ethernet
Arduino IDE 1.8.19+for Arduino.ESP32 Core 2.0.5+for ESP32_S2/S3/C3-based boards. ESP32 Latest CoreAsyncTCP library v1.1.1+
The best and easiest way is to useArduino Library Manager. Search forAsyncWebServer_ESP32_SC_ENC, then select / install the latest version. You can also use this link for more detailed instructions.
- Navigate toAsyncWebServer_ESP32_SC_ENC page.
- Download the latest release
AsyncWebServer_ESP32_SC_ENC-main.zip. - Extract the zip file to
AsyncWebServer_ESP32_SC_ENC-maindirectory - Copy the whole
AsyncWebServer_ESP32_SC_ENC-mainfolder to Arduino libraries' directory such as~/Arduino/libraries/.
- InstallVS Code
- InstallPlatformIO
- InstallAsyncWebServer_ESP32_SC_ENC library by usingLibrary Manager. Search forAsyncWebServer_ESP32_SC_ENC inPlatform.io Author's Libraries
- Use includedplatformio.ini file from examples to ensure that all dependent libraries will installed automatically. Please visit documentation for the other options and examples atProject Configuration File
- This isfully asynchronous server and as such does not run on the
loop()thread. - You can not use
yield()ordelay()or any function that uses them inside the callbacks - The server is smart enough to know when to close the connection and free resources
- You can not send more than one response to a single request
- Listens for connections
- Wraps the new clients into
Request - Keeps track of clients and cleans memory
- Manages
Rewritesand apply them on the request url - Manages
Handlersand attaches them to Requests
- TCP connection is received by the server
- The connection is wrapped inside
Requestobject - When the request head is received (type, url, get params, http version and host),the server goes through all
Rewrites(in the order they were added) to rewrite the url and inject query parameters,next, it goes through all attachedHandlers(in the order they were added) trying to find onethatcanHandlethe given request. If none are found, the default(catch-all) handler is attached. - The rest of the request is received, calling the
handleUploadorhandleBodymethods of theHandlerif they are needed (POST+File/Body) - When the whole request is parsed, the result is given to the
handleRequestmethod of theHandlerand is ready to be responded to - In the
handleRequestmethod, to theRequestis attached aResponseobject (see below) that will serve the response data back to the client - When the
Responseis sent, the client is closed and freed from the memory
- The
Rewritesare used to rewrite the request url and/or inject get parameters for a specific request url path. - All
Rewritesare evaluated on the request in the order they have been added to the server. - The
Rewritewill change the request url only if the request url (excluding get parameters) is fully matchthe rewrite url, and when the optionalFiltercallback return true. - Setting a
Filterto theRewriteenables to control when to apply the rewrite, decision can be based onrequest url, http version, request host/port/target host, get parameters or the request client's localIP or remoteIP. - The
Rewritecan specify a target url with optional get parameters, e.g./to-url?with=params
- The
Handlersare used for executing specific actions to particular requests - One
Handlerinstance can be attached to any request and lives together with the server - Setting a
Filterto theHandlerenables to control when to apply the handler, decision can be based onrequest url, http version, request host/port/target host, get parameters or the request client's localIP or remoteIP. - The
canHandlemethod is used for handler specific control on whether the requests can be handledand for declaring any interesting headers that theRequestshould parse. Decision can be based on requestmethod, request url, http version, request host/port/target host and get parameters - Once a
Handleris attached to givenRequest(canHandlereturned true)thatHandlertakes care to receive any file/data upload and attach aResponseonce theRequesthas been fully parsed Handlersare evaluated in the order they are attached to the server. ThecanHandleis called onlyif theFilterthat was set to theHandlerreturn true.- The first
Handlerthat can handle the request is selected, not furtherFilterandcanHandleare called.
- The
Responseobjects are used to send the response data back to the client - The
Responseobject lives with theRequestand is freed on end or disconnect - Different techniques are used depending on the response type to send the data in packetsreturning back almost immediately and sending the next packet when this one is received.Any time in between is spent to run the user loop and handle other network packets
- Responding asynchronously is probably the most difficult thing for most to understand
- Many different options exist for the user to make responding a background task
AsyncWebServer_ESP32_SC_ENCcontains simple template processing engine.- Template processing can be added to most response types.
- Currently it supports only replacing template placeholders with actual values. No conditional processing, cycles, etc.
- Placeholders are delimited with
%symbols. Like this:%TEMPLATE_PLACEHOLDER%. - It works by extracting placeholder name from response text and passing it to user provided function which should return actual value to be used instead of placeholder.
- Since it's user provided function, it is possible for library users to implement conditional processing and cycles themselves.
- Since it's impossible to know the actual response size after template processing step in advance (and, therefore, to include it in response headers), the response becomeschunked.
request->version();// uint8_t: 0 = HTTP/1.0, 1 = HTTP/1.1request->method();// enum: HTTP_GET, HTTP_POST, HTTP_DELETE, HTTP_PUT, HTTP_PATCH, HTTP_HEAD, HTTP_OPTIONSrequest->url();// String: URL of the request (not including host, port or GET parameters)request->host();// String: The requested host (can be used for virtual hosting)request->contentType();// String: ContentType of the request (not available in Handler::canHandle)request->contentLength();// size_t: ContentLength of the request (not available in Handler::canHandle)request->multipart();// bool: True if the request has content type "multipart"
//List all collected headersint headers = request->headers();int i;for (i=0;i<headers;i++){ AsyncWebHeader* h = request->getHeader(i); Serial.printf("HEADER[%s]: %s\n", h->name().c_str(), h->value().c_str());}//get specific header by nameif (request->hasHeader("MyHeader")){ AsyncWebHeader* h = request->getHeader("MyHeader"); Serial.printf("MyHeader: %s\n", h->value().c_str());}//List all collected headers (Compatibility)int headers = request->headers();int i;for (i=0;i<headers;i++){ Serial.printf("HEADER[%s]: %s\n", request->headerName(i).c_str(), request->header(i).c_str());}//get specific header by name (Compatibility)if (request->hasHeader("MyHeader")){ Serial.printf("MyHeader: %s\n", request->header("MyHeader").c_str());}
//List all parametersint params = request->params();for (int i=0;i<params;i++){ AsyncWebParameter* p = request->getParam(i);if (p->isFile()) {//p->isPost() is also true Serial.printf("FILE[%s]: %s, size: %u\n", p->name().c_str(), p->value().c_str(), p->size()); }elseif (p->isPost()) { Serial.printf("POST[%s]: %s\n", p->name().c_str(), p->value().c_str()); }else { Serial.printf("GET[%s]: %s\n", p->name().c_str(), p->value().c_str()); }}//Check if GET parameter existsif (request->hasParam("download")) AsyncWebParameter* p = request->getParam("download");//Check if POST (but not File) parameter existsif (request->hasParam("download",true)) AsyncWebParameter* p = request->getParam("download",true);//Check if FILE was uploadedif (request->hasParam("download",true,true)) AsyncWebParameter* p = request->getParam("download",true,true);//List all parameters (Compatibility)int args = request->args();for (int i=0;i<args;i++){ Serial.printf("ARG[%s]: %s\n", request->argName(i).c_str(), request->arg(i).c_str());}//Check if parameter exists (Compatibility)if (request->hasArg("download")) String arg = request->arg("download");
Endpoints which consume JSON can use a special handler to get ready to use JSON data in the request callback:
#include"AsyncJson.h"#include"ArduinoJson.h"AsyncCallbackJsonWebHandler* handler =new AsyncCallbackJsonWebHandler("/rest/endpoint", [](AsyncWebServerRequest *request, JsonVariant &json) { JsonObject& jsonObj = json.as<JsonObject>();// ...});server.addHandler(handler);
//to local urlrequest->redirect("/login");//to external urlrequest->redirect("http://esp8266.com");
request->send(404);//Sends 404 File Not Found
AsyncWebServerResponse *response = request->beginResponse(404);//Sends 404 File Not Foundresponse->addHeader("Server","AsyncWebServer_ESP32_SC_ENC");request->send(response);
request->send(200,"text/plain","Hello World!");
AsyncWebServerResponse *response = request->beginResponse(200,"text/plain","Hello World!");response->addHeader("Server","AsyncWebServer");request->send(response);
//read 12 bytes from Serial and send them as Content Type text/plainrequest->send(Serial,"text/plain",12);
//read 12 bytes from Serial and send them as Content Type text/plainAsyncWebServerResponse *response = request->beginResponse(Serial,"text/plain",12);response->addHeader("Server","AsyncWebServer_ESP32_SC_ENC");request->send(response);
Stringprocessor(const String& var){if (var =="HELLO_FROM_TEMPLATE")returnF("Hello world!");returnString();}// ...//read 12 bytes from Serial and send them as Content Type text/plainrequest->send(Serial,"text/plain",12, processor);
Stringprocessor(const String& var){if (var =="HELLO_FROM_TEMPLATE")returnF("Hello world!");returnString();}// ...//read 12 bytes from Serial and send them as Content Type text/plainAsyncWebServerResponse *response = request->beginResponse(Serial,"text/plain",12, processor);response->addHeader("Server","AsyncWebServer_ESP32_SC_ENC");request->send(response);
//send 128 bytes as plain textrequest->send("text/plain",128, [](uint8_t *buffer,size_t maxLen,size_t index) -> size_t {//Write up to "maxLen" bytes into "buffer" and return the amount written.//index equals the amount of bytes that have been already sent//You will not be asked for more bytes once the content length has been reached.//Keep in mind that you can not delay or yield waiting for more data!//Send what you currently have and you will be asked for more againreturn mySource.read(buffer, maxLen);});
//send 128 bytes as plain textAsyncWebServerResponse *response = request->beginResponse("text/plain",128, [](uint8_t *buffer,size_t maxLen,size_t index) -> size_t {//Write up to "maxLen" bytes into "buffer" and return the amount written.//index equals the amount of bytes that have been already sent//You will not be asked for more bytes once the content length has been reached.//Keep in mind that you can not delay or yield waiting for more data!//Send what you currently have and you will be asked for more againreturn mySource.read(buffer, maxLen);});response->addHeader("Server","AsyncWebServer_ESP32_SC_ENC");request->send(response);
Stringprocessor(const String& var){if (var =="HELLO_FROM_TEMPLATE")returnF("Hello world!");returnString();}// ...//send 128 bytes as plain textrequest->send("text/plain",128, [](uint8_t *buffer,size_t maxLen,size_t index) -> size_t {//Write up to "maxLen" bytes into "buffer" and return the amount written.//index equals the amount of bytes that have been already sent//You will not be asked for more bytes once the content length has been reached.//Keep in mind that you can not delay or yield waiting for more data!//Send what you currently have and you will be asked for more againreturn mySource.read(buffer, maxLen);}, processor);
Stringprocessor(const String& var){if (var =="HELLO_FROM_TEMPLATE")returnF("Hello world!");returnString();}// ...//send 128 bytes as plain textAsyncWebServerResponse *response = request->beginResponse("text/plain",128, [](uint8_t *buffer,size_t maxLen,size_t index) -> size_t {//Write up to "maxLen" bytes into "buffer" and return the amount written.//index equals the amount of bytes that have been already sent//You will not be asked for more bytes once the content length has been reached.//Keep in mind that you can not delay or yield waiting for more data!//Send what you currently have and you will be asked for more againreturn mySource.read(buffer, maxLen);}, processor);response->addHeader("Server","AsyncWebServer_ESP32_SC_ENC");request->send(response);
Used when content length is unknown. Works best if the client supports HTTP/1.1
AsyncWebServerResponse *response = request->beginChunkedResponse("text/plain", [](uint8_t *buffer,size_t maxLen,size_t index) -> size_t {//Write up to "maxLen" bytes into "buffer" and return the amount written.//index equals the amount of bytes that have been already sent//You will be asked for more data until 0 is returned//Keep in mind that you can not delay or yield waiting for more data!return mySource.read(buffer, maxLen);});response->addHeader("Server","AsyncWebServer_ESP32_SC_ENC");request->send(response);
Used when content length is unknown. Works best if the client supports HTTP/1.1
Stringprocessor(const String& var){if (var =="HELLO_FROM_TEMPLATE")returnF("Hello world!");returnString();}// ...AsyncWebServerResponse *response = request->beginChunkedResponse("text/plain", [](uint8_t *buffer,size_t maxLen,size_t index) -> size_t {//Write up to "maxLen" bytes into "buffer" and return the amount written.//index equals the amount of bytes that have been already sent//You will be asked for more data until 0 is returned//Keep in mind that you can not delay or yield waiting for more data!return mySource.read(buffer, maxLen);}, processor);response->addHeader("Server","AsyncWebServer_ESP32_SC_ENC");request->send(response);
AsyncResponseStream *response = request->beginResponseStream("text/html");response->addHeader("Server","AsyncWebServer_ESP32_SC_ENC");response->printf("<!DOCTYPE html><html><head><title>Webpage at %s</title></head><body>", request->url().c_str());response->print("<h2>Hello");response->print(request->client()->remoteIP());response->print("</h2>");response->print("<h3>General</h3>");response->print("<ul>");response->printf("<li>Version: HTTP/1.%u</li>", request->version());response->printf("<li>Method: %s</li>", request->methodToString());response->printf("<li>URL: %s</li>", request->url().c_str());response->printf("<li>Host: %s</li>", request->host().c_str());response->printf("<li>ContentType: %s</li>", request->contentType().c_str());response->printf("<li>ContentLength: %u</li>", request->contentLength());response->printf("<li>Multipart: %s</li>", request->multipart()?"true":"false");response->print("</ul>");response->print("<h3>Headers</h3>");response->print("<ul>");int headers = request->headers();for (int i=0;i<headers;i++){ AsyncWebHeader* h = request->getHeader(i); response->printf("<li>%s: %s</li>", h->name().c_str(), h->value().c_str());}response->print("</ul>");response->print("<h3>Parameters</h3>");response->print("<ul>");int params = request->params();for (int i=0;i<params;i++){ AsyncWebParameter* p = request->getParam(i);if (p->isFile()) { response->printf("<li>FILE[%s]: %s, size: %u</li>", p->name().c_str(), p->value().c_str(), p->size()); }elseif (p->isPost()) { response->printf("<li>POST[%s]: %s</li>", p->name().c_str(), p->value().c_str()); }else { response->printf("<li>GET[%s]: %s</li>", p->name().c_str(), p->value().c_str()); }}response->print("</ul>");response->print("</body></html>");//send the response lastrequest->send(response);
This way of sending Json is great for when the result isbelow 4KB
#include"AsyncJson.h"#include"ArduinoJson.h"AsyncResponseStream *response = request->beginResponseStream("application/json");DynamicJsonBuffer jsonBuffer;JsonObject &root = jsonBuffer.createObject();root["heap"] = ESP.getFreeHeap();root["ssid"] = WiFi.SSID();root.printTo(*response);request->send(response);
This response can handle reallylarge Json objects (tested to 40KB)
There isn't any noticeable speed decrease for small results with the method above
Since ArduinoJson does not allow reading parts of the string, the whole Json has to be passed every time achunks needs to be sent, which shows speed decrease proportional to the resulting json packets
#include"AsyncJson.h"#include"ArduinoJson.h"AsyncJsonResponse * response =new AsyncJsonResponse();response->addHeader("Server","AsyncWebServer");JsonObject& root = response->getRoot();root["IP"] = Ethernet.localIP();response->setLength();request->send(response);
It is possible to rewrite the request url with parameter matchg. Here is an example with one parameter:Rewrite for example "/radio/{frequence}" -> "/radio?f={frequence}"
classOneParamRewrite :publicAsyncWebRewrite{protected: String _urlPrefix;int _paramIndex; String _paramsBackup;public:OneParamRewrite(constchar* from,constchar* to) : AsyncWebRewrite(from, to) { _paramIndex = _from.indexOf('{');if ( _paramIndex >=0 && _from.endsWith("}")) { _urlPrefix = _from.substring(0, _paramIndex);int index = _params.indexOf('{');if (index >=0) { _params = _params.substring(0, index); } }else { _urlPrefix = _from; } _paramsBackup = _params; }boolmatch(AsyncWebServerRequest *request)override {if (request->url().startsWith(_urlPrefix)) {if (_paramIndex >=0) { _params = _paramsBackup + request->url().substring(_paramIndex); }else { _params = _paramsBackup; }returntrue; }else {returnfalse; } }};
Usage:
server.addRewrite(new OneParamRewrite("/radio/{frequence}","/radio?f={frequence}") );
Filters can be set toRewrite orHandler in order to control when to apply the rewrite and consider the handler.A filter is a callback function that evaluates the request and return a booleantrue to include the itemorfalse to exclude it.
Some responses are implemented, but you should not use them, because they do not conform to HTTP.The following example will lead to unclean close of the connection and more time wastedthan providing the length of the content
//This is used as fallback for chunked responses to HTTP/1.0 Clientsrequest->send("text/plain",0, [](uint8_t *buffer,size_t maxLen,size_t index) -> size_t {//Write up to "maxLen" bytes into "buffer" and return the amount written.//You will be asked for more data until 0 is returned//Keep in mind that you can not delay or yield waiting for more data!return mySource.read(buffer, maxLen);});
The server includes a web socket plugin which lets you define different WebSocket locations to connect towithout starting another listening service or using different port
voidonEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type,void * arg,uint8_t *data,size_t len){if (type == WS_EVT_CONNECT) {//client connected Serial.printf("ws[%s][%u] connect\n", server->url(), client->id()); client->printf("Hello Client %u :)", client->id()); client->ping(); }elseif (type == WS_EVT_DISCONNECT) {//client disconnected Serial.printf("ws[%s][%u] disconnect: %u\n", server->url(), client->id()); }elseif (type == WS_EVT_ERROR) {//error was received from the other end Serial.printf("ws[%s][%u] error(%u): %s\n", server->url(), client->id(), *((uint16_t*)arg), (char*)data); }elseif (type == WS_EVT_PONG) {//pong message was received (in response to a ping request maybe) Serial.printf("ws[%s][%u] pong[%u]: %s\n", server->url(), client->id(), len, (len)?(char*)data:""); }elseif (type == WS_EVT_DATA) {//data packet AwsFrameInfo * info = (AwsFrameInfo*)arg;if (info->final && info->index ==0 && info->len == len) {//the whole message is in a single frame and we got all of it's data Serial.printf("ws[%s][%u] %s-message[%llu]:", server->url(), client->id(), (info->opcode == WS_TEXT)?"text":"binary", info->len);if (info->opcode == WS_TEXT) { data[len] =0; Serial.printf("%s\n", (char*)data); }else {for (size_t i=0; i < info->len; i++) { Serial.printf("%02x", data[i]); } Serial.printf("\n"); }if (info->opcode == WS_TEXT) client->text("I got your text message");else client->binary("I got your binary message"); }else {//message is comprised of multiple frames or the frame is split into multiple packetsif (info->index ==0) {if (info->num ==0) Serial.printf("ws[%s][%u] %s-message start\n", server->url(), client->id(), (info->message_opcode == WS_TEXT)?"text":"binary"); Serial.printf("ws[%s][%u] frame[%u] start[%llu]\n", server->url(), client->id(), info->num, info->len); } Serial.printf("ws[%s][%u] frame[%u] %s[%llu - %llu]:", server->url(), client->id(), info->num, (info->message_opcode == WS_TEXT)?"text":"binary", info->index, info->index + len);if (info->message_opcode == WS_TEXT) { data[len] =0; Serial.printf("%s\n", (char*)data); }else {for (size_t i=0; i < len; i++){ Serial.printf("%02x", data[i]); } Serial.printf("\n"); }if ((info->index + len) == info->len) { Serial.printf("ws[%s][%u] frame[%u] end[%llu]\n", server->url(), client->id(), info->num, info->len);if (info->final) { Serial.printf("ws[%s][%u] %s-message end\n", server->url(), client->id(), (info->message_opcode == WS_TEXT)?"text":"binary");if (info->message_opcode == WS_TEXT) client->text("I got your text message");else client->binary("I got your binary message"); } } } }}
//Server methodsAsyncWebSocketws("/ws");//printf to a clientws.printf((uint32_t)client_id, arguments...);//printf to all clientsws.printfAll(arguments...);//send text to a clientws.text((uint32_t)client_id, (char*)text);ws.text((uint32_t)client_id, (uint8_t*)text, (size_t)len);//send text to all clientsws.textAll((char*)text);ws.textAll((uint8_t*)text, (size_t)len);//send binary to a clientws.binary((uint32_t)client_id, (char*)binary);ws.binary((uint32_t)client_id, (uint8_t*)binary, (size_t)len);ws.binary((uint32_t)client_id, flash_binary,4);//send binary to all clientsws.binaryAll((char*)binary);ws.binaryAll((uint8_t*)binary, (size_t)len);//HTTP Authenticate before switch to Websocket protocolws.setAuthentication("user","pass");//client methodsAsyncWebSocketClient * client;//printfclient->printf(arguments...);//send textclient->text((char*)text);client->text((uint8_t*)text, (size_t)len);//send binaryclient->binary((char*)binary);client->binary((uint8_t*)binary, (size_t)len);
When sending a web socket message using the above methods a buffer is created. Under certain circumstances you might want to manipulate or populate this buffer directly from your application, for example to prevent unnecessary duplications of the data. This example below shows how to create a buffer and print data to it from an ArduinoJson object then send it.
voidsendDataWs(AsyncWebSocketClient * client){ DynamicJsonBuffer jsonBuffer; JsonObject& root = jsonBuffer.createObject(); root["a"] ="abc"; root["b"] ="abcd"; root["c"] ="abcde"; root["d"] ="abcdef"; root["e"] ="abcdefg";size_t len = root.measureLength(); AsyncWebSocketMessageBuffer * buffer = ws.makeBuffer(len);// creates a buffer (len + 1) for you.if (buffer) { root.printTo((char *)buffer->get(), len +1);if (client) { client->text(buffer); }else { ws.textAll(buffer); } }}
Browsers sometimes do not correctly close the websocket connection, even when theclose() function is called in javascript. This will eventually exhaust the web server's resources and will cause the server to crash. Periodically calling thecleanClients() function from the mainloop() function limits the number of clients by closing the oldest client when the maximum number of clients has been exceeded. This can called be every cycle, however, if you wish to use less power, then calling as infrequently as once per second is sufficient.
voidloop(){ ws.cleanupClients();}
The server includesEventSource (Server-Sent Events) plugin which can be used to send short text events to the browser.Difference betweenEventSource andWebSockets is thatEventSource is single direction, text-only protocol.
AsyncWebServerserver(80);AsyncEventSourceevents("/events");voidsetup(){// setup ...... events.onConnect([](AsyncEventSourceClient *client) {if (client->lastId()) { Serial.printf("Client reconnected! Last message ID that it got is: %u\n", client->lastId()); }//send event with message "hello!", id current millis// and set reconnect delay to 1 second client->send("hello!",NULL,millis(),1000); });//HTTP Basic authentication events.setAuthentication("user","pass"); server.addHandler(&events);// setup ......}voidloop(){if (eventTriggered) {// your logic here//send event "myevent" events.send("my event content","myevent",millis()); }}
if(!!window.EventSource){varsource=newEventSource('/events');source.addEventListener('open',function(e){console.log("Events Connected");},false);source.addEventListener('error',function(e){if(e.target.readyState!=EventSource.OPEN){console.log("Events Disconnected");}},false);source.addEventListener('message',function(e){console.log("message",e.data);},false);source.addEventListener('myevent',function(e){console.log("myevent",e.data);},false);}
Server goes through handlers in same order as they were added. You can't simple add handler with same path to override them.To remove handler:
// save callback for particular URL pathauto handler = server.on("/some/path", [](AsyncWebServerRequest *request){//do something useful});// when you don't need handler anymore remove itserver.removeHandler(&handler);// same with rewritesserver.removeRewrite(&someRewrite);server.onNotFound([](AsyncWebServerRequest *request){ request->send(404);});// remove server.onNotFound handlerserver.onNotFound(NULL);// remove all rewrites, handlers and onNotFound/onFileUpload/onRequestBody callbacksserver.reset();
#if !( defined(ESP32) ) #error This code is designed for (ESP32_S2/3, ESP32_C3 + LwIP ENC28J60) to run on ESP32 platform! Please check your Tools->Board setting.#endif#include<Arduino.h>#define_ASYNC_WEBSERVER_LOGLEVEL_4// Enter a MAC address and IP address for your controller below.#defineNUMBER_OF_MAC20byte mac[][NUMBER_OF_MAC] ={ {0xDE,0xAD,0xBE,0xEF,0xFE,0x01 }, {0xDE,0xAD,0xBE,0xEF,0xBE,0x02 }, {0xDE,0xAD,0xBE,0xEF,0xFE,0x03 }, {0xDE,0xAD,0xBE,0xEF,0xBE,0x04 }, {0xDE,0xAD,0xBE,0xEF,0xFE,0x05 }, {0xDE,0xAD,0xBE,0xEF,0xBE,0x06 }, {0xDE,0xAD,0xBE,0xEF,0xFE,0x07 }, {0xDE,0xAD,0xBE,0xEF,0xBE,0x08 }, {0xDE,0xAD,0xBE,0xEF,0xFE,0x09 }, {0xDE,0xAD,0xBE,0xEF,0xBE,0x0A }, {0xDE,0xAD,0xBE,0xEF,0xFE,0x0B }, {0xDE,0xAD,0xBE,0xEF,0xBE,0x0C }, {0xDE,0xAD,0xBE,0xEF,0xFE,0x0D }, {0xDE,0xAD,0xBE,0xEF,0xBE,0x0E }, {0xDE,0xAD,0xBE,0xEF,0xFE,0x0F }, {0xDE,0xAD,0xBE,0xEF,0xBE,0x10 }, {0xDE,0xAD,0xBE,0xEF,0xFE,0x11 }, {0xDE,0xAD,0xBE,0xEF,0xBE,0x12 }, {0xDE,0xAD,0xBE,0xEF,0xFE,0x13 }, {0xDE,0xAD,0xBE,0xEF,0xBE,0x14 },};// Select the IP address according to your local networkIPAddressmyIP(192,168,2,232);IPAddressmyGW(192,168,2,1);IPAddressmySN(255,255,255,0);// Google DNS Server IPIPAddressmyDNS(8,8,8,8);//////////////////////////////////////////////////////////// For ENC28J60 & ESP32-S3// Optional values to override default settings// Don't change unless you know what you're doing//#define ETH_SPI_HOST SPI3_HOST//#define SPI_CLOCK_MHZ 8// Must connect INT to GPIOxx or not working//#define INT_GPIO 4//#define MISO_GPIO 13//#define MOSI_GPIO 11//#define SCK_GPIO 12//#define CS_GPIO 10//////////////////////////////////////////////////////////#include<AsyncTCP.h>#include<AsyncWebServer_ESP32_SC_ENC.h>AsyncWebServerserver(80);voidhandleRoot(AsyncWebServerRequest *request){ request->send(200,"text/plain",String("Hello from Async_HelloServer on") + ARDUINO_BOARD );}voidhandleNotFound(AsyncWebServerRequest *request){ String message ="File Not Found\n\n"; message +="URI:";//message += server.uri(); message += request->url(); message +="\nMethod:"; message += (request->method() == HTTP_GET) ?"GET" :"POST"; message +="\nArguments:"; message += request->args(); message +="\n";for (uint8_t i =0; i < request->args(); i++) { message +="" + request->argName(i) +":" + request->arg(i) +"\n"; } request->send(404,"text/plain", message);}voidsetup(){ Serial.begin(115200);while (!Serial &&millis() <5000);delay(500); Serial.print(F("\nStart Async_HelloServer on")); Serial.print(ARDUINO_BOARD); Serial.print(F(" with")); Serial.println(SHIELD_TYPE); Serial.println(ASYNC_WEBSERVER_ESP32_SC_ENC_VERSION);AWS_LOGWARN(F("Default SPI pinout:"));AWS_LOGWARN1(F("SPI Host:"), ETH_SPI_HOST);AWS_LOGWARN1(F("MOSI:"), MOSI_GPIO);AWS_LOGWARN1(F("MISO:"), MISO_GPIO);AWS_LOGWARN1(F("SCK:"), SCK_GPIO);AWS_LOGWARN1(F("CS:"), CS_GPIO);AWS_LOGWARN1(F("INT:"), INT_GPIO);AWS_LOGWARN1(F("SPI Clock (MHz):"), SPI_CLOCK_MHZ);AWS_LOGWARN(F("========================="));///////////////////////////////////// To be called before ETH.begin()ESP32_ENC_onEvent();// start the ethernet connection and the server:// Use DHCP dynamic IP and random macuint16_t index =millis() % NUMBER_OF_MAC;//bool begin(int MISO_GPIO, int MOSI_GPIO, int SCLK_GPIO, int CS_GPIO, int INT_GPIO, int SPI_CLOCK_MHZ,// int SPI_HOST, uint8_t *ENC28J60_Mac = ENC28J60_Default_Mac);//ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST ); ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST, mac[index] );// Static IP, leave without this line to get IP via DHCP//bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = 0, IPAddress dns2 = 0); ETH.config(myIP, myGW, mySN, myDNS);ESP32_ENC_waitForConnect();/////////////////////////////////// server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {handleRoot(request); }); server.on("/inline", [](AsyncWebServerRequest * request) { request->send(200,"text/plain","This works as well"); }); server.onNotFound(handleNotFound); server.begin(); Serial.print(F("HTTP EthernetWebServer is @ IP :")); Serial.println(ETH.localIP());}voidloop(){}
#include<Arduino.h>#include<AsyncWebServer_ESP32_SC_ENC.h>...voidhandleRequest(AsyncWebServerRequest *request){}classWebClass {public : AsyncWebServer classWebServer = AsyncWebServer(81);WebClass(){};voidclassRequest (AsyncWebServerRequest *request){}voidbegin() {// attach global request handler classWebServer.on("/example", HTTP_ANY, handleRequest);// attach class request handler classWebServer.on("/example", HTTP_ANY,std::bind(&WebClass::classRequest,this, std::placeholders::_1)); }};AsyncWebServerglobalWebServer(80);WebClass webClassInstance;voidsetup() {// attach global request handler globalWebServer.on("/example", HTTP_ANY, handleRequest);// attach class request handler globalWebServer.on("/example", HTTP_ANY,std::bind(&WebClass::classRequest, webClassInstance, std::placeholders::_1));}voidloop() {}
// Disable client connections if it was activatedif ( ws.enabled() ) ws.enable(false);// enable client connections if it was disabledif ( !ws.enabled() ) ws.enable(true);
In some cases, such as when working with CORS, or with some sort of custom authentication system,you might need to define a header that should get added to all responses (including static, websocket and EventSource).The DefaultHeaders singleton allows you to do this.
Example:
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin","*");webServer.begin();
NOTE: You will still need to respond to the OPTIONS method for CORS pre-flight in most cases. (unless you are only using GET)
This is one option:
webServer.onNotFound([](AsyncWebServerRequest *request){if (request->method() == HTTP_OPTIONS) { request->send(200); }else { request->send(404); }});With path variable you can create a custom regex rule for a specific parameter in a route.For example we want asensorId parameter in a route rule to match only a integer.
server.on("^\\/sensor\\/([0-9]+)$", HTTP_GET, [] (AsyncWebServerRequest *request) { String sensorId = request->pathArg(0);});
NOTE: All regex patterns starts with^ and ends with$
To enable thePath variable support, you have to define the buildflag-DASYNCWEBSERVER_REGEX.
For Arduino IDE create/updateplatform.local.txt:
Windows: C:\Users(username)\AppData\Local\Arduino15\packages\{espxxxx}\hardware\espxxxx\{version}\platform.local.txt
Linux: ~/.arduino15/packages/{espxxxx}/hardware/{espxxxx}/{version}/platform.local.txt
Add/Update the following line:
compiler.cpp.extra_flags=-DDASYNCWEBSERVER_REGEXFor platformio modifyplatformio.ini:
[env:myboard]build_flags = -DASYNCWEBSERVER_REGEX
NOTE: By enablingASYNCWEBSERVER_REGEX,<regex> will be included. This will add an 100k to your binary.
You can change theINT pin to another one. Default isGPIO4
// Must connect INT to GPIOxx or not working#defineINT_GPIO4
| ENC28J60 | <---> | ESP32_S3 |
|---|---|---|
| MOSI | <---> | GPIO11 |
| MISO | <---> | GPIO13 |
| SCK | <---> | GPIO12 |
| SS | <---> | GPIO10 |
| INT | <---> | GPIO4 |
| GND | <---> | GND |
| 3.3V | <---> | 3.3V |
| ENC28J60 | <---> | ESP32_S2 |
|---|---|---|
| MOSI | <---> | GPIO35 |
| MISO | <---> | GPIO37 |
| SCK | <---> | GPIO36 |
| SS | <---> | GPIO34 |
| INT | <---> | GPIO4 |
| RST | <---> | RST |
| GND | <---> | GND |
| 3.3V | <---> | 3.3V |
| ENC28J60 | <---> | ESP32_C3 |
|---|---|---|
| MOSI | <---> | GPIO6 |
| MISO | <---> | GPIO5 |
| SCK | <---> | GPIO4 |
| SS | <---> | GPIO7 |
| INT | <---> | GPIO10 |
| RST | <---> | RST |
| GND | <---> | GND |
| 3.3V | <---> | 3.3V |
- Async_AdvancedWebServer
- Async_AdvancedWebServer_MemoryIssues_SendArduinoString
- Async_AdvancedWebServer_MemoryIssues_Send_CString
- Async_AdvancedWebServer_SendChunked
- Async_HelloServer
- Async_HelloServer2
- Async_HttpBasicAuth
- AsyncMultiWebServer_ESP32_ENC
- Async_PostServer
- Async_RegexPatterns_ESP32_ENC
- AsyncSimpleServer_ESP32_ENC
- AsyncWebServer_SendChunked
- Async_WebSocketsServer
- MQTTClient_Auth
- MQTTClient_Basic
- MQTT_ThingStream
ExampleAsync_AdvancedWebServer
AsyncWebServer_ESP32_SC_ENC/examples/Async_AdvancedWebServer/Async_AdvancedWebServer.ino
Lines 41 to 272 in328368d
| #if !( defined(ESP32) ) | |
| #error This code is designed for (ESP32_S2/3, ESP32_C3 + LwIP ENC28J60) to run on ESP32 platform! Please check your Tools->Board setting. | |
| #endif | |
| #include<Arduino.h> | |
| #define_ASYNC_WEBSERVER_LOGLEVEL_4 | |
| // Enter a MAC address and IP address for your controller below. | |
| #defineNUMBER_OF_MAC20 | |
| byte mac[][NUMBER_OF_MAC] = | |
| { | |
| {0xDE,0xAD,0xBE,0xEF,0xFE,0x01 }, | |
| {0xDE,0xAD,0xBE,0xEF,0xBE,0x02 }, | |
| {0xDE,0xAD,0xBE,0xEF,0xFE,0x03 }, | |
| {0xDE,0xAD,0xBE,0xEF,0xBE,0x04 }, | |
| {0xDE,0xAD,0xBE,0xEF,0xFE,0x05 }, | |
| {0xDE,0xAD,0xBE,0xEF,0xBE,0x06 }, | |
| {0xDE,0xAD,0xBE,0xEF,0xFE,0x07 }, | |
| {0xDE,0xAD,0xBE,0xEF,0xBE,0x08 }, | |
| {0xDE,0xAD,0xBE,0xEF,0xFE,0x09 }, | |
| {0xDE,0xAD,0xBE,0xEF,0xBE,0x0A }, | |
| {0xDE,0xAD,0xBE,0xEF,0xFE,0x0B }, | |
| {0xDE,0xAD,0xBE,0xEF,0xBE,0x0C }, | |
| {0xDE,0xAD,0xBE,0xEF,0xFE,0x0D }, | |
| {0xDE,0xAD,0xBE,0xEF,0xBE,0x0E }, | |
| {0xDE,0xAD,0xBE,0xEF,0xFE,0x0F }, | |
| {0xDE,0xAD,0xBE,0xEF,0xBE,0x10 }, | |
| {0xDE,0xAD,0xBE,0xEF,0xFE,0x11 }, | |
| {0xDE,0xAD,0xBE,0xEF,0xBE,0x12 }, | |
| {0xDE,0xAD,0xBE,0xEF,0xFE,0x13 }, | |
| {0xDE,0xAD,0xBE,0xEF,0xBE,0x14 }, | |
| }; | |
| // Select the IP address according to your local network | |
| IPAddressmyIP(192,168,2,232); | |
| IPAddressmyGW(192,168,2,1); | |
| IPAddressmySN(255,255,255,0); | |
| // Google DNS Server IP | |
| IPAddressmyDNS(8,8,8,8); | |
| ////////////////////////////////////////////////////////// | |
| // For ENC28J60 & ESP32-S3 | |
| // Optional values to override default settings | |
| // Don't change unless you know what you're doing | |
| //#define ETH_SPI_HOST SPI3_HOST | |
| //#define SPI_CLOCK_MHZ 8 | |
| // Must connect INT to GPIOxx or not working | |
| //#define INT_GPIO 4 | |
| //#define MISO_GPIO 13 | |
| //#define MOSI_GPIO 11 | |
| //#define SCK_GPIO 12 | |
| //#define CS_GPIO 10 | |
| // For ESP32_C3 | |
| // Optional values to override default settings | |
| // Don't change unless you know what you're doing | |
| //#define ETH_SPI_HOST SPI2_HOST | |
| //#define SPI_CLOCK_MHZ 8 | |
| // Must connect INT to GPIOxx or not working | |
| //#define INT_GPIO 10 | |
| //#define MISO_GPIO 5 | |
| //#define MOSI_GPIO 6 | |
| //#define SCK_GPIO 4 | |
| //#define CS_GPIO 7 | |
| ////////////////////////////////////////////////////////// | |
| #include<AsyncTCP.h> | |
| #include<AsyncWebServer_ESP32_SC_ENC.h> | |
| AsyncWebServerserver(80); | |
| int reqCount =0;// number of requests received | |
| voidhandleRoot(AsyncWebServerRequest *request) | |
| { | |
| #defineBUFFER_SIZE400 | |
| char temp[BUFFER_SIZE]; | |
| int sec =millis() /1000; | |
| int min = sec /60; | |
| int hr = min /60; | |
| int day = hr /24; | |
| snprintf(temp, BUFFER_SIZE -1, | |
| "<html>\ | |
| <head>\ | |
| <meta http-equiv='refresh' content='5'/>\ | |
| <title>AsyncWebServer-%s</title>\ | |
| <style>\ | |
| body { background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }\ | |
| </style>\ | |
| </head>\ | |
| <body>\ | |
| <h2>AsyncWebServer_ESP32_SC_ENC!</h2>\ | |
| <h3>running on %s</h3>\ | |
| <p>Uptime: %d d %02d:%02d:%02d</p>\ | |
| <img src=\"/test.svg\" />\ | |
| </body>\ | |
| </html>", BOARD_NAME, BOARD_NAME, day, hr %24, min %60, sec %60); | |
| request->send(200,"text/html", temp); | |
| } | |
| voidhandleNotFound(AsyncWebServerRequest *request) | |
| { | |
| String message ="File Not Found\n\n"; | |
| message +="URI:"; | |
| message += request->url(); | |
| message +="\nMethod:"; | |
| message += (request->method() == HTTP_GET) ?"GET" :"POST"; | |
| message +="\nArguments:"; | |
| message += request->args(); | |
| message +="\n"; | |
| for (uint8_t i =0; i < request->args(); i++) | |
| { | |
| message +="" + request->argName(i) +":" + request->arg(i) +"\n"; | |
| } | |
| request->send(404,"text/plain", message); | |
| } | |
| voiddrawGraph(AsyncWebServerRequest *request) | |
| { | |
| String out; | |
| out.reserve(3000); | |
| char temp[70]; | |
| out +="<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"310\" height=\"150\">\n"; | |
| out +="<rect width=\"310\" height=\"150\" fill=\"rgb(250, 230, 210)\" stroke-width=\"2\" stroke=\"rgb(0, 0, 0)\" />\n"; | |
| out +="<g stroke=\"blue\">\n"; | |
| int y =rand() %130; | |
| for (int x =10; x <300; x +=10) | |
| { | |
| int y2 =rand() %130; | |
| sprintf(temp,"<line x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" stroke-width=\"2\" />\n", x,140 - y, x +10,140 - y2); | |
| out += temp; | |
| y = y2; | |
| } | |
| out +="</g>\n</svg>\n"; | |
| request->send(200,"image/svg+xml", out); | |
| } | |
| voidsetup() | |
| { | |
| Serial.begin(115200); | |
| while (!Serial &&millis() <5000); | |
| delay(500); | |
| Serial.print(F("\nStart Async_AdvancedWebServer on")); | |
| Serial.print(BOARD_NAME); | |
| Serial.print(F(" with")); | |
| Serial.println(SHIELD_TYPE); | |
| Serial.println(ASYNC_WEBSERVER_ESP32_SC_ENC_VERSION); | |
| AWS_LOGWARN(F("Default SPI pinout:")); | |
| AWS_LOGWARN1(F("SPI Host:"), ETH_SPI_HOST); | |
| AWS_LOGWARN1(F("MOSI:"), MOSI_GPIO); | |
| AWS_LOGWARN1(F("MISO:"), MISO_GPIO); | |
| AWS_LOGWARN1(F("SCK:"), SCK_GPIO); | |
| AWS_LOGWARN1(F("CS:"), CS_GPIO); | |
| AWS_LOGWARN1(F("INT:"), INT_GPIO); | |
| AWS_LOGWARN1(F("SPI Clock (MHz):"), SPI_CLOCK_MHZ); | |
| AWS_LOGWARN(F("=========================")); | |
| /////////////////////////////////// | |
| // To be called before ETH.begin() | |
| ESP32_ENC_onEvent(); | |
| // start the ethernet connection and the server: | |
| // Use DHCP dynamic IP and random mac | |
| uint16_t index =millis() % NUMBER_OF_MAC; | |
| //bool begin(int MISO_GPIO, int MOSI_GPIO, int SCLK_GPIO, int CS_GPIO, int INT_GPIO, int SPI_CLOCK_MHZ, | |
| // int SPI_HOST, uint8_t *ENC28J60_Mac = ENC28J60_Default_Mac); | |
| //ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST ); | |
| ETH.begin( MISO_GPIO, MOSI_GPIO, SCK_GPIO, CS_GPIO, INT_GPIO, SPI_CLOCK_MHZ, ETH_SPI_HOST, mac[index] ); | |
| // Static IP, leave without this line to get IP via DHCP | |
| //bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = 0, IPAddress dns2 = 0); | |
| //ETH.config(myIP, myGW, mySN, myDNS); | |
| ESP32_ENC_waitForConnect(); | |
| /////////////////////////////////// | |
| server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) | |
| { | |
| handleRoot(request); | |
| }); | |
| server.on("/test.svg", HTTP_GET, [](AsyncWebServerRequest * request) | |
| { | |
| drawGraph(request); | |
| }); | |
| server.on("/inline", [](AsyncWebServerRequest * request) | |
| { | |
| request->send(200,"text/plain","This works as well"); | |
| }); | |
| server.onNotFound(handleNotFound); | |
| server.begin(); | |
| Serial.print(F("HTTP EthernetWebServer is @ IP :")); | |
| Serial.println(ETH.localIP()); | |
| } | |
| voidloop() | |
| { | |
| } |
You can access the Async Advanced WebServer @ the server IP
Following are debug terminal output and screen shots when running exampleAsyncMultiWebServer_ESP32_ENC onESP32S3_DEV with ESP32_S3_ENC28J60, using ESP32 corev2.0.0+, to demonstrate the operation of 3 independent AsyncWebServers on 3 different ports and how to handle the complicated AsyncMultiWebServers.
Start AsyncMultiWebServer_ESP32_ENC on ESP32S3_DEV with ESP32_S3_ENC28J60AsyncWebServer_ESP32_SC_ENC v1.8.0for core v2.0.0+[AWS] Default SPI pinout:[AWS] SPI Host:1[AWS] MOSI:11[AWS] MISO:13[AWS] SCK:12[AWS] CS:10[AWS] INT:4[AWS] SPIClock (MHz): 8[AWS] =========================ETH StartedETH ConnectedETH MAC: DE:AD:BE:EF:BE:14, IPv4: 192.168.2.232FULL_DUPLEX, 10MbpsConnected to network. IP = 192.168.2.232Initialize multiServer OK, serverIndex = 0, port = 8080HTTP server started at ports 8080Initialize multiServer OK, serverIndex = 1, port = 8081HTTP server started at ports 8081Initialize multiServer OK, serverIndex = 2, port = 8082HTTP server started at ports 8082
You can access the Async Advanced WebServers @ the server IP and corresponding ports (8080, 8081 and 8082)
Following is the debug terminal and screen shot when running exampleAsync_AdvancedWebServer_MemoryIssues_Send_CString, onESP32S3_DEV with ESP32_S3_ENC28J60, to demonstrate the new and powerfulHEAP-saving feature
Start Async_AdvancedWebServer_MemoryIssues_Send_CString on ESP32S3_DEV with ESP32_S3_ENC28J60AsyncWebServer_ESP32_SC_ENC v1.8.0for core v2.0.0+[AWS] Default SPI pinout:[AWS] SPI Host:1[AWS] MOSI:11[AWS] MISO:13[AWS] SCK:12[AWS] CS:10[AWS] INT:4[AWS] SPIClock (MHz): 8[AWS] =========================ETH StartedETH ConnectedETH MAC: DE:AD:BE:EF:BE:14, IPv4: 192.168.2.232FULL_DUPLEX, 10MbpsHTTP EthernetWebServer is @ IP : 192.168.2.232HEAP DATA - Pre Create Arduino String Max heap: 359580 Free heap: 258572 Used heap: 101008.HEAP DATA - Pre Send Max heap: 359580 Free heap: 253504 Used heap: 106076HEAP DATA - Post Send Max heap: 359580 Free heap: 247044 Used heap: 112536.HEAP DATA - Post Send Max heap: 359580 Free heap: 245556 Used heap: 113992......HEAP DATA - Post Send Max heap: 359580 Free heap: 245556 Used heap: 114024.. .
While usingArduino String, the HEAP usage is very large
Start Async_AdvancedWebServer_MemoryIssues_SendArduinoString on ESP32S3_DEV with ESP32_S3_ENC28J60AsyncWebServer_ESP32_SC_ENC v1.8.0for core v2.0.0+[AWS] Default SPI pinout:[AWS] SPI Host:1[AWS] MOSI:11[AWS] MISO:13[AWS] SCK:12[AWS] CS:10[AWS] INT:4[AWS] SPIClock (MHz): 8[AWS] =========================ETH StartedETH ConnectedETH MAC: DE:AD:BE:EF:BE:14, IPv4: 192.168.2.232FULL_DUPLEX, 10MbpsHTTP EthernetWebServer is @ IP : 192.168.2.232HEAP DATA - Pre Create Arduino String Max heap: 359852 Free heap: 298856 Used heap: 60996....HEAP DATA - Pre Send Max heap: 359852 Free heap: 254224 Used heap: 105628HEAP DATA - Post Send Max heap: 359852 Free heap: 214792 Used heap: 144988.
You can access the Async Advanced WebServers at the displayed server IP, e.g.192.168.2.232
Following is debug terminal output when running exampleAsync_AdvancedWebServer_SendChunked onESP32S3_DEV with ESP32_S3_ENC28J60, using ESP32 corev2.0.0+, to demo how to usebeginChunkedResponse() to send largehtml in chunks
Start Async_AdvancedWebServer_SendChunked on ESP32S3_DEV with ESP32_S3_ENC28J60AsyncWebServer_ESP32_SC_ENC v1.8.0for core v2.0.0+[AWS] Default SPI pinout:[AWS] SPI Host:1[AWS] MOSI:11[AWS] MISO:13[AWS] SCK:12[AWS] CS:10[AWS] INT:4[AWS] SPIClock (MHz): 8[AWS] =========================ETH StartedETH ConnectedETH MAC: DE:AD:BE:EF:FE:01, IPv4: 192.168.2.95FULL_DUPLEX, 10MbpsAsyncWebServer is @ IP : 192.168.2.95.[AWS] Total length to send in chunks = 31259[AWS] Bytes sent in chunk = 5620[AWS] Bytes sent in chunk = 4300[AWS] Bytes sent in chunk = 4300[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 1428[AWS] Bytes sent in chunk = 1291[AWS] Bytes sent in chunk = 0.[AWS] Total length to send in chunks = 31279[AWS] Bytes sent in chunk = 5620[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 1428[AWS] Bytes sent in chunk = 1428[AWS] Bytes sent in chunk = 2755[AWS] Bytes sent in chunk = 0
You can access the Async Advanced WebServers @ the server IP
Following is debug terminal output when running exampleAsyncWebServer_SendChunked onESP32S3_DEV with ESP32_S3_ENC28J60, using ESP32 corev2.0.0+, to demo how to usebeginChunkedResponse() to send largehtml in chunks
Start AsyncWebServer_SendChunked on ESP32S3_DEV with ESP32_S3_ENC28J60AsyncWebServer_ESP32_SC_ENC v1.8.0for core v2.0.0+[AWS] Default SPI pinout:[AWS] SPI Host:1[AWS] MOSI:11[AWS] MISO:13[AWS] SCK:12[AWS] CS:10[AWS] INT:4[AWS] SPIClock (MHz): 8[AWS] =========================ETH StartedETH ConnectedETH MAC: DE:AD:BE:EF:FE:01, IPv4: 192.168.2.232FULL_DUPLEX, 10MbpsAsyncWebServer is @ IP : 192.168.2.232.[AWS] Total length to send in chunks = 46804[AWS] Bytes sent in chunk = 5624[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 1428[AWS] Bytes sent in chunk = 1428[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 1092[AWS] Bytes sent in chunk = 0[AWS] Total length to send in chunks = 46804[AWS] Bytes sent in chunk = 5624[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 1428[AWS] Bytes sent in chunk = 1428[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 1092[AWS] Bytes sent in chunk = 0
Following is debug terminal output when running exampleAsync_WebSocketsServer onESP32S3_DEV with LwIP ENC28J60, using ESP32 corev2.0.0+, to demo how to useAsync_WebSocketsServer feature
Starting Async_WebSocketsServer on ESP32S3_DEV with ESP32_S3_ENC28J60AsyncWebServer_ESP32_SC_ENC v1.8.0for core v2.0.0+[AWS] Default SPI pinout:[AWS] SPI Host:1[AWS] MOSI:11[AWS] MISO:13[AWS] SCK:12[AWS] CS:10[AWS] INT:4[AWS] SPIClock (MHz): 8[AWS] =========================ETH StartedETH ConnectedETH MAC: DE:AD:BE:EF:BE:08, IPv4: 192.168.2.88FULL_DUPLEX, 10Mbpsws[Server: /ws][ClientID: 1] WSClient connectedws[Server: /ws][ClientID: 1] WSClient disconnectedws[Server: /ws][ClientID: 2] WSClient connectedws[Server: /ws][ClientID: 3] WSClient connected
Following is debug terminal output when running exampleAsync_HTTPBasicAuth onESP32S3_DEV with LwIP ENC28J60, using ESP32 corev2.0.0+, to demo how to useAsync_Auth feature
Start Async_HTTPBasicAuth on ESP32S3_DEV with ESP32_S3_ENC28J60AsyncWebServer_ESP32_SC_ENC v1.8.0for core v2.0.0+[AWS] Default SPI pinout:[AWS] SPI Host:1[AWS] MOSI:11[AWS] MISO:13[AWS] SCK:12[AWS] CS:10[AWS] INT:4[AWS] SPIClock (MHz): 8[AWS] =========================ETH StartedETH ConnectedETH MAC: DE:AD:BE:EF:BE:08, IPv4: 192.168.2.88FULL_DUPLEX, 10MbpsAsync_HttpBasicAuth started @ IP : 192.168.2.88Open http://192.168.2.88/ in your browser to see it workingLogin using username = admin and password = esp32_enc28j60
Following is debug terminal output when running exampleAsync_AdvancedWebServer_SendChunked onESP32S2_DEV with ESP32_S2_ENC28J60, using ESP32 corev2.0.0+, to demo how to usebeginChunkedResponse() to send largehtml in chunks. Thebuilt-in MAC address is now used instead of user-defined one.
Start Async_AdvancedWebServer_SendChunked on ESP32S2_DEV with ESP32_S2_ENC28J60AsyncWebServer_ESP32_SC_ENC v1.8.0for core v2.0.0+[AWS] Default SPI pinout:[AWS] SPI Host:1[AWS] MOSI:35[AWS] MISO:37[AWS] SCK:36[AWS] CS:34[AWS] INT:4[AWS] SPIClock (MHz): 8[AWS] =========================ETH StartedETH ConnectedETH MAC: 7E:DF:A1:08:64:27, IPv4: 192.168.2.132FULL_DUPLEX, 10MbpsAsyncWebServer is @ IP : 192.168.2.132..[AWS] Total length to send in chunks = 31259[AWS] Bytes sent in chunk = 5620[AWS] Bytes sent in chunk = 4300[AWS] Bytes sent in chunk = 4300[AWS] Bytes sent in chunk = 4300[AWS] Bytes sent in chunk = 4300[AWS] Bytes sent in chunk = 4300[AWS] Bytes sent in chunk = 4139[AWS] Bytes sent in chunk = 0[AWS] Total length to send in chunks = 31279[AWS] Bytes sent in chunk = 5620[AWS] Bytes sent in chunk = 4300[AWS] Bytes sent in chunk = 4300[AWS] Bytes sent in chunk = 4300[AWS] Bytes sent in chunk = 4300[AWS] Bytes sent in chunk = 4300[AWS] Bytes sent in chunk = 4159[AWS] Bytes sent in chunk = 0
You can access the Async Advanced WebServers @ the server IP
Following is debug terminal output when running exampleAsync_AdvancedWebServer_SendChunked onESP32C3_DEV with ESP32_C3_ENC28J60, using ESP32 corev2.0.0+, to demo how to usebeginChunkedResponse() to send largehtml in chunks. Thebuilt-in MAC address is now used instead of user-defined one.
Start Async_AdvancedWebServer_SendChunked on ESP32C3_DEV with ESP32_C3_ENC28J60AsyncWebServer_ESP32_SC_ENC v1.8.0for core v2.0.0+[AWS] Default SPI pinout:[AWS] SPI Host:1[AWS] MOSI:6[AWS] MISO:5[AWS] SCK:4[AWS] CS:7[AWS] INT:10[AWS] SPIClock (MHz): 8[AWS] =========================[AWS] Using built-in mac_eth = 7C:DF:A1:DA:66:87ETH StartedETH ConnectedETH MAC: 7C:DF:A1:DA:66:87, IPv4: 192.168.2.136FULL_DUPLEX, 10MbpsAsyncWebServer is @ IP : 192.168.2.136.[AWS] Total length to send in chunks = 31259[AWS] Bytes sent in chunk = 5620[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 5736[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 5736[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 5575[AWS] Bytes sent in chunk = 0.[AWS] Total length to send in chunks = 31279[AWS] Bytes sent in chunk = 5620[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 5736[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 5736[AWS] Bytes sent in chunk = 2864[AWS] Bytes sent in chunk = 2731[AWS] Bytes sent in chunk = 0
You can access the Async Advanced WebServers @ the server IP
Debug is enabled by default on Serial. Debug Level from 0 to 4. To disable, change theETHERNET_WEBSERVER_LOGLEVEL to 0
// Use this to output debug msgs to Serial#defineDEBUG_ASYNC_WEBSERVER_PORT Serial// Use this to disable all output debug msgs// Debug Level from 0 to 4#define_ASYNC_WEBSERVER_LOGLEVEL_0
If you get compilation errors, more often than not, you may need to install a newer version of Arduino IDE, the ArduinoESP32 core or depending libraries.
Sometimes, the library will only work if you update theESP32 core to the latest version because I'm always using the latest cores /libraries.
Submit issues to:AsyncWebServer_ESP32_SC_ENC issues
- Fix bug. Add enhancement
- Add support to more Ethernet shields, such asW5x00, DP83848, TLK110, IP101, RTL8201, DM9051, KSZ8041, KSZ8081, etc.
- Add
LittleFSsupport to use with new cores
- Initial port to
ESP32_S3boards usingENC28J60Ethernet. - Add more examples.
- Add debugging features.
- Add
Table-of-ContentsandVersion String - Display compiler
#warningonly whenDEBUG_LEVELis 3+ - Fix
AsyncWebSocketbug - Support using
CStringto save heap to sendvery large data. Checkrequest->send(200, textPlainStr, jsonChartDataCharStr); - Without using String Class - to save heap #8 - Add examplesAsync_AdvancedWebServer_SendChunked andAsyncWebServer_SendChunked to demo how to use
beginChunkedResponse()to send largehtmlin chunks - Use
allman astyleand addutils - Add
Async_WebSocketsServer,Async_HttpBasicAuthandMQTTexamples - Add support toESP32S2-based boards using
LwIP ENC28J60 Ethernet - Add support toESP32S2-based boards using
LwIP ENC28J60 Ethernet
- Based on and modified fromHristo Gochkov's ESPAsyncWebServer. Many thanks toHristo Gochkov for greatESPAsyncWebServer Library
- Thanks totobozo to make the libraryESP32-ENC28J60 from which this library uses some ideas and codes
![]() ⭐️⭐️ Hristo Gochkov | ![]() tobozo |
If you want to contribute to this project:
- Report bugs and errors
- Ask for enhancements
- Create issues and pull requests
- Tell other people about this library
- The library is licensed underGPLv3
Copyright (c) 2016- Hristo Gochkov
Copyright (c) 2022- Khoi Hoang
About
Asynchronous HTTP and WebSocket Server Library for (ESP32_S2/S3/C3 + LwIP ENC28J60). Now supporting using CString to save heap to send very large data and with examples to demo how to use beginChunkedResponse() to send large html in chunks
Topics
Resources
License
Contributing
Uh oh!
There was an error while loading.Please reload this page.














