knolleary / pubsubclient

A client library for the Arduino Ethernet Shield that provides support for MQTT.
http://pubsubclient.knolleary.net/
MIT License
3.82k stars 1.47k forks source link

Weird characters at the end of payload on callback #928

Closed dustin-auby closed 2 years ago

dustin-auby commented 2 years ago

Hi Guys,

I'm encountering a weird issue with my payloads. im getting extra characters in the payload. mostly a "e" or ".0" will be appended to the end of the payload. in the bellow example i send a air-con mode of "cool" to the topic. in my mqtt client it is received properly as well as home assistant but on my wemos D1 R2 it receives as "coole". any idea what could cause this all of a sudden ?.

i am using pubsubclient v 2.8 any assistance on this would be greatly apriciated

void callback(char* topic, byte* payload, unsigned int length) {

  Serial.print("Message:");
  Serial.println((char*)payload);
}
knolleary commented 2 years ago

You are ignoring the length parameter that tells you how long the payload is.

Instead, your code will print the bytes of payload until it hits a 0x00... so it's pure chance what extra chars youll get.

The quick fix is to do:

payload[length] = 0;

To ensure there is a 0 immediately after the valid bytes of the payload.

dustin-auby commented 2 years ago

Thanks for the quick reply, that has resolved the issue