Begin an ESP32 OTA with esp_ota_begin and esp_ota_write
Start an ESP32 OTA update with esp_ota_begin, stream the image through esp_ota_write, then finish with esp_ota_end, on ESP-IDF v5.4.
Open the update once, write chunks as they arrive, and close it so the image is validated. esp_ota_begin takes the target partition and an image size, and hands back a handle that esp_ota_write and esp_ota_end use. With ESP-IDF v5.4, passing OTA_WITH_SEQUENTIAL_WRITES erases sectors as you go instead of erasing the whole partition up front.
#include "esp_ota_ops.h"
#include "esp_log.h"
esp_err_t ota_apply(const uint8_t *img, size_t len) {
const esp_partition_t *next = esp_ota_get_next_update_partition(NULL);
esp_ota_handle_t h;
esp_err_t err = esp_ota_begin(next, OTA_WITH_SEQUENTIAL_WRITES, &h);
if (err != ESP_OK) return err;
for (size_t off = 0; off < len; off += 1024) {
size_t n = (len - off < 1024) ? (len - off) : 1024;
err = esp_ota_write(h, img + off, n);
if (err != ESP_OK) { esp_ota_abort(h); return err; }
}
err = esp_ota_end(h); // checks magic byte, size and checksum
ESP_LOGI("ota", "end: %s", esp_err_to_name(err));
return err;
}I (5120) ota: end: ESP_OKThe tick count will differ. esp_ota_end is where a truncated or corrupted image is caught, with ESP_ERR_OTA_VALIDATE_FAILED, so never skip it. The new image does not run until you call esp_ota_set_boot_partition. See the OTA reference.