MQTT pubsubclient: how to store received message for later use?

Hi there !

Got an issue with MQTT pubsubclient library....

I need to receive a message: so I setup this "callback" function and subscribe to the topic I want. This is working fine!

Now....all example I found just do a "serial.print" of the received topic/payload inside the callback function... :confused:

It's not what I wish....I would like to recover the payload inside the main program for later processing. (infact I want to use this mqtt message as configuration parameter inside my software)

I tried the following:

char* received_topic;
byte* received_payload;
unsigned int received_length;
bool received_msg = false;
/* *********************************** MQTT ************************* */
void callback(char* topic, byte* payload, unsigned int length) {
    received_topic = topic;
    received_payload = payload;
    received_length = length;
    received_msg = true;
    // handle message arrived
}

maybe I missed something stupid, but I was expecting the received_* variable to be global so I can read then in main program as soon as I detect received_msg = true.

what did I missed?

reception is working: I can detect it and output the payload with serial.print(...) inside my callback. but received_payload, receive_topic and received_lenght seems empty if I move my serial.print(...) inside main program.

Assigning the pointers won’t work because the internal buffer is used for both sending and receiving. So you need to copy the content instead.

To avoid using dynamic memory, instead of making “received_topic” and “received_payload” a pointer, you need to make them array instead (the array must have the largest possible size).

Now, “topic” is null-terminated so you can use strcpy() to copy it.
“payload” can be copied by using memcpy() as “length” is used as the parameter for size.

Ahh, well seen :-)

did you mean something like this ? It seems to works (tested only nominal situation, not pushed to limits)

char received_topic[128];
byte received_payload[128];
unsigned int received_length;
bool received_msg = false;
/* *********************************** MQTT ************************* */
void callback(char* topic, byte* payload, unsigned int length) {
  strcpy(received_topic, topic);
  memcpy(received_payload, payload, length);
  received_msg = true;
  received_length = length;
}

I'm not sure about the "128", library refer to a packet size limit to 128byte, but I'm not sure if 'packet' refer to payload or full packet (payload, topic etc...all included).