Skip to content

Instantly share code, notes, and snippets.

@sticilface
Last active November 26, 2015 11:59
Show Gist options
  • Save sticilface/f8a65dc4a227b47eca4b to your computer and use it in GitHub Desktop.
Save sticilface/f8a65dc4a227b47eca4b to your computer and use it in GitHub Desktop.
Send buffered packets from print to either ESP8266WebServer or WiFiClient on ESP8266
/*
Send out buffered packets to ESP8266WebServer or WiFiClient on ESP8266 on Arduino IDE.
See https://github.com/bblanchon/ArduinoJson/issues/166
exmaple of use with arudino json
size_t jsonlength = root.measureLength();
HTTP.setContentLength(jsonlength);
HTTP.send(200, "text/json" );
BufferedPrint<HTTP_DOWNLOAD_UNIT_SIZE> proxy(HTTP);
root.printTo(proxy);
proxy.flush();
OR
size_t jsonlength = root.measureLength();
HTTP.setContentLength(jsonlength);
HTTP.send(200, "text/json" );
WiFiClient client = HTTP.client();
BufferedPrint<HTTP_DOWNLOAD_UNIT_SIZE> proxy(client);
root.printTo(proxy);
proxy.flush();
*/
template<size_t CAPACITY>
class BufferedPrint : public Print
{
public:
BufferedPrint(ESP8266WebServer & HTTP) : _size(0)
{
_client = HTTP.client();
}
BufferedPrint(WiFiClient & client) : _client(client), _size(0)
{
}
~BufferedPrint() {
_client.stop();
}
virtual size_t write(uint8_t c)
{
_buffer[_size++] = c;
if (_size + 1 == CAPACITY)
{
flush();
}
}
void flush()
{
_client.write( (const char *)_buffer, _size);
_size = 0;
}
private:
WiFiClient _client;
size_t _size;
char _buffer[CAPACITY];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment