arduino-libraries / ArduinoMqttClient

ArduinoMqttClient Library for Arduino
GNU Lesser General Public License v2.1
183 stars 72 forks source link

json string is "damaged" on transmitting #89

Open g6094199 opened 1 year ago

g6094199 commented 1 year ago

hi,

i try to send an json string to mqtt like so:

   const char topic[]      = "Hoechst/PHI-Log/data/json";

    .....

    mqttClient.beginMessage(topic);

    serializeJson(doc, mqttClient);
    mqttClient.endMessage();

and the received string is in the correct topic but like so:

null3�Hoechst/PHI-Log/data/json{"clock":"22/06/2023 13:41:40","number":"","sht85_humid":"51.34","sht85_temp":"29.64","ENV_temp":"32.53","ENV_humid":"53.32","ENV_pressure":"99.91","ENV_illuminance":"81.29","sgp40_sraw":"32571","sgp40_voc":"0","scd30_humid":"43.94","scd30_temp":"32.79","scd3

someone knows whats going wrong? or is it a bug?

jwende commented 4 months ago

I did something similar today and it worked for me by providing a seperate buffer ...

StaticJsonDocument<200> doc;
Serial.print("Temperature = ");
Serial.print(bme.readTemperature());
Serial.println(" *C");
doc["Temperature"] = bme.readTemperature();

Serial.print("Pressure = ");
Serial.print(bme.readPressure() / 100.0F);
Serial.println(" hPa");
doc["Pressure"] = bme.readPressure() / 100.0F;

Serial.print("Humidity = ");
Serial.print(bme.readHumidity());
Serial.println(" %");
doc["Humidity"] = bme.readHumidity();

mqttClient.beginMessage(topic+"/json");
char output[128];
serializeJson(doc, output);
mqttClient.print(output);
mqttClient.endMessage();

Hope this helps ...

domfie commented 1 month ago

Problem is here that the internal buffer is only 128 or 256 characters wide. You need to supply the length of the message to send so the lib will switch to streaming magic. I was searching for a malformed json error in AWS IoT and found this out after debugging the message in another topic. Message was 307 chars long and got truncated :).

You can see an example in the advanced example.