C++ object subscribe not working

Hi all,

I’m trying to subscribe to events using the example in the documentation but it doesn’t seem to fire. Works fine outside of a C++ object. Any thoughts?

Here’s a stripped down version of the code.

#include "application.h"

class Subscriber {
  public:
   Subscriber() {
      Particle.subscribe("presence", &Subscriber::handler, this);
    }
    void handler(const char *eventName, const char *data) {
      Serial.println(data);
      Particle.publish("presence_handler", "I can't handle this request yet");
    }
};

Subscriber mySubscriber;

void setup() {
    Serial.begin(9600);
    delay(10000); // Time to open putty
    Serial.println("Setup complete");
}

void loop() {
}

I believe the problem is the constructor of a global object is too early in startup to subscribe. I usually add a setup() method to my object, put the subscription there, and call the setup method of the object from setup().

1 Like

Thanks @rickkas7 that resolves the issue.

Any idea how to only register to MY_DEVICES when using an object?

The last “this” isn’t usually present and changing

Particle.subscribe("presence", &Subscriber::handler, this);

to

Particle.subscribe("presence", &Subscriber::handler, this, MY_DEVICES);

compiles but fails to execute.

Are you publishing as PRIVATE too?
MY_DEVICES requires PRIVATE events.

1 Like

Perfect! Thank’s @ScruffR

I was in my previous tests but to troubleshoot issues I made everything public. Didn’t realize MY_DEVICES and PRIVATE weren’t independent of each other.