Search code examples
c++11asynchronouswebserveresp32arduino-esp32

Passing processor-function in library for ESP AsyncWebServerRequest


I'm trying to include the ESPAsyncWebServer lib in an own C++ class/library. I'm struggling to pass the processor function when starting a server.

Same problem was discussed here: Calling member function by pointer Passing a function as a parameter within a class ...but I can't find the solution.

My code looks like this:

code.ino:

#include "SoftwareUpdater.h"

AsyncWebServer server(80);
SoftwareUpdater Updater(&server);

void setup() {
  Serial.begin(115200);
  Updater.initialise();
}

void loop() {
}

Softwareupdater.cpp:

#include "SoftwareUpdater.h"

SoftwareUpdater::SoftwareUpdater(AsyncWebServer *_server) {
  server = _server;
}

void SoftwareUpdater::initialise() {
  server->on("/manager", HTTP_GET, [](AsyncWebServerRequest *request) {
    request->send(SPIFFS, "/index.htm", String(), false, [&](const String &var) -> String {
      return processor(var);
    });
  });
  server->begin();
};

String SoftwareUpdater::processor(const String &var) {
  if (var == "var_manager") {
    return "text";
  }
};

Softwareupdater.h:

#ifndef SoftwareUpdater_h
#define SoftwareUpdater_h

#include "FS.h"
#include "SPIFFS.h"
#include <ESPAsyncWebServer.h>

class SoftwareUpdater {
private:
  void _setupAsyncServer();

public:
  AsyncWebServer *server;
  String processor(const String &var);

  SoftwareUpdater(AsyncWebServer *server);
  void initialise();
};

#endif

The error is:

cannot call member function 'String SoftwareUpdater::processor(const String&)' without object exit status 1 Compilation error: 'this' was not captured for this lambda function

Picture: This is the error I get


Solution

  • You are trying to call the properties of an object in a lambda function, which does not know the object. So, you would have to pass the object, too.

    server->on("/manager", HTTP_GET, [this](AsyncWebServerRequest *request){
      request->send(SPIFFS, "/index.htm", String(), false, [this](const String &var) -> String {
        return this->processor(var);
      });
    });