2

I want my ESP8266-based device to create an accesspoint that allows the user to input their home ssid and password. There is a device object that holds most of the data defined elsewhere.

I'm trying to use the ESP8266WebServer library. It requires me to define parameterless callback functions. Where should I declare and define these callback functions so that they can access the server object? In all the example code, the server object is global. I'd want to avoid that, and I'd also like to avoid having a server object as a permanent Device class member.

How should I go about this? It is not allowed to define the callback functions inside Device::getWifiCredentials, and if I declare them outside then server isn't in scope.

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

// Function to create AccessPoint to get ssid and password
int Device::getWifiCredentials() {

    ESP8266WebServer server(80);
    server.begin();
    
    // define callbacks
    server.on("/", handleRoot); // initial page

    server.on("/ssid", handleCredentials); // catch response from initial page

    // wait for credentials to be delivered
    server.handleClient();

    while( WiFi.status() != WL_CONNECTED){
        Serial.print(".");
        delay(500);
    }

    return ACTION_SUCCESSFUL;

}

// **Where can these functions be defined to allow them to access the server object?**

void handleRoot() {
};

void handleCredentials() {

    String ssid;
    String pw;

    if( server.hasArg() ){
        ssid = server.arg("ssid");
        pw = server.arg("pw");
    }
};
2
  • 2
    "It is not allowed to define the callback functions inside Device::getWifiCredentials", it can be done with an anonymous function like server.on("/ssid", []() { }.
    – hcheung
    Feb 12 at 0:26
  • 1
    i would move ESP8266WebServer server(80); to the 4th line; outside any function. I think you might need to call on() before begin() as well, just once, like in setup(), at least that's how mine works.
    – dandavis
    Feb 12 at 12:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.