How to Stop a Bad OTA Update Bricking Your ESP32 Prototype
An over-the-air update can download perfectly, pass its checks, boot, and still leave you with a dead board. If the new firmware crashes before it reaches Wi-Fi, or just never connects, you can't send it a fix. You're back to the USB cable, assuming you can still reach the socket.
ESP-IDF has app rollback for this. A new image boots on probation, and unless it confirms that it works, the bootloader goes back to the old one. You have to switch it on and decide what "works" means.
Give the bootloader two slots to choose between
You need two OTA app partitions and a small otadata partition that records which one to boot. This partitions.csv is for a board with 4 MB of flash and no factory image:
# Name, Type, SubType, Offset, Size
nvs, data, nvs, 0x9000, 0x4000
otadata, data, ota, 0xd000, 0x2000
phy_init, data, phy, 0xf000, 0x1000
ota_0, app, ota_0, 0x10000, 0x1E0000
ota_1, app, ota_1, 0x1F0000, 0x1E0000
Then add these to sdkconfig.defaults:
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
CONFIG_PARTITION_TABLE_CUSTOM=y
CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y
Flash this over the cable once, with a full idf.py flash. Rollback lives in the bootloader and the slots live in the partition table, and an ordinary app OTA replaces neither. If you already have an sdkconfig file, check the options in idf.py menuconfig, because defaults don't override values already set there.
Quick detour: otadata is 0x2000 bytes because it is two flash sectors. Losing power while rewriting your only record of what to boot would be a daft way to die, so there is a second copy to fall back on, which is a nice bit of design. Back to the apps.
A new image gets exactly one chance
With rollback enabled, an update moves through these states:
ESP_OTA_IMG_NEW: written and selected, not yet booted.ESP_OTA_IMG_PENDING_VERIFY: the bootloader sets this on the first boot.ESP_OTA_IMG_VALID: your app confirmed itself.ESP_OTA_IMG_INVALID: your app rejected itself.ESP_OTA_IMG_ABORTED: it rebooted while still pending, so the bootloader gave up on it.
Rollback needs a reset. A crash that reboots the chip will trigger it, but firmware that sits in a retry loop waiting for Wi-Fi can stay pending, and useless, for as long as it has power.
Put a deadline on the self-test
Start a timer before doing anything that could hang. If it expires, restart, and the bootloader will roll back.
#include <stdbool.h>
#include "esp_err.h"
#include "esp_ota_ops.h"
#include "esp_system.h"
#include "esp_timer.h"
/* Yours: bring up the hardware and network, reach the update server. */
bool start_and_self_test(void);
static void verify_deadline(void *arg)
{
esp_restart(); /* still pending, so this rolls back */
}
void app_main(void)
{
esp_ota_img_states_t state;
bool pending =
esp_ota_get_state_partition(esp_ota_get_running_partition(),
&state) == ESP_OK &&
state == ESP_OTA_IMG_PENDING_VERIFY;
esp_timer_handle_t timer = NULL;
if (pending) {
const esp_timer_create_args_t args = {
.callback = verify_deadline,
.name = "ota_verify",
};
ESP_ERROR_CHECK(esp_timer_create(&args, &timer));
ESP_ERROR_CHECK(esp_timer_start_once(timer, 120 * 1000000ULL));
}
bool ok = start_and_self_test();
if (pending) {
if (ok) {
ESP_ERROR_CHECK(esp_timer_stop(timer));
ESP_ERROR_CHECK(esp_ota_mark_app_valid_cancel_rollback());
} else {
esp_ota_mark_app_invalid_rollback_and_reboot();
}
}
/* Normal application work starts here. */
}
The 120 seconds is a placeholder. Time a slow but healthy boot on your own network and leave a generous margin.
A software timer has limits. If a callback blocks the timer task, or the system is wedged badly enough, it won't run. Keep the interrupt watchdog on, and consider CONFIG_ESP_TASK_WDT_PANIC=y so that a task watchdog timeout resets the chip instead of only complaining.
Test the way back in, not every feature
Above all, ask: can this firmware receive the next update? You can fix a broken temperature reading remotely, but you can't do that with a broken network stack.
A sensible minimum is:
- configuration loads;
- the network connects;
- an authenticated request to the update server succeeds;
- anything that could damage hardware if wrong, such as output pin setup, behaves.
This does mean a router outage or power cut during probation can reject a perfectly good build. I'd take that trade for a prototype: the old firmware still runs, and you can retry.
Don't install the same bad build again
There's a loop here that is easy to miss. The device rolls back, asks the server for updates, sees the "newer" build and installs it again, round and round, wearing flash as it goes.
Read the incoming image's version first and compare it with the last rejected one:
#include <string.h>
#include "esp_https_ota.h"
#include "esp_ota_ops.h"
#include "esp_system.h"
esp_err_t update_from(const esp_http_client_config_t *http)
{
const esp_https_ota_config_t cfg = { .http_config = http };
esp_https_ota_handle_t handle = NULL;
esp_err_t err = esp_https_ota_begin(&cfg, &handle);
if (err != ESP_OK) {
return err;
}
esp_app_desc_t incoming, rejected;
err = esp_https_ota_get_img_desc(handle, &incoming);
const esp_partition_t *bad = esp_ota_get_last_invalid_partition();
if (err == ESP_OK && bad != NULL &&
esp_ota_get_partition_description(bad, &rejected) == ESP_OK &&
strncmp(incoming.version, rejected.version,
sizeof(incoming.version)) == 0) {
err = ESP_ERR_INVALID_VERSION;
}
if (err == ESP_OK) {
do {
err = esp_https_ota_perform(handle);
} while (err == ESP_ERR_HTTPS_OTA_IN_PROGRESS);
}
if (err == ESP_OK && !esp_https_ota_is_complete_data_received(handle)) {
err = ESP_FAIL;
}
if (err != ESP_OK) {
esp_https_ota_abort(handle);
return err;
}
err = esp_https_ota_finish(handle);
if (err == ESP_OK) {
esp_restart();
}
return err;
}
Give every build a distinct version string, or this check can't tell the fix from the failure. Set up server verification in the HTTP config with cert_pem or crt_bundle_attach.
HTTPS only tells you who you downloaded from. If you need the device to check who built the image, look at ESP-IDF's signed app verification, which can be used without hardware secure boot.
Don't confuse any of this with anti-rollback, which stops devices returning to firmware with an older security version. It burns eFuses, allows only 32 steps on the ESP32, and is not something to enable casually on a prototype.
Old firmware must survive new data
Rollback restores the app, not your NVS contents or other stored data. If version 2 converts the configuration to a new format and then fails, version 1 wakes up to settings it can't read.
Avoid destructive migrations until after confirmation, or write new keys alongside the old ones. Also check your NVS start-up code: the common pattern of erasing the partition when initialisation reports a version mismatch could take your Wi-Fi credentials with it.
Arduino may confirm the image for you
In the Arduino-ESP32 core, when rollback support is compiled in, initArduino() handles pending images before your setup() runs. The default verifyOta() returns true, so the image is approved before your code has proved anything.
To confirm it later yourself, override the weak hook:
extern "C" bool verifyRollbackLater() {
return true;
}
You then need the same pending check, deadline and mark-valid call as above. Your build and installed bootloader must both support rollback, so don't assume they do; run the tests below.
Break it on purpose before you trust it
With the cable attached and the serial monitor open, send these over the air from a known good build, each with its own version string:
- A build that calls
abort()before confirmation. It should return to the old slot after the reset. - A build whose self-test loops forever with a delay. It should return after your deadline.
- A build with the wrong update server address. It should reject itself.
- A good build, with power pulled during the download. The old app should still boot.
- A good build, with power pulled during probation. It should roll back.
After the first three, ask for an update again and check that the rejected version is refused. Then send a good build and make sure it stays after two reboots.
Rollback won't rescue you from every mistake. If a bug appears an hour after confirmation, the image is already "valid", and a broken bootloader or damaged hardware is outside rollback's reach. Leave the programming pads accessible on the prototype. The best remote recovery system still benefits from three centimetres of clearance for a plug.