Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to set the callback from a c++ class? #81

Closed
suculent opened this issue Jul 3, 2017 · 1 comment
Closed

How to set the callback from a c++ class? #81

suculent opened this issue Jul 3, 2017 · 1 comment

Comments

@suculent
Copy link

suculent commented Jul 3, 2017

First of all, sorry that I'm asking here... it seems to me like a generic C/C++ question but it's probably too generic to be searched on Google. I was grown somewhere between Z80 assembler and high-level languages like Objective-C, Swift and JavaScript, so the C-side is temporarily unfamiliar to me.

In your header, you declare:

//! Set the callback function
PubSubClient& set_callback(callback_t cb) { _callback = cb; return *this; }

In my .h:

class MyClass {
 public: 
    PubSubClient *mqtt_client;
    // I had to inline the callback here because otherwise linker has issues with undefined attribute types
     inline void mqtt_callback(const MQTT::Publish& pub) {
      Serial.println("*TH: MQTT callback...");
      if (pub.has_stream()) {
        Serial.print(pub.topic());
        Serial.print(" => ");
        if (pub.has_stream()) {
          uint8_t buf[MQTT_BUFFER_SIZE];
          int read;
          while (read = pub.payload_stream()->read(buf, MQTT_BUFFER_SIZE)) {
            // Do something with data in buffer
            Serial.write(buf, read);
          }
          pub.payload_stream()->stop();
          Serial.println("stop.");
        } else {
          Serial.println(pub.payload_string());
        }
      }
    }
}

In my .cpp:

mqtt_client = new PubSubClient(*wifi_client, mqtt_url.c_str());
if (mqtt_client->connect(MQTT::Connect(id)
                .set_clean_session()
                .set_will(willTopic, disconnected_response.c_str())
                .set_auth(user, pass)
                .set_keepalive(30)
              )) {
    // The callback function does not get called. Why?
    mqtt_client->set_callback([this](const MQTT::Publish &pub) {
      Serial.print("*MQTT Callback called...");
      this->mqtt_callback(pub);
    });
}

The callback function does not get called. Why?

@suculent
Copy link
Author

After couple weeks I've noticed that the PubSubClient::loop() function is not called in the upper code... which was the reason why the callback didn't happen and no messages were received.

Everything started working normally after adding the forgotten call.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant