esmp3/src/updater.cpp

97 lines
2.2 KiB
C++

#include <Arduino.h>
#include <Update.h>
#include "config.h"
#include "updater.h"
#include "http_client_wrapper.h"
void Updater::run() {
DEBUG("Updater is running...\n");
HTTPClientWrapper* http = new HTTPClientWrapper();
DEBUG("Requesting update info...\n");
bool result = http->get(OTA_UPDATE_URL);
if (!result) {
ERROR("Updater failed requesting %s.\n", OTA_UPDATE_URL);
return;
}
String line_str = "";
if (!read_line(&line_str, http, "VERSION")) {
return;
}
uint16_t version = line_str.toInt();
if (version==0) {
ERROR("Could not parse version number.\n");
return;
}
DEBUG("Found version %d. My version is %d.\n", version, OTA_VERSION);
if (version <= OTA_VERSION) {
return;
}
String image_path = "";
if (!read_line(&image_path, http, "IMAGE_PATH")) {
return;
}
String image_md5 = "";
if (!read_line(&image_md5, http, "IMAGE_MD5")) {
return;
}
http->close();
delete http;
if(do_update(U_FLASH, image_path, image_md5)) {
DEBUG("Update done. Rebooting...\n");
} else {
DEBUG("Update failed. Rebooting...\n");
}
delay(1000);
ESP.restart();
}
bool Updater::read_line(String* dst, HTTPClientWrapper* http, String expected_key) {
expected_key += "=";
String line = http->readUntil("\n");
if (!line.startsWith(expected_key)) {
ERROR("Expected line start with '%s', but it started with '%s'.\n", expected_key.c_str(), line.c_str());
return false;
}
line = line.substring(expected_key.length());
line.trim();
dst->concat(line);
return true;
}
bool Updater::do_update(int command, String url, String expected_md5) {
HTTPClientWrapper* http = new HTTPClientWrapper();
bool result = http->get(url);
if (!result) {
ERROR("Updater failed requesting %s.\n", url.c_str());
return false;
}
result = Update.begin(http->getSize(), command);
if (!result) {
ERROR("Update could not be started.\n");
return false;
}
Update.setMD5(expected_md5.c_str());
uint8_t buf[512];
uint16_t len;
while((len = http->read(buf, 512))) {
Update.write(buf, len);
}
http->close();
delete http;
result = Update.end();
if (!result) {
const char* error = Update.errorString();
ERROR("Writing the update failed. The error was: %s\n", error);
return false;
}
return true;
}