Skip to content

Instantly share code, notes, and snippets.

@MkLHX
Last active August 2, 2022 17:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MkLHX/295e79a407db6a553085279f9548954b to your computer and use it in GitHub Desktop.
Save MkLHX/295e79a407db6a553085279f9548954b to your computer and use it in GitHub Desktop.
ESP32 - Update firmware through AsyncWebServer
AsyncWebServer server_http(80);
const char header_html[] PROGMEM = "<!DOCTYPE html><html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'/><meta name='viewport' content='width=device-width, initial-scale=1, minimum-scale=1.0, shrink-to-fit=no'><title>GreenPonik.com - WebView</title></head><body>";
const char footer_html[] PROGMEM = "</body></html>";
const char update_html[] PROGMEM = "<h1>Only .bin file</h1><form method='POST' action='/updt' enctype='multipart/form-data'><input type='file' name='update' required><input type='submit' value='Run Update'></form>";
void setup()
{
/* ... */
//Update through vebview
server_http.on("/updt", HTTP_GET, [](AsyncWebServerRequest *request) {
String view_html;
view_html += header_html;
view_html += "<h1>Actual Firmware Release: " + FW_VERSION + "</h1>";
view_html += update_html;
view_html += footer_html;
request->send(200, "text/html", view_html);
});
server_http.on("/updt", HTTP_POST, [](AsyncWebServerRequest *request) {
espShouldReboot = !Update.hasError();
AsyncWebServerResponse *response = request->beginResponse(200, "text/html", espShouldReboot ? "<h1><strong>Update DONE</strong></h1><br><a href='/'>Return Home</a>" : "<h1><strong>Update FAILED</strong></h1><br><a href='/updt'>Retry?</a>");
response->addHeader("Connection", "close");
request->send(response); }, [](AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
if (!index)
{
Serial.printf("Update Start: %s\n", filename.c_str());
if (!Update.begin((ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000))
{
Update.printError(Serial);
}
}
if (!Update.hasError())
{
if (Update.write(data, len) != len)
{
Update.printError(Serial);
}
}
if (final)
{
if (Update.end(true))
{
Serial.printf("Update Success: %uB\n", index + len);
}
else
{
Update.printError(Serial);
}
}
});
server_http.begin();
/* ... */
}
void loop()
{
if (espShouldReboot)
{
Serial.println(F("Esp reboot ..."));
delay(100);
ESP.restart();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment