I'm running a bit of code on an Arduino machine that uses C++. The setup (very roughly) is like below in the main function. The example is fairly contrived, and the code design doesn't really pass the smell check, but it's the best I can do.
There's a 3rd party WiFi library that I'm trying to add an "onDisconnect" hook to. When my TaskRunner class executes, I attach a function to this hook so that when the WiFi disconnects, my task runner is notified.
The challenge is I don't know the language well enough to assign an anonymous function that also keeps the "isWifiConnected in scope. I'm somewhat learning C++ on the fly so please feel free to change the title of the question as I might not even be asking the right one.
Note that I may not be looking for an anonymous function. I'm trying to update the isWifiConnected property when onDisconnect() is called.
#include <iostream>
using namespace std;
// A 3rd Party class
// https://github.com/Hieromon/AutoConnect/blob/master/src/AutoConnect.h
// https://github.com/Hieromon/AutoConnect/blob/master/src/AutoConnect.cpp
class AutoConnect {
public:
AutoConnect(){};
// I add this to the class as a hook to be called at about
// line 549 code block where AutoConnect calls disconnect code
void (*onDisconnect)();
};
void onDisconnect(){
cout << "Disconnecting!" << endl;
cout << "But how to make isWifiConnected false? I don't have access :/";
};
// My task runner
class TaskRunner {
public:
bool isWifiConnected;
AutoConnect *connector;
TaskRunner(AutoConnect & connector){
this->connector = & connector;
}
void execute(){
isWifiConnected = true;
// run some WiFi connection code ...
// assign the onDisconnect hook to be run when it disconnects
connector -> onDisconnect = onDisconnect;
// but how can I update "isWifiConnected" = false when the onDisconnect runs
// In JavaScript, I could do
/*
connector -> onDisconnect = function(){
// variable stays in scope due to closure.
isWifiConnected = false;
}
*/
}
};
int main() {
cout<<"Running ..." << endl;
// Instantiate my classes and inject WifiConnector into my task runner
AutoConnect connector;
TaskRunner runner = TaskRunner(connector);
// Simulate an event loop for effect
for(int i = 0; i < 10; i++){
if(i == 0) runner.execute();
// on some other condition, Wifi is disconnected
if(i == 9) connector.onDisconnect();
}
return 0;
}
Any ideas on how to update the TaskRunner's isWifiConnected variable? I've tried various pointer combinations but can't quite get it right.