From 5ffa607322db725ad3d9ffd4940bf7f2dac4851c Mon Sep 17 00:00:00 2001 From: Nicholas O'Leary Date: Sun, 4 Nov 2012 14:07:56 +0000 Subject: [PATCH] Copy payload before republishing in mqtt_publish_in_callback example --- .../mqtt_publish_in_callback.ino | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/PubSubClient/examples/mqtt_publish_in_callback/mqtt_publish_in_callback.ino b/PubSubClient/examples/mqtt_publish_in_callback/mqtt_publish_in_callback.ino index 278149a..ece5c2e 100644 --- a/PubSubClient/examples/mqtt_publish_in_callback/mqtt_publish_in_callback.ino +++ b/PubSubClient/examples/mqtt_publish_in_callback/mqtt_publish_in_callback.ino @@ -31,7 +31,17 @@ PubSubClient client(server, 1883, callback, ethClient); // Callback function void callback(char* topic, byte* payload, unsigned int length) { - client.publish("outTopic", payload, length); + // In order to republish this payload, a copy must be made + // as the orignal payload buffer will be overwritten whilst + // constructing the PUBLISH packet. + + // Allocate the correct amount of memory for the payload copy + byte* p = (byte*)malloc(length); + // Copy the payload to the new buffer + memcpy(p,payload,length); + client.publish("outTopic", p, length); + // Free the memory + free(p); } void setup()