Search code examples
esp32

Explain the routing code calling signature for ESPAsyncWebServer


Here is one of the routes in my ESP32 app that is for ESPAsyncWebServer to interpret:

// Route to delete the data log file
  server.on("/deletedata", HTTP_GET, [](AsyncWebServerRequest *request) {
    request->send(SPIFFS, "/index.html", "text/html", false, processor);
    DeleteFile(data_logfile);
  });

Having had examples to inform me, my initial set of routes is working fine. But I am expanding with new pages and want to more fully understand what the method params are actually doing. For example, what is the full signature of request->send()? In particular, the second parameter ("/index.html") ? This is the origin file of the request as it turns out, but I don't understand why that is needed. Also, what is "processor"? The other params I understand pretty well. "DeleteFile(data_logfile);" calls a method in the ESP32 code that carries out the action indicated by the HTTP /deletedata request.

ESPAsyncWebServer works great but isn't that well-documented (that I can find).


Solution

  • request-send() accepts a file system type, a route to a page in the file system, a content type for the handled page, a flag indicating that the client should download that file or not and a processor function which will be called as the page gets send out to the client.

    The processor function will be called as soon as the send() function finds a pair of two signal characters which is default to "%" in the asyncWebserver's case.

    It is used for building a dynamic webpage with templates. If you have let's say an index.html file with templates, you can replace your template parameters with values using the Processor function.

    Here is an example:

    Index.html Page:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Example page</title>
    </head>
    <body>
        <h1> %variableFromESP% </h1>
    </body>
    </html>
    

    ESP endpoint:

    /*
     This processor function will be called if the server finds
     something between two controll characters.
     In this case: %variableFromESP%.
     This processor function is used to replace this character
     with whatever value.
    */
    String processor( const String& var ){
       if( var == "variableFromESP" ){
           return "Hello World";
       }
       return "";
    }
    // Using LittleFs as a file system, a testPage.html route,text/html type
    // do not download this file, and passing the processor function.
    server.on("/testPage", HTTP_GET, [](AsyncWebServerRequest *request) {
      request->send(LittleFs, "/testPage.html", "text/html", false, processor);
    });