Skip to content

Commit

Permalink
Cleanup ota files (#111)
Browse files Browse the repository at this point in the history
- Constify everything
- Remove duplicate code
- Fix warnings in js
- Reduces bin size from 1283453 to 1283273 bytes
  • Loading branch information
enwi committed Aug 11, 2023
1 parent d6734a7 commit 19f6a09
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 44 deletions.
2 changes: 1 addition & 1 deletion ESP32_AP-Flasher/include/ota.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ void handleGetExtUrl(AsyncWebServerRequest* request);
void handleLittleFSUpload(AsyncWebServerRequest* request, String filename, size_t index, uint8_t* data, size_t len, bool final);
void handleUpdateOTA(AsyncWebServerRequest* request);
void firmwareUpdateTask(void* parameter);
void updateFirmware(const char* url, const char* expectedMd5, size_t size);
void updateFirmware(const char* url, const char* expectedMd5, const size_t size);
void handleRollback(AsyncWebServerRequest* request);
void handleUpdateActions(AsyncWebServerRequest* request);
43 changes: 22 additions & 21 deletions ESP32_AP-Flasher/src/ota.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
#include <ArduinoJson.h>
#include <FS.h>
#include <HTTPClient.h>
#include "storage.h"
#include <MD5Builder.h>
#include <Update.h>

#include "storage.h"
#include "tag_db.h"
#include "web.h"

Expand Down Expand Up @@ -38,7 +38,7 @@ void handleSysinfoRequest(AsyncWebServerRequest* request) {
doc["flashsize"] = ESP.getFlashChipSize();
doc["rollback"] = Update.canRollBack();

size_t bufferSize = measureJson(doc) + 1;
const size_t bufferSize = measureJson(doc) + 1;
AsyncResponseStream* response = request->beginResponseStream("application/json", bufferSize);
serializeJson(doc, *response);
request->send(response);
Expand All @@ -50,7 +50,7 @@ void handleCheckFile(AsyncWebServerRequest* request) {
return;
}

String filePath = request->getParam("path")->value();
const String filePath = request->getParam("path")->value();
File file = contentFS->open(filePath, "r");
if (!file) {
StaticJsonDocument<64> doc;
Expand All @@ -62,13 +62,13 @@ void handleCheckFile(AsyncWebServerRequest* request) {
return;
}

size_t fileSize = file.size();
const size_t fileSize = file.size();

MD5Builder md5;
md5.begin();
md5.addStream(file, fileSize);
md5.calculate();
String md5Hash = md5.toString();
const String md5Hash = md5.toString();

file.close();

Expand All @@ -77,22 +77,21 @@ void handleCheckFile(AsyncWebServerRequest* request) {
doc["md5"] = md5Hash;
String jsonResponse;
serializeJson(doc, jsonResponse);

request->send(200, "application/json", jsonResponse);
}

void handleGetExtUrl(AsyncWebServerRequest* request) {
if (request->hasParam("url")) {
String url = request->getParam("url")->value();
const String url = request->getParam("url")->value();
HTTPClient http;
http.begin(url);
http.setConnectTimeout(5000);
http.setFollowRedirects(HTTPC_FORCE_FOLLOW_REDIRECTS);
int httpResponseCode = http.GET();
const int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
Serial.println(httpResponseCode);
String contentType = http.header("Content-Type");
size_t contentLength = http.getSize();
const String contentType = http.header("Content-Type");
const size_t contentLength = http.getSize();
if (contentLength > 0) {
String content = http.getString();
AsyncWebServerResponse* response = request->beginResponse(200, contentType, content);
Expand Down Expand Up @@ -169,17 +168,21 @@ void firmwareUpdateTask(void* parameter) {
} else {
const char* url = params->url.c_str();
const char* md5 = params->md5.c_str();
size_t size = params->size;
const size_t size = params->size;
updateFirmware(url, md5, size);
}

delete params;
vTaskDelete(NULL);
}

void updateFirmware(const char* url, const char* expectedMd5, size_t size) {
uint32_t freeStack = uxTaskGetStackHighWaterMark(NULL);
inline void printHeap() {
const uint32_t freeStack = uxTaskGetStackHighWaterMark(NULL);
Serial.printf("Free heap: %d allocatable: %d stack: %d\n", ESP.getFreeHeap(), ESP.getMaxAllocHeap(), freeStack);
}

void updateFirmware(const char* url, const char* expectedMd5, const size_t size) {
printHeap();

config.runStatus = RUNSTATUS_STOP;
vTaskDelay(3000 / portTICK_PERIOD_MS);
Expand All @@ -194,11 +197,9 @@ void updateFirmware(const char* url, const char* expectedMd5, size_t size) {

httpClient.begin(url);
httpClient.setFollowRedirects(HTTPC_FORCE_FOLLOW_REDIRECTS);
freeStack = uxTaskGetStackHighWaterMark(NULL);
Serial.printf("Free heap: %d allocatable: %d stack: %d\n", ESP.getFreeHeap(), ESP.getMaxAllocHeap(), freeStack);
int httpCode = httpClient.GET();
freeStack = uxTaskGetStackHighWaterMark(NULL);
Serial.printf("Free heap: %d allocatable: %d stack: %d\n", ESP.getFreeHeap(), ESP.getMaxAllocHeap(), freeStack);
printHeap();
const int httpCode = httpClient.GET();
printHeap();

if (httpCode == HTTP_CODE_OK) {
if (Update.begin(size)) {
Expand All @@ -215,7 +216,7 @@ void updateFirmware(const char* url, const char* expectedMd5, size_t size) {
}
});

size_t written = Update.writeStream(httpClient.getStream());
const size_t written = Update.writeStream(httpClient.getStream());
if (written == httpClient.getSize()) {
if (Update.end(true)) {
wsSerial("Firmware update successful");
Expand Down Expand Up @@ -248,7 +249,7 @@ void updateFirmware(const char* url, const char* expectedMd5, size_t size) {

void handleRollback(AsyncWebServerRequest* request) {
if (Update.canRollBack()) {
bool rollbackSuccess = Update.rollBack();
const bool rollbackSuccess = Update.rollBack();
if (rollbackSuccess) {
request->send(200, "Rollback successful");
wsSerial("Rollback successful");
Expand Down Expand Up @@ -276,7 +277,7 @@ void handleUpdateActions(AsyncWebServerRequest* request) {
}
StaticJsonDocument<1000> doc;
DeserializationError error = deserializeJson(doc, file);
JsonArray deleteFiles = doc["deletefile"].as<JsonArray>();
const JsonArray deleteFiles = doc["deletefile"].as<JsonArray>();
for (const auto& filePath : deleteFiles) {
if (contentFS->remove(filePath.as<const char*>())) {
wsSerial("deleted file: " + filePath.as<String>());
Expand Down
40 changes: 18 additions & 22 deletions ESP32_AP-Flasher/wwwroot/ota.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,14 @@ export async function initUpdate() {
print("Update it manually one last time.");
disableButtons(true);
}
return "{}";
return {};
} else {
return response.json();
}
})
.then(data => {
if (data.env) {
let matchtest='';
let matchtest = '';
if (data.buildversion != filesystemversion && filesystemversion != "custom" && data.buildversion != "custom") matchtest = " <- not matching!"
print(`env: ${data.env}`);
print(`build date: ${formatEpoch(data.buildtime)}`);
Expand All @@ -45,7 +45,7 @@ export async function initUpdate() {
print(`sha: ${data.sha}`);
print(`psram size: ${data.psramsize}`);
print(`flash size: ${data.flashsize}`);
print("--------------------------","gray");
print("--------------------------", "gray");
env = data.env;
currentVer = data.buildversion;
currentBuildtime = data.buildtime;
Expand All @@ -61,7 +61,6 @@ export async function initUpdate() {
.then(data => {
const releaseDetails = data.map(release => {
const assets = release.assets;
let fileUrl = null;
const filesJsonAsset = assets.find(asset => asset.name === 'filesystem.json');
const binariesJsonAsset = assets.find(asset => asset.name === 'binaries.json');
if (filesJsonAsset && binariesJsonAsset) {
Expand All @@ -82,7 +81,7 @@ export async function initUpdate() {
easyupdate.innerHTML = ("No releases found.");
} else {
const release = releaseDetails[0];
if (release && release.tag_name) {
if (release?.tag_name) {
if (release.tag_name == currentVer) {
easyupdate.innerHTML = `Version ${currentVer}. You are up to date`;
} else if (release.date < formatEpoch(currentBuildtime)) {
Expand All @@ -100,7 +99,7 @@ export async function initUpdate() {
table.appendChild(tableHeader);

releaseDetails.forEach(release => {
if (release && release.html_url) {
if (release?.html_url) {
const tableRow = document.createElement('tr');
let tablerow = `<td><a href="${release.html_url}" target="_new">${release.tag_name}</a></td><td>${release.date}</td><td>${release.name}</td><td><button onclick="otamodule.updateESP('${release.bin_url}', true)">ESP32</button></td><td><button onclick="otamodule.updateWebpage('${release.file_url}','${release.tag_name}', true)">Filesystem</button></td>`;
if (release.tag_name == currentVer) {
Expand Down Expand Up @@ -163,7 +162,6 @@ export async function updateWebpage(fileUrl, tagname, showReload) {
});

const checkfiles = async (files) => {

const updateactions = files.find(files => files.name === "update_actions.json");
if (updateactions) {
await fetchAndPost(updateactions.url, updateactions.name, updateactions.path);
Expand All @@ -173,7 +171,7 @@ export async function updateWebpage(fileUrl, tagname, showReload) {
body: ''
});
if (response.ok) {
const data = await response.text();
await response.text();
} else {
print(`error performing update actions: ${response.status}`, "red");
errors++;
Expand Down Expand Up @@ -227,12 +225,12 @@ export async function updateWebpage(fileUrl, tagname, showReload) {
consoleDiv.appendChild(newLine);
consoleDiv.scrollTop = consoleDiv.scrollHeight;
}
};
};
} catch (error) {
print('Error: ' + error, "red");
errors++;
reject(error);
}
reject(error);
}
})();
});
}
Expand All @@ -259,17 +257,16 @@ export async function updateESP(fileUrl, showConfirm) {
while (retryCount < maxRetries) {
try {
const response = await fetch("/getexturl?url=" + fileUrl);

const responseBody = await response.text();
if (!response.ok) {
throw new Error("Network response was not OK");
throw new Error("Network response was not OK: " + responseBody);
}

const responseBody = await response.text();
if (responseBody.trim()[0] !== "[") {
if (!responseBody.trim().startsWith("[")) {
throw new Error("Failed to fetch the release info file");
}

const data = JSON.parse(responseBody);

const file = data.find((entry) => entry.name == env + '.bin');
if (file) {
binurl = file.url;
Expand All @@ -291,7 +288,7 @@ export async function updateESP(fileUrl, showConfirm) {
});

if (response.ok) {
const result = await response.text();
await response.text();
print('OTA update initiated.');
} else {
print('Failed to initiate OTA update: ' + response.status, "red");
Expand All @@ -313,7 +310,7 @@ export async function updateESP(fileUrl, showConfirm) {

if (retryCount === maxRetries) {
print("Reached maximum retry count. Failed to execute the update.", "red");
}
}

running = false;
disableButtons(false);
Expand All @@ -327,17 +324,16 @@ $('#rollbackBtn').onclick = function () {
errors = 0;
const consoleDiv = document.getElementById('updateconsole');
consoleDiv.scrollTop = consoleDiv.scrollHeight;

print("Rolling back...");

fetch("/rollback", {
method: "POST",
body: ''
})

running = false;
disableButtons(false);

}

export function print(line, color = "white") {
Expand All @@ -360,7 +356,7 @@ export function print(line, color = "white") {

export function reboot() {
print("Rebooting now... Reloading webpage in 5 seconds...", "yellow");
fetch("/reboot",{method: "POST"});
fetch("/reboot", { method: "POST" });
setTimeout(() => {
location.reload();
}, 5000);
Expand Down

0 comments on commit 19f6a09

Please sign in to comment.