Files
PI_mikrokontroler_2/src/Uploader.cpp

79 lines
2.4 KiB
C++

#include "Uploader.h"
Uploader::Uploader(Display &display) : _display(display) {}
void Uploader::processQueue(int maxFiles) {
if (WiFi.status() != WL_CONNECTED) return;
String caCert = loadCACert("/cert.pem");
if (caCert == "") {
ESP_LOGE("UPLOADER", "Brak cert.pem na SD!");
return;
}
int sentCount = 0;
File root = SD.open("/");
// Przeszukiwanie folderów numerycznych stworzonych przez Measure.cpp
while (File folder = root.openNextFile()) {
if (sentCount >= maxFiles) break;
if (folder.isDirectory()) {
File dir = SD.open(folder.path());
while (File file = dir.openNextFile()) {
if (sentCount >= maxFiles) break;
String fileName = file.name();
if (fileName.endsWith(".wmt")) {
_display.textStatus("SSL UPLOADING...");
if (sendFile(String(file.path()), caCert)) {
String oldPath = String(file.path());
String newPath = oldPath;
newPath.replace(".wmt", ".sent");
file.close();
SD.rename(oldPath.c_str(), newPath.c_str());
sentCount++;
}
}
file.close();
}
dir.close();
}
folder.close();
}
root.close();
}
bool Uploader::sendFile(String filePath, String& caCert) {
File f = SD.open(filePath, FILE_READ);
if (!f) return false;
WiFiClientSecure client;
client.setCACert(caCert.c_str());
HTTPClient http;
bool success = false;
if (http.begin(client, "https://api.pwojtaszek.codes/upload")) {
http.addHeader("Content-Type", "application/octet-stream");
http.addHeader("X-File-Name", filePath);
http.addHeader("X-Device-ID", config.hostname);
int code = http.sendRequest("POST", &f, f.size());
if (code == 200) {
ESP_LOGI("UPLOADER", "Upload OK: %s", filePath.c_str());
success = true;
} else {
ESP_LOGE("UPLOADER", "Error: %d", code);
}
http.end();
}
f.close();
return success;
}
String Uploader::loadCACert(const char* path) {
File f = SD.open(path);
if (!f) return "";
String cert = f.readString();
f.close();
return cert;
}