Search code examples
arduinowebserveresp8266global

How to instantiate ESP AsyncWebServer inside a class? (arduino esp8266)


Problem: ESP8266 AsyncWebServer only works when I instantiate it as a global but not when I instantiate it inside a class.

Here's the two complete sketechs that both generate an error

Method 1: trying this without a constuctor to init:

#include <ESPAsyncWebServer.h>

//  AsyncWebServer server(80);  // works when I instantiate it here

class foo {
  AsyncWebServer server(80);  // fails if instead I instantiate it here
  int dummy{0};
};

void setup() {}
void loop() {}

Error Message 1

sketch_jun06d:6:25: error: expected identifier before numeric constant
   AsyncWebServer server(80);  // this does not work
                         ^
sketch_jun06d:6:25: error: expected ',' or '...' before numeric constant

Method 2 initializing in the constructor

class foo{
  public:

 AsyncWebServer server;
 foo() {
   server(80);
 };
};

Error Message 2

In constructor 'foo::foo()':
sketch_jun06d:18:8: error: no matching function for call to 'AsyncWebServer::AsyncWebServer()'
  foo() {
        ^
Arduino/sketch_jun06d/sketch_jun06d.ino:18:8: note: candidates are:
In file included from sketch_jun06d.ino:1:0:
libraries/ESPAsyncWebServer-master/src/ESPAsyncWebServer.h:405:5: note: AsyncWebServer::AsyncWebServer(uint16_t)
     AsyncWebServer(uint16_t port);
     ^
libraries/ESPAsyncWebServer-master/src/ESPAsyncWebServer.h:405:5: note:   candidate expects 1 argument, 0 provided
libraries/ESPAsyncWebServer-master/src/ESPAsyncWebServer.h:397:7: note: AsyncWebServer::AsyncWebServer(const AsyncWebServer&)
 class AsyncWebServer {
       ^
libraries/ESPAsyncWebServer-master/src/ESPAsyncWebServer.h:397:7: note:   candidate expects 1 argument, 0 provided
sketch_jun06d:19:13: error: no match for call to '(AsyncWebServer) (int)'
    server(80);
             ^

Analysis this is baffling me since the error message seems to say the calling signature is wrong. Yet it works outside the class identically. crazy?

Platform and target using Arduino.app 1.8.12 on a mac.

Arduino: 1.8.12 (Mac OS X), Board: "WeMos D1 R1, 80 MHz, Flash, Legacy (new can return nullptr), All SSL ciphers (most compatible), 4MB (FS:2MB OTA:~1019KB), v2 Lower Memory, Disabled, None, Only Sketch, 3000000"

Version: I can't find an explicit verison number in the ESPAsyncWebServer files but I see the unzupped code has october 2019 date on the files.


Solution

  • Use an initializer list on your constructor.

    This is uncompiled and untested but should at least get you moving in the right direction.

    class foo {
      AsyncWebServer server;  // fails if instead I instantiate it here
      int dummy;
    
      foo() : server(80), dummy(0){}
    };