I made a function that serializes settings and returns a char* containing serialized data.
First i'm packing all the values into a StaticJsonDocument
, then determining size of the output string using measureJson
, then allocating space for the output char out[strsize]
and then serializing data into space allocated serializeJson(doc,out,strsize)
The problem is that output string remains empty for unknown reason.
Things i checked:
- Json document is constructed properly and actually contains configurations settings
measureJson()
function properly returns the size of output and space is being allocated,strsize
is not 0
Code:
char* configSerialize(bool msgpack){
StaticJsonDocument<settsize> doc;
JsonArray ipk = doc.createNestedArray("ip");
JsonArray gateipk = doc.createNestedArray("gateip");
JsonArray dnsk = doc.createNestedArray("dns");
JsonArray mack = doc.createNestedArray("mac");
unsigned char i;
for(i=0;i<4;i++){
ipk.add(ip[i]);
gateipk.add(gateip[i]);
dnsk.add(dns[i]);
}
for(i=0;i<6;i++){
mack.add(mac[i]);
}
doc["subnet"] = subnet;
doc["dhcp"] = DHCP;
doc["alertbuzz"] = alertbuzz;
const size_t strsize = msgpack ? measureMsgPack(doc) : measureJson(doc);
char out[strsize];
if(msgpack) serializeMsgPack(doc,out,strsize);
else serializeJson(doc,out,strsize);
return out;
}
This is a local variable/array inside your
configSerialize()
function and is invalid once you return from that function.One way would be to use
new
anddelete
to allocate/deallocate space on the heap, but I would not recommend that on Arduino.Another way would be to use
char out[FIXED_SIZE];
outside of your function - i.e. as a global variable.Also, if you're planning to use
out
as a string pointer, you'll need to add a zero byte at the end (and allocate space for that extra byte).