Copy the image from partition to partition
Posted: Wed May 29, 2024 11:35 am
Hello Everyone,
i am trying to copy a binary image located on a data fat partition to an app partition to set the boot from the app partition.
My Idea is to allocate a buffer and read and write the image in loop. Unfortunately is the copied image invalid and i keep getting these log messages:
E (3024) esp_image: image at 0x110000 has invalid magic byte (nothing flashed here?)
E (3034) example_main: Failed to set boot partition to OTA_0: ESP_ERR_OTA_VALIDATE_FAILED
Here is the code:
i am trying to copy a binary image located on a data fat partition to an app partition to set the boot from the app partition.
My Idea is to allocate a buffer and read and write the image in loop. Unfortunately is the copied image invalid and i keep getting these log messages:
E (3024) esp_image: image at 0x110000 has invalid magic byte (nothing flashed here?)
E (3034) example_main: Failed to set boot partition to OTA_0: ESP_ERR_OTA_VALIDATE_FAILED
Here is the code:
- void copy_image_to_ota0() {
- const esp_partition_t *storage_partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_FAT, "storage");
- if (!storage_partition) {
- ESP_LOGE(TAG, "Storage partition not found");
- return;
- }
- const esp_partition_t *ota_0_partition = esp_partition_find_first(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_APP_OTA_0, NULL);
- if (!ota_0_partition) {
- ESP_LOGE(TAG, "OTA_0 partition not found");
- return;
- }
- if (storage_partition->size > ota_0_partition->size) {
- ESP_LOGE(TAG, "Storage partition is larger than OTA_0 partition");
- return;
- }
- ESP_LOGI(TAG, "Copying image from storage to OTA_0 partition");
- const int BUFFER_SIZE = 4096;
- void *buffer = malloc(BUFFER_SIZE);
- if (!buffer) {
- ESP_LOGE(TAG, "Failed to allocate memory for buffer");
- return;
- }
- size_t offset = 0;
- esp_err_t err;
- while (offset < storage_partition->size) {
- size_t bytes_to_copy = MIN(BUFFER_SIZE, storage_partition->size - offset);
- err = esp_partition_read(storage_partition, offset, buffer, bytes_to_copy);
- if (err != ESP_OK) {
- ESP_LOGE(TAG, "Failed to read from storage partition at offset 0x%08x: %s", offset, esp_err_to_name(err));
- free(buffer);
- return;
- }
- err = esp_partition_write(ota_0_partition, offset, buffer, bytes_to_copy);
- if (err != ESP_OK) {
- ESP_LOGE(TAG, "Failed to write to OTA_0 partition at offset 0x%08x: %s", offset, esp_err_to_name(err));
- free(buffer);
- return;
- }
- ESP_LOGD(TAG, "Copied %d bytes from offset 0x%08x", bytes_to_copy, offset);
- offset += bytes_to_copy;
- }
- ESP_LOGI(TAG, "Image copied successfully to OTA_0 partition");
- free(buffer);
- }