0

Quick question... Can the ESP32 AsyncWebServer port be set/reset AFTER the server has been declared?

The server is declared after the global variables, but before any functions, with the line: AsyncWebServer server(PortNumber);

Usually, the port number is 80 (the default HTTP port). However, I have the need to use a different port and the port will be chosen by the user from a WiFi credentials page and then stored in NVS.

So, I need to retrieve the port number from the NVS before I execute the AsyncWebServer command, or be able to change the port number on the fly.

How can I achieve this?

Nugget
  • 63
  • 5

2 Answers2

0

Looking at the ESPAsyncWebserver declaration there doesn't seem to be a way to change or set the port after creating an instance of it. But isn't the solution to your problem as simple as creating the server later, after your configuration settings have been read? Something to this tune:

uint16_t port = config.read("server_port");
ESPAsyncWebserver* server = new ESPAsyncWebserver(port);
Tarmo
  • 3,728
  • 1
  • 8
  • 25
  • "But isn't the solution to your problem as simple as creating the server later, after your configuration settings have been read?" - Absolutely, but that is the problem. The values are stored in NVS and I retrieve them using the preferences library, which is read in setup(). The AsyncWebServer and port number are declared as a global variable, so I don't see how the NVS can be read first. I don't understand your code example of: "config.read" - is that what I am missing? By the way, I am writing the code using the Arduino IDE. – Nugget Feb 13 '23 at 11:01
  • I found an article online which claims to have solved this problem as follows: std::unique_ptr server; server.reset(new AsyncWebServer(new_port)); However, "std::unique_ptr server;" returns "invalid use of template name" when compiled. And "server.reset(new AsyncWebServer(new_port));" returns "no matching function for call to 'AsyncWebServer::reset(AsyncWebServer*)'". There has been no response from the original poster to clarify how they made this work. – Nugget Feb 13 '23 at 11:14
  • "The AsyncWebServer and port number are declared as a global variable" - this is the problem. Don't do that. You're free to create and initialize your objects whenever you want, so instead declaring an global object create a global pointer and allocate the object later when the time is right. – Tarmo Feb 13 '23 at 14:20
0

The answer to this is here: Answer

Nugget
  • 63
  • 5