Is it possible to subscribe to a System event using a class member function for the callback?
I have tried both these calls and they both will not compile
This style works for registering a Software timer, but not for System.on
System.on(cloud_status, &NetworkControl::CloudStatusEvent, *this);
this one also does not compile
auto CloudHandler = std::bind(&NetworkControl::CloudStatusEvent, this, std::placeholders::_1, std::placeholders::_2);
System.on(cloud_status, CloudHandler);
where the class function is defined as
void NetworkControl::CloudStatusEvent(system_event_t event, int data)
{
}
Hi guys,
Any news regarding this? Is it possible to use non-static class method as a callback for system events on 0.6.4 firmware?
–
/G
It’s not currently possible to pass a class member to System.on, as none of the overloads allow for it.
Since system events tend to be global, the easiest workaround is to create a static method that’s a wrapper, and store the instance of the class in a static member, and then you can call your non-static class member.
#include "Particle.h"
class MyClass {
public:
MyClass();
virtual ~MyClass();
void setup();
void buttonClick(system_event_t event, int param);
private:
static void buttonClickStatic(system_event_t event, int param);
int counter = 0;
static MyClass *instance;
};
MyClass::MyClass() {
instance = this;
}
MyClass::~MyClass() {
}
void MyClass::setup() {
System.on(button_click, buttonClickStatic);
}
void MyClass::buttonClick(system_event_t event, int param) {
int times = system_button_clicks(param);
Serial.printlnf("eventH=%08lx eventL=%08lx times=%d counter=%d", (uint32_t)(event >> 32), (uint32_t) event, times, ++counter);
}
// static
void MyClass::buttonClickStatic(system_event_t event, int param) {
instance->buttonClick(event, param);
}
MyClass *MyClass::instance;
MyClass myClass;
void setup() {
Serial.begin();
myClass.setup();
}
void loop() {
}
4 Likes