ESPHome  2023.3.2
ota_backend_esp_idf.cpp
Go to the documentation of this file.
1 #include "esphome/core/defines.h"
2 #ifdef USE_ESP_IDF
3 
4 #include <esp_task_wdt.h>
5 
6 #include "ota_backend_esp_idf.h"
7 #include "ota_component.h"
8 #include <esp_ota_ops.h>
10 
11 namespace esphome {
12 namespace ota {
13 
15  this->partition_ = esp_ota_get_next_update_partition(nullptr);
16  if (this->partition_ == nullptr) {
18  }
19  esp_task_wdt_init(15, false); // The following function takes longer than the 5 seconds timeout of WDT
20  esp_err_t err = esp_ota_begin(this->partition_, image_size, &this->update_handle_);
21  esp_task_wdt_init(CONFIG_ESP_TASK_WDT_TIMEOUT_S, false); // Set the WDT back to the configured timeout
22  if (err != ESP_OK) {
23  esp_ota_abort(this->update_handle_);
24  this->update_handle_ = 0;
25  if (err == ESP_ERR_INVALID_SIZE) {
27  } else if (err == ESP_ERR_FLASH_OP_TIMEOUT || err == ESP_ERR_FLASH_OP_FAIL) {
29  }
31  }
32  this->md5_.init();
33  return OTA_RESPONSE_OK;
34 }
35 
36 void IDFOTABackend::set_update_md5(const char *expected_md5) { memcpy(this->expected_bin_md5_, expected_md5, 32); }
37 
38 OTAResponseTypes IDFOTABackend::write(uint8_t *data, size_t len) {
39  esp_err_t err = esp_ota_write(this->update_handle_, data, len);
40  this->md5_.add(data, len);
41  if (err != ESP_OK) {
42  if (err == ESP_ERR_OTA_VALIDATE_FAILED) {
44  } else if (err == ESP_ERR_FLASH_OP_TIMEOUT || err == ESP_ERR_FLASH_OP_FAIL) {
46  }
48  }
49  return OTA_RESPONSE_OK;
50 }
51 
53  this->md5_.calculate();
54  if (!this->md5_.equals_hex(this->expected_bin_md5_)) {
55  this->abort();
57  }
58  esp_err_t err = esp_ota_end(this->update_handle_);
59  this->update_handle_ = 0;
60  if (err == ESP_OK) {
61  err = esp_ota_set_boot_partition(this->partition_);
62  if (err == ESP_OK) {
63  return OTA_RESPONSE_OK;
64  }
65  }
66  if (err == ESP_ERR_OTA_VALIDATE_FAILED) {
68  }
69  if (err == ESP_ERR_FLASH_OP_TIMEOUT || err == ESP_ERR_FLASH_OP_FAIL) {
71  }
73 }
74 
76  esp_ota_abort(this->update_handle_);
77  this->update_handle_ = 0;
78 }
79 
80 } // namespace ota
81 } // namespace esphome
82 #endif
void init()
Initialize a new MD5 digest computation.
Definition: md5.cpp:10
bool equals_hex(const char *expected)
Compare the digest against a provided hex-encoded digest (32 bytes).
Definition: md5.cpp:59
OTAResponseTypes begin(size_t image_size) override
void add(const uint8_t *data, size_t len)
Add bytes of data for the digest.
Definition: md5.cpp:15
std::string size_t len
Definition: helpers.h:286
Definition: a4988.cpp:4
OTAResponseTypes write(uint8_t *data, size_t len) override
void calculate()
Compute the digest, based on the provided data.
Definition: md5.cpp:17
void set_update_md5(const char *md5) override
OTAResponseTypes end() override