knolleary / pubsubclient

A client library for the Arduino Ethernet Shield that provides support for MQTT.
http://pubsubclient.knolleary.net/
MIT License
3.82k stars 1.47k forks source link

Publish stream with unknown length #935

Closed AddioElectronics closed 2 years ago

AddioElectronics commented 2 years ago

Instead of serializing JSON data to a string, and then publishing, I am wanting to serialize to publish stream. Problem is I do not know the length before hand, and do not want to calculate each value and key in the JSON document.

Is it ok to pass beginPublish() a length larger than what I send, and call endPublish prematurely? Or would I have to send dummy data after?

My idea is something like this, just wondering if there is a right and a wrong way to do this.

bool success = false;
size_t docSize = document->capacity();

if (success = mqttClient.beginPublish(topic, docSize, deviceMqttSettings.retain))
{
    size_t size = serializeJson(document, mqttClient);

    while (docSize > size)
    {
        mqttClient.write((uint8_t)" ");
        size++;
    }

    success = mqttClient.endPublish();
}
IronBamBam1990 commented 2 years ago

size_t len = measureJson(doc); But you can do this at other way

AddioElectronics commented 2 years ago

Ahh thanks. Did not know that function exists.