Files
PI_mikrokontroler_2/releases/v1.4.0/src/APIClient.cpp

147 lines
4.6 KiB
C++

#include "APIClient.h"
#include <ArduinoJson.h>
static const char* TAG_API = "API";
APIClient::APIClient() {
}
bool APIClient::login() {
if (WiFi.status() != WL_CONNECTED) return false;
HTTPClient http;
String baseUrl = String(config.restURL);
int port = config.restPort;
if (baseUrl.indexOf("/accels/api1") >= 0) {
baseUrl = "http://62.93.60.19";
port = 5004;
}
String url = baseUrl + ":" + String(port) + "/api/v1/auth/token";
ESP_LOGI(TAG_API, "Login to %s", url.c_str());
http.begin(url);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
String payload = "grant_type=password&username=" + String(config.restUser) + "&password=" + String(config.restPass);
int httpCode = http.POST(payload);
if (httpCode == 200) {
String response = http.getString();
JsonDocument doc;
DeserializationError error = deserializeJson(doc, response);
if (!error && doc["access_token"].is<String>()) {
bearerToken = doc["access_token"].as<String>();
ESP_LOGI(TAG_API, "Token retrieved successfully.");
http.end();
return true;
}
} else {
ESP_LOGE(TAG_API, "Login failed: %d - %s", httpCode, http.getString().c_str());
}
http.end();
return false;
}
bool APIClient::uploadMeasurement(const String& filePath) {
if (WiFi.status() != WL_CONNECTED) {
ESP_LOGE(TAG_API, "No WiFi connection.");
return false;
}
if (bearerToken.isEmpty()) {
if (!login()) return false;
}
File file = SD.open(filePath, FILE_READ);
if (!file) {
ESP_LOGE(TAG_API, "Failed to open file %s", filePath.c_str());
return false;
}
String filename = filePath;
int slashIndex = filename.lastIndexOf('/');
if (slashIndex >= 0) {
filename = filename.substring(slashIndex + 1);
}
String boundary = "----WebKitFormBoundaryESP32WMT";
String head = "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"file\"; filename=\"" + filename + "\"\r\n"
+ "Content-Type: application/octet-stream\r\n\r\n";
String tail = "\r\n--" + boundary + "--\r\n";
size_t fileSize = file.size();
size_t totalLength = head.length() + fileSize + tail.length();
WiFiClient client;
String host = String(config.restURL);
int port = config.restPort;
if (host.indexOf("/accels/api1") >= 0) {
host = "http://62.93.60.19";
port = 5004;
}
host.replace("http://", "");
host.replace("https://", "");
ESP_LOGI(TAG_API, "Connecting to %s:%d for upload", host.c_str(), port);
if (!client.connect(host.c_str(), port)) {
ESP_LOGE(TAG_API, "Connection failed to host %s:%d", host.c_str(), port);
file.close();
return false;
}
ESP_LOGI(TAG_API, "Uploading %s (%d bytes)", filePath.c_str(), fileSize);
client.print(String("POST /api/v1/measurements/measurements/upload HTTP/1.1\r\n"));
client.print(String("Host: ") + host + "\r\n");
client.print(String("Authorization: Bearer ") + bearerToken + "\r\n");
client.print(String("Content-Length: ") + String(totalLength) + "\r\n");
client.print(String("Content-Type: multipart/form-data; boundary=") + boundary + "\r\n");
client.print(String("Connection: close\r\n\r\n"));
client.print(head);
uint8_t buffer[2048];
while (file.available()) {
size_t len = file.read(buffer, sizeof(buffer));
client.write(buffer, len);
Watchdog::feed();
}
client.print(tail);
file.close();
int httpCode = 0;
String responseLine;
unsigned long timeout = millis();
while (client.connected() && millis() - timeout < 15000) {
if (client.available()) {
responseLine = client.readStringUntil('\n');
responseLine.trim();
if (responseLine.startsWith("HTTP/1.1 ")) {
httpCode = responseLine.substring(9, 12).toInt();
}
if (responseLine.length() == 0) break;
}
Watchdog::feed();
}
String responseBody = "";
while(client.available()){
responseBody += client.readString();
}
client.stop();
if (httpCode == 201) {
ESP_LOGI(TAG_API, "Upload successful: 201");
return true;
} else if (httpCode == 401) {
ESP_LOGW(TAG_API, "Token expired or invalid, clearing token.");
bearerToken = "";
} else {
ESP_LOGE(TAG_API, "Upload failed with code %d. Response: %s", httpCode, responseBody.c_str());
}
return false;
}