From d9aadb79fd5ac10fc9c5b844db8c3e1095961b2d Mon Sep 17 00:00:00 2001 From: Denys Fedoryshchenko Date: Thu, 20 Feb 2020 01:08:07 +0200 Subject: [PATCH] Handle stream timeouts properly, for slow HTTP/HTTPS links --- libraries/Update/src/Updater.cpp | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/libraries/Update/src/Updater.cpp b/libraries/Update/src/Updater.cpp index cfa28827e96..253176b93ac 100644 --- a/libraries/Update/src/Updater.cpp +++ b/libraries/Update/src/Updater.cpp @@ -318,6 +318,8 @@ size_t UpdateClass::write(uint8_t *data, size_t len) { size_t UpdateClass::writeStream(Stream &data) { size_t written = 0; size_t toRead = 0; + int timeout_failures = 0; + if(hasError() || !isRunning()) return 0; @@ -339,15 +341,24 @@ size_t UpdateClass::writeStream(Stream &data) { bytesToRead = remaining(); } - toRead = data.readBytes(_buffer + _bufferLen, bytesToRead); - if(toRead == 0) { //Timeout - delay(100); - toRead = data.readBytes(_buffer + _bufferLen, bytesToRead); - if(toRead == 0) { //Timeout - _abort(UPDATE_ERROR_STREAM); - return written; + /* + Init read&timeout counters and try to read, if read failed, increase counter, + wait 100ms and try to read again. If counter > 300 (30 sec), give up/abort + */ + toRead = 0; + timeout_failures = 0; + while(!toRead) { + toRead = data.readBytes(_buffer + _bufferLen, bytesToRead); + if(toRead == 0) { + timeout_failures++; + if (timeout_failures >= 300) { + _abort(UPDATE_ERROR_STREAM); + return written; + } + delay(100); } } + if(_ledPin != -1) { digitalWrite(_ledPin, !_ledOn); // Switch LED off }