From bdfbe4093e56160b8d3f7fee13aeaea2504d1763 Mon Sep 17 00:00:00 2001 From: pennam Date: Thu, 19 Oct 2023 11:37:49 +0200 Subject: [PATCH] Add protected methods to init variables and handle crc --- src/Arduino_ESP32_OTA.cpp | 47 ++++++++++++++++++++++++++++++++++----- src/Arduino_ESP32_OTA.h | 9 +++++++- 2 files changed, 50 insertions(+), 6 deletions(-) diff --git a/src/Arduino_ESP32_OTA.cpp b/src/Arduino_ESP32_OTA.cpp index 7a95dfb..2b32a21 100644 --- a/src/Arduino_ESP32_OTA.cpp +++ b/src/Arduino_ESP32_OTA.cpp @@ -47,14 +47,21 @@ Arduino_ESP32_OTA::Arduino_ESP32_OTA() Arduino_ESP32_OTA::Error Arduino_ESP32_OTA::begin() { + /* initialize private variables */ + otaInit(); /* ... initialize CRC ... */ - _crc32 = 0xFFFFFFFF; + crc32Init(); if(!isCapable()) { DEBUG_ERROR("%s: board is not capable to perform OTA", __FUNCTION__); return Error::NoOtaStorage; } + + if(Update.isRunning()) { + Update.abort(); + DEBUG_DEBUG("%s: Aborting running update", __FUNCTION__); + } if(!Update.begin(UPDATE_SIZE_UNKNOWN)) { DEBUG_ERROR("%s: failed to initialize flash update", __FUNCTION__); @@ -89,7 +96,7 @@ uint8_t Arduino_ESP32_OTA::read_byte_from_network() } if (_client->available()) { const uint8_t data = _client->read(); - _crc32 = crc_update(_crc32, &data, 1); + crc32Update(data); return data; } } @@ -243,10 +250,10 @@ int Arduino_ESP32_OTA::download(const char * ota_url) Arduino_ESP32_OTA::Error Arduino_ESP32_OTA::update() { - /* ... then finalise ... */ - _crc32 ^= 0xFFFFFFFF; + /* ... then finalize ... */ + crc32Finalize(); - if(_crc32 != _ota_header.header.crc32) { + if(!crc32Verify()) { DEBUG_ERROR("%s: CRC32 mismatch", __FUNCTION__); return Error::OtaHeaderCrc; } @@ -270,3 +277,33 @@ bool Arduino_ESP32_OTA::isCapable() const esp_partition_t * ota_1 = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_1, NULL); return ((ota_0 != nullptr) && (ota_1 != nullptr)); } + +/****************************************************************************** + PROTECTED MEMBER FUNCTIONS + ******************************************************************************/ + +void Arduino_ESP32_OTA::otaInit() +{ + _ota_size = 0; + _ota_header = {0}; +} + +void Arduino_ESP32_OTA::crc32Init() +{ + _crc32 = 0xFFFFFFFF; +} + +void Arduino_ESP32_OTA::crc32Update(const uint8_t data) +{ + _crc32 = crc_update(_crc32, &data, 1); +} + +void Arduino_ESP32_OTA::crc32Finalize() +{ + _crc32 ^= 0xFFFFFFFF; +} + +bool Arduino_ESP32_OTA::crc32Verify() +{ + return (_crc32 == _ota_header.header.crc32); +} diff --git a/src/Arduino_ESP32_OTA.h b/src/Arduino_ESP32_OTA.h index b34aa88..fac2aeb 100644 --- a/src/Arduino_ESP32_OTA.h +++ b/src/Arduino_ESP32_OTA.h @@ -82,8 +82,15 @@ class Arduino_ESP32_OTA void reset(); static bool isCapable(); -private: +protected: + + void otaInit(); + void crc32Init(); + void crc32Update(const uint8_t data); + void crc32Finalize(); + bool crc32Verify(); +private: Client * _client; OtaHeader _ota_header; size_t _ota_size;