Hi everyone.
I'm new to IOT and I'm having a very simple question.
In my code I have subscribe "appClient" topic and I publish my messages under "Esp8266Client" topic.
I have written a callback code which publish whatever it gets in its payload.
why received messages and published messages are different from each other?
This is my callback function:
void callback(char* topic, byte* payload, unsigned int length)
{
String Sdata;
for (int i = 1; i <= length; i++)
{
Sdata += "-" + String(payload[i], DEC);
}
String topic_R = "ESP8266Client";
client.publish(topic_R.c_str() , Sdata.c_str());
}
here is the result show in broker:
appClient 1
ESP8266Client -105
appClient 12
ESP8266Client -50-108
appClient 123
ESP8266Client -50-51-105
appClient 1234
ESP8266Client -50-51-52-101
appClient 1111
ESP8266Client -49-49-49-101
Why are you using Strings ?
Try this
void callback(char* topic, byte* payload, unsigned int length)
{
char buffer[30;
memcpy(buffer, payload); //copy the payload to the buffer
buffer[length] = '\0'; //terminate the string (NOT a String !
char * outTopic = "steamer/ESP8266Client";
client.publish(outTopic , buffer);
}
thank you very much UKHeliBob
it worked with a little correction.
Please post the working version for future readers of the thread
I see that I missed the closing ] in the declaration of buffer
for (int i = 1; i <= length; i++)
If length is the number of bytes in payload, then i will miss the first byte in payload AND access past the end of payload.
thank you all.
this is the working version of this code:
void callback(char* topic, byte* payload, unsigned int length)
{
char buffer1[30];
memcpy(buffer1, payload, length); //copy the payload to the buffer
buffer1[length] = '\0'; //terminate the string (NOT a String !)
char * outTopic = "ESP8266Client";
client.publish(outTopic , buffer1);
}