Https ota update follow redirects esp32

Hi Im new to this forum. Please move this or delete if this is the wrong place to post.

I recently struggled to implement ota updates from GitHub releases. because GitHub redirects the https://github.com/user/repo/releases/download/v1/firmware.bin link to the actual download link once. all info I found failed with this link eg this post.

Finally I found this great example. This follows redirects plus progress status is printed to serial. https is handled via insecure mode see first link for more info.
Github might rate limit your ip if you call this too often though.
I tested this on a adafruit feather esp32s3 4mb flash 2mb param.

I just want to document this here as I had a hard time with this and hope this helps future me or others.




// source https://github.com/espressif/arduino-esp32/issues/9530#issuecomment-2090034699 


#include <Arduino.h>
#include <HTTPClient.h>
#include <HTTPUpdate.h>
#include <Update.h>
#include <WiFiClientSecure.h>

const char* fmtMemCk = "\nFree: %d\tMaxAlloc: %d\t PSFree: %d\n\n";

#define URL "https://testServer/version/downloadSpecific?version=1.0.7"
#define SSID "WIFI_SSID"
#define PASSWORD "WIFI_PASS"
#define MEMCK Serial.printf(fmtMemCk,ESP.getFreeHeap(),ESP.getMaxAllocHeap(),ESP.getFreePsram())

WiFiClientSecure secureClient;
HTTPUpdate Updater;

void updateSuccess() {
    printf("Update success\n");
}

void updateStart() {
    printf("Update started\n");
}

void updateProgressReport(float percent) {
    printf("Progress: %.2f %%\n", percent);
    MEMCK;
}

void updateError(int error) {
    printf("%s\n", Updater.getLastErrorString().c_str());
}

void connectToWiFi() {
    WiFi.mode(WIFI_STA);
    WiFi.begin(SSID, PASSWORD);
    uint8_t result = WiFi.waitForConnectResult();
    if (result != WL_CONNECTED) {
        printf("WiFi connection failed: %d\n", result);
        ESP.restart();
        return;
    }
    printf("WiFi connected\n");
}

void setup() {
    Serial.begin(115200);
    connectToWiFi();

    secureClient.setInsecure();
    secureClient.setTimeout(5);

    Updater.rebootOnUpdate(false);
    Updater.setFollowRedirects(HTTPC_FORCE_FOLLOW_REDIRECTS);

    Updater.onStart([]() { updateStart(); });
    Updater.onEnd([]() { updateSuccess(); });
    Updater.onError([](int err) { updateError(err); });
    Updater.onProgress([](int current, int total) {
        updateProgressReport(100.0 * current / total);
    });

    HTTPUpdateResult result = Updater.update(secureClient, URL, "", [](HTTPClient *http) {
        http->addHeader("Authorization", "{\"token\":\"noInitYet\"}");
        http->addHeader("Accept", "application/octet-stream");
    });
    if (result != HTTP_UPDATE_OK) {
        updateError(result);
    } else {
        printf("Update success\n");
    }
}

void loop() {
    vTaskDelay(1);
}
1 Like