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

Add support for using std::function callbacks instead of C-pointers #35

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/MqttClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,11 @@ MqttClient::~MqttClient()
}
}

#ifdef MQTT_CLIENT_STD_FUNCTION_CALLBACK
void MqttClient::onMessage(MessageCallback callback)
#else
void MqttClient::onMessage(void(*callback)(int))
#endif
{
_onMessage = callback;
}
Expand Down Expand Up @@ -557,7 +561,11 @@ void MqttClient::poll()
_rxState = MQTT_CLIENT_RX_STATE_READ_PUBLISH_PAYLOAD;

if (_onMessage) {
#ifdef MQTT_CLIENT_STD_FUNCTION_CALLBACK
_onMessage(this,_rxLength);
#else
_onMessage(_rxLength);
#endif

if (_rxLength == 0) {
_rxState = MQTT_CLIENT_RX_STATE_READ_TYPE;
Expand All @@ -580,7 +588,11 @@ void MqttClient::poll()
_rxState = MQTT_CLIENT_RX_STATE_READ_PUBLISH_PAYLOAD;

if (_onMessage) {
#ifdef MQTT_CLIENT_STD_FUNCTION_CALLBACK
_onMessage(this,_rxLength);
#else
_onMessage(_rxLength);
#endif
}

if (_rxLength == 0) {
Expand Down
19 changes: 16 additions & 3 deletions src/MqttClient.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,26 @@
#define MQTT_BAD_USER_NAME_OR_PASSWORD 4
#define MQTT_NOT_AUTHORIZED 5

// Make this definition in your application code to use std::functions for onMessage callbacks instead of C-pointers:
// #define MQTT_CLIENT_STD_FUNCTION_CALLBACK

#ifdef MQTT_CLIENT_STD_FUNCTION_CALLBACK
#include <functional>
#endif

class MqttClient : public Client {
public:
MqttClient(Client* client);
MqttClient(Client& client);
virtual ~MqttClient();


#ifdef MQTT_CLIENT_STD_FUNCTION_CALLBACK
typedef std::function<void(MqttClient *client, int messageSize)> MessageCallback;
void onMessage(MessageCallback callback);
#else
inline void setClient(Client& client) { _client = &client; }


void onMessage(void(*)(int));
#endif

int parseMessage();
String messageTopic() const;
Expand Down Expand Up @@ -133,7 +142,11 @@ class MqttClient : public Client {
private:
Client* _client;

#ifdef MQTT_CLIENT_STD_FUNCTION_CALLBACK
MessageCallback _onMessage;
#else
void (*_onMessage)(int);
#endif

String _id;
String _username;
Expand Down