Particle publish commend causing the device to go offline

I used sprintf to format data into a string and then publish it. I’ve tried publishing the first half and the second half of the string and both worked. But when I combine them into one longer string, the device will go offline.

Here’s my code. The string is formatted so that I can parse data to a website.

char publishString[80];

sprintf(publishString, "{\"Item1\": %f, \"Item2\": %f, \"Item3\": %s, \"Item4\": %f}", Item1, Item2, Item3.c_str(), Item4);
Particle.publish("Data",publishString);

I also tried to increase the buffer number from 80 to 255 to 500, none of them worked. According to the reference, the max data should be 622.

I deleted a delay function in front of the sprintf and it worked. I don’t know why a delay function would affect it but it did.

How did your "delay function" work?
When your code "stalls" for ~10sec without allowing the cloud tasks to run (either by calling Particle.process() or using SYSTEM_THREAD(ENABLED)) the cloud connection will break.

You should use snprintf() where you can also provide the buffer size to avoid buffer overflow.
However, sprintf() and snprintf() return the number of characters formatted, if this is equal to (or for sprintf() greater than) your buffer size chances are that your buffer is too short. If it always stays below you should be good without increasing the buffer.

BTW, I guess you rather want to limit the number of decimal places in your %f fields (e.g. %.2f) and you should explicitly state the scope of your publish (PRIVATE or PUBLIC) - at some point this will become compulsory and then you'd have to change that, if you do it now, you won't need to revisit this part :wink:

2 Likes

Thanks for the reply! My delay function is just the delay() in particle, that can delay in miliseconds. I had a delay(10*1000); before calling the sprintf and publish.

What device OS version are you targeting?

In really old ones delay(10*1000) would be killing the cloud connection (and also limit the publish length to 254 IIRC).

Mine is 1.1.0