Hi,
Question to correct the cardinal sin of string use for the string bashers
This achieves the MQTT server output I want and it works
What is the most efficient, least risk way to write this? Full explanations for why if your version is better please.
Danke :))
mqttClient.beginMessage("MSG/outgoing");
String strBraceIn = "{";
String strBraceOut = "}";
String strQuoteIn = "\"";
String strQuoteOut = "\"";
String strColon = ": ";
String strComma = ",";
mqttClient.print(strBraceIn + "\n");
mqttClient.print(strQuoteIn + "temperature" + strQuoteOut + strColon + TempRandNum + strComma + "\n");
mqttClient.print(strQuoteIn + "humidity" + strQuoteOut + strColon + HumRandNum + strComma + "\n");
mqttClient.print(strQuoteIn + "barometer" + strQuoteOut + strColon + BarRandNum + strComma + "\n");
mqttClient.print(strQuoteIn + "wind" + strQuoteOut + strColon + strBraceIn + "\n");
mqttClient.print(strQuoteIn + "velocity" + strQuoteOut + strColon + VeloRandNum + strComma + "\n");
mqttClient.print(strQuoteIn + "bearing" + strQuoteOut + strColon + BearRandNum + strComma + "\n");
mqttClient.print(strBraceOut + "\n");
mqttClient.print(strBraceOut);
mqttClient.endMessage();
When combining Strings with '+', you create a whole stack of temporary Strings. It eventually can bite you. Further each String object uses a minimum of 6 bytes not including the actual text.
So char braceIn = '{';
is far more efficient.
I would just simply print every single piece of the data that you want to send.
mqttClient.print(braceIn);
mqttClient.print('\n');
...
mqttClient.print (F("temperature"));
...
The F macro saves space (on AVR based boards) by not placing the text in RAM.
Not behind a PC to work it all out for you, I hope you get the idea.
2 Likes
I would never bash strings. Null terminated character arrays are good. Strings or objects of the String class, though I do not use.
2 Likes
J-M-L
May 6, 2022, 7:40pm
4
I would use 1 character like 't' for "température" or 'h' instead of humidity etc
There is no reason to be that verbose for M2M communication
That would make the transmission more efficient and use up less memory
(Plus what @sterretje said)
2 Likes
Why not something like this for each measurement?
mqttClient.print("{\n");
mqttClient.print("\"temperature\": ");
mqttClient.print(TempRandNum);
mqttClient.print(",\n");
No string object overhead.
2 Likes
Thanks. Awesome. There you go.
Also possibly streaming values known order.
Everything is coming together in the IoT system now.
He is using an AMD-uino with RAM to waste and String loving library.
system
Closed
November 2, 2022, 8:53pm
9
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.