ArduinoJSON with 2 different JsonDocument in the same MQTT CallBack function
I use MQTT library with ArduinoJSON with 2 different JsonDocument in the same MQTT CallBack function.
It is the right way to use ArduinoJson library in MQTT callBack function
https://github.com/256dpi/arduino-mqtt
Thank you
void messageReceived(String &topic, String &payload_mqtt) {
topic.reserve(32);
payload_mqtt.reserve(128);
/*
If you write topic == "foo" you're comparing pointer equality,
which will always fail since the pointer to "foo" will never be the same as the pointer to topic.
You need to use the equals method on the String class: topic.equals("foo") to compare the contents of the two strings.
*/
if(topic.equals("topic_grid")) { // "topic_grid" from Mk2 router
DynamicJsonDocument doc1(128); // Allocate a temporary JsonDocument
DeserializationError error = deserializeJson(doc1, payload_mqtt);
if (error) { // Test if parsing succeeds
count_json++;
return; // Terminate the function
}
PW = doc1["PW"];
PR = doc1["PR"];
L1 = doc1["L1"];
L2 = doc1["L2"];
L3 = doc1["L3"];
doc1.clear();
}
/*
{"FCST_D1":15,"FCST_D2":12,"FCST_3H":11,"FCST_6H":10}
Data structures 64 Bytes needed to stores the JSON objects and arrays in memory
Strings 32 Bytes needed to stores the strings in memory
Total (minimum) 96 Minimum capacity for the JsonDocument.
Total (recommended) 128 Including some slack in case the strings change, and rounded to a power of two
*/
if (topic.equals("topic_forecast")) {
DynamicJsonDocument doc2(128);
DeserializationError error = deserializeJson(doc2, payload_mqtt);
if (error) { // Test if parsing succeeds
count_json++;
return;
} // Terminate the function
FCST_D1 = doc2["fcst_d1"];
FCST_D2 = doc2["fcst_d2"];
FCST_3H = doc2["fcst_3h"];
FCST_6H = doc2["fcst_6h"];
doc2.clear();
}
if (topic.equals("topic_VOC/GarageCOV/voc")) {
VOC_garage = payload_mqtt.toInt();
}
}