108 lines
2.9 KiB
C++
108 lines
2.9 KiB
C++
#ifndef UNIT_TEST
|
|
#include <fetchOTA.h>
|
|
|
|
|
|
#include "Arduino.h"
|
|
#include <ArduinoJson.h>
|
|
#include <HTTPClient.h>
|
|
|
|
#include <vector>
|
|
#include <ArduinoLog.h>
|
|
#include <HTTPUpdate.h>
|
|
|
|
|
|
OTA::OTA(String server_url, String currentVersion, String currentDeviceConfiguration) {
|
|
_serverUrl = server_url;
|
|
_currentVersion = parseVersion(currentVersion.c_str());
|
|
_current_device_configuration = currentDeviceConfiguration;
|
|
}
|
|
|
|
|
|
Firmware OTA::getLatestVersionOnServer() {
|
|
HTTPClient http;
|
|
http.begin(_serverUrl);
|
|
int httpCode = http.GET();
|
|
|
|
if (httpCode != 200) {
|
|
return createErrorResponse("HTTP GET request failed with code " + String(httpCode));
|
|
}
|
|
|
|
String payload = http.getString();
|
|
DynamicJsonDocument doc(4096);
|
|
DeserializationError error = deserializeJson(doc, payload);
|
|
|
|
if (error) {
|
|
return createErrorResponse("Failed to deserialize JSON");
|
|
}
|
|
|
|
if (!doc.containsKey("Configurations")) {
|
|
return createErrorResponse("JSON response does not contain a 'Configurations' key");
|
|
}
|
|
|
|
std::vector<Configuration> configs;
|
|
for (JsonObject config : doc["Configurations"].as<JsonArray>()) {
|
|
if (config.containsKey("Version") && config.containsKey("URL")) {
|
|
configs.push_back(Configuration{
|
|
parseVersion(config["Version"]),
|
|
config["URL"],
|
|
config["Board"],
|
|
config["Configuration"]
|
|
});
|
|
}
|
|
}
|
|
|
|
if (configs.empty()) {
|
|
return createErrorResponse("No valid configuration found in the JSON response");
|
|
}
|
|
|
|
Configuration latest = getLatestConfiguration(configs.data(), configs.size());
|
|
return Firmware{
|
|
latest.version,
|
|
latest.url,
|
|
true,
|
|
""
|
|
};
|
|
}
|
|
|
|
Firmware OTA::createErrorResponse(const String& errorMsg) {
|
|
return Firmware{
|
|
Version{0, 0, 0},
|
|
"",
|
|
false,
|
|
errorMsg
|
|
};
|
|
}
|
|
|
|
void OTA::run_ota_update(String url) {
|
|
Log.verbose("Starting OTA upgrade");
|
|
HTTPUpdate httpUpdate;
|
|
httpUpdate.onStart(update_started);
|
|
httpUpdate.onEnd(update_finished);
|
|
httpUpdate.onProgress(update_progress);
|
|
httpUpdate.onError(update_error);
|
|
Serial.println("RUNNING OTA");
|
|
|
|
WiFiClientSecure client;
|
|
client.setInsecure();
|
|
|
|
t_httpUpdate_return ret = httpUpdate.update(client, "https://iot.tobiasmaier.me/firmware/waterlevel/INA233/1_1_1.bin");
|
|
// t_httpUpdate_return ret = httpUpdate.update(client, "https://iot.tobiasmaier.me", 443, "/firmware/waterlevel/INA233/1_0_1.bin");
|
|
|
|
switch (ret) {
|
|
case HTTP_UPDATE_FAILED:
|
|
Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s\n", httpUpdate.getLastError(), httpUpdate.getLastErrorString().c_str());
|
|
break;
|
|
|
|
case HTTP_UPDATE_NO_UPDATES:
|
|
Serial.println("HTTP_UPDATE_NO_UPDATES");
|
|
break;
|
|
|
|
case HTTP_UPDATE_OK:
|
|
Serial.println("HTTP_UPDATE_OK");
|
|
break;
|
|
}
|
|
}
|
|
|
|
|
|
|
|
#endif |