Search code examples
c++arduinoesp32

Refactoring an Arduino sketch into a C++ class


I am trying to convert this Arduino sketch into a C++ class. The header file, "WifiManager.h" is defined as

class WifiManager
{
  public:
    // TODO: Use a singleton pattern https://stackoverflow.com/a/1008289
    WifiManager();
    void run();
    bool isConnected();
    char *getIpAddress();
    virtual ~WifiManager();

  private:

};

and is implemented in a WifiManager.cpp, whose full code implementation is accessible here. In nutshell, the .cppfile implements the .h's API but also handles the WIFI callback functions. As for testing, I am assuming that the callback functions will be called automatically if I run the program as follows:

#include <Arduino.h>
#include "WifiManager.h"
WifiManager *wifi;
void setup()
{
    Serial.begin(115200);
    wifi = new WifiManager();
}

void loop()
{
    delay(1000);
}

This, however, does not work. It seems that all WIFI related callbacks do not run at all. However, I do not know how to fix this as I a C++ beginner. Thus, I would like to know what is the best way to fix this.


Solution

  • I think you need to call WiFi.begin. You called it in onWhenWifiOnDisconnects(), but even if a disconnect event is fired, you registered the event handler in the constructor only after the call to WiFi.disconnect(true).

    So to clear this up, what your code does right now:

    1. In the constructor you call WiFi.disconnect(true)

    2. Disconnect event is fired, but nobody handles it

    3. You register your event handler and then nothing happens

    You should call WiFi.begin in the constructor or in a separate member function that you explicitly call and not (only) in onWhenWifiOnDisconnects().