256dpi / arduino-mqtt

MQTT library for Arduino
MIT License
1.01k stars 232 forks source link

Make callbacks std::function #224

Closed gonzabrusco closed 3 years ago

gonzabrusco commented 3 years ago

Hello. I'm using your library inside my class and when I try to pass a method of my class (not a global function) to your onMessage() function to set it as a callback, the compiler fails. I think this is because the the callback format you propose is:

typedef void (*MQTTClientCallbackSimple)(String &topic, String &payload);

And this does not allow to bind the this pointer to the callback.

In this case, the callback setting should look like this:

mqttObject.onMessage(std::bind(&_DataSender::messageReceivedCallback, this, std::placeholders::_1, std::placeholders::_2));

Where mqttObject is an object inside the _DataSender class and messageReceivedCallback is a method inside _DataSender class.

I'm not really sure but I think this could be fixed if the prototype of the callback function gets changed to this:

typedef std::function<void(String &topic, String &payload)> MQTTClientCallbackSimple;

And include this in the MQTTClient.h :

#include <functional>

Thanks!! Gonzalo

256dpi commented 3 years ago

Will be added in #220.