Member function as handler not working?

I can’t seem to get this code to work for some reason: my handler never gets called:

project.ino

#include "application.h"
#include "InternetButton.h"

#include "Subscriber.h"
#include "NyanCatMelody.h"

InternetButton b = InternetButton();
Subscriber mySubscriber(b);

void setup() {
  b.begin();

  // ... THIS GETS CALLED ...
  b.allLedsOn(0, 0, 255);
  delay(1000);
  b.allLedsOff();
}

void loop() {
  // ... code to publish events based on button presses ...
}

subscription.h:

#ifndef SUBSCRIBER_H
#define SUBSCRIBER_H

class Subscriber {
public:
  Subscriber(InternetButton& button);
  void handler(const char *eventName, const char *data);

private:
  InternetButton& m_button;
  bool m_rainbowMode;
};

#endif

subscription.cpp:

#include "application.h"
#include "InternetButton.h"

#include "Subscriber.h"

Subscriber::Subscriber(InternetButton& button) : m_button(button) {
  Particle.subscribe("buddin/", &Subscriber::handler, this);
}

void Subscriber::handler(const char *eventName, const char *data) {
  // ... NEVER GETS CALLED :( ...
  // But the "buddin/" event this is subscribed to 
  // is firing (I can see it in the Console)
}

The order of execution of global constructor calls is not predictable so try putting your subscription call in a init() or begin() method.

2 Likes