Skip to content

Instantly share code, notes, and snippets.

@cgawron
Created May 3, 2018 05:16
Show Gist options
  • Save cgawron/8d00ed6be14fbc7a3677922dfdf65e4b to your computer and use it in GitHub Desktop.
Save cgawron/8d00ed6be14fbc7a3677922dfdf65e4b to your computer and use it in GitHub Desktop.
ESP32 OTA with espmqtt
static void handle_ota(esp_mqtt_event_handle_t event, char *path[], int numComponents)
{
esp_err_t err;
static esp_ota_handle_t update_handle = 0;
if (numComponents < 3)
{
ESP_LOGW(TAG, "too few components");
return;
}
if (strcmp("version", path[2]) == 0)
{
ESP_LOGI(TAG, "ota: version=%.*s", event->data_len, event->data);
if (strncmp(BUILD_TAG, event->data, strlen(BUILD_TAG)) < 0)
{
ESP_LOGI(TAG, "ota: firmware outdated, requesting update");
mqtt_subscribe("ota/firmware");
}
}
else if (strcmp("firmware", path[2]) == 0)
{
ESP_LOGI(TAG, "ota: receiving firmware image");
if (event->current_data_offset == 0)
{
update_partition = esp_ota_get_next_update_partition(NULL);
ESP_LOGI(TAG, "Writing to partition subtype %d at offset 0x%x",
update_partition->subtype, update_partition->address);
assert(update_partition != NULL);
err = esp_ota_begin(update_partition, OTA_SIZE_UNKNOWN, &update_handle);
if (err != ESP_OK)
{
ESP_LOGE(TAG, "esp_ota_begin failed (%s)", esp_err_to_name(err));
return;
}
ESP_LOGI(TAG, "esp_ota_begin succeeded");
}
if (update_handle)
{
// ESP_LOGI(TAG, "ota: writing %d bytes at offset %d", event->data_len, event->current_data_offset);
err = esp_ota_write(update_handle, event->data, event->data_len);
if (err != ESP_OK)
{
ESP_LOGE(TAG, "Error: esp_ota_write failed (%s)!", esp_err_to_name(err));
return;
}
}
if (event->data_len + event->current_data_offset >= event->total_data_len)
{
if (esp_ota_end(update_handle) != ESP_OK)
{
ESP_LOGE(TAG, "esp_ota_end failed!");
return;
}
err = esp_ota_set_boot_partition(update_partition);
if (err != ESP_OK)
{
ESP_LOGE(TAG, "esp_ota_set_boot_partition failed (%s)!", esp_err_to_name(err));
return;
}
ESP_LOGI(TAG, "Prepare to restart system!");
esp_restart();
return;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment