Files
AquaMasterMQTT/src/databasebackend.h
2025-06-13 23:11:58 +02:00

192 lines
5.5 KiB
C

#pragma once
#include <Arduino.h>
#include <HTTPClient.h>
#include "master.h"
const char* BACKEND_SERVER = "http://db.reptilfpv.de:3000";
String BACKEND_TOKEN = licence; // Use the licence as the token for authentication
bool backendOnline() {
Serial.println(licence);
if (WiFi.status() != WL_CONNECTED) {
Serial.println("No WiFi connection.");
return false;
}
HTTPClient http;
http.begin(String(BACKEND_SERVER) + "/api/health");
http.addHeader("Authorization", String("Bearer ") + BACKEND_TOKEN);
int httpCode = http.GET();
bool isOnline = (httpCode == HTTP_CODE_OK);
if (isOnline) {
Serial.println("Database server connection successful");
} else {
Serial.printf("Database server connection failed, error: %d\n", httpCode);
}
http.end();
return isOnline;
}
struct UserData {
String uid;
String firstname;
String lastname;
int alter;
bool exists;
};
// UserData checkUser(const String& uid) is defined only once to avoid redefinition errors.
UserData checkUser(const String& uid) {
UserData userData = {"", "", "", 0, false};
if (!backendOnline()) {
Serial.println("No internet connection, cannot check user.");
return userData;
}
HTTPClient http;
http.begin(String(BACKEND_SERVER) + "/api/users/find");
http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", String("Bearer ") + BACKEND_TOKEN);
// Create JSON payload
StaticJsonDocument<200> requestDoc;
requestDoc["uid"] = uid;
String requestBody;
serializeJson(requestDoc, requestBody);
int httpCode = http.POST(requestBody);
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
StaticJsonDocument<512> responseDoc;
DeserializationError error = deserializeJson(responseDoc, payload);
if (!error) {
userData.uid = responseDoc["uid"].as<String>();
userData.firstname = responseDoc["firstname"].as<String>();
userData.lastname = responseDoc["lastname"].as<String>();
userData.alter = responseDoc["alter"] | 0;
userData.exists = true;
}
} else {
Serial.printf("User check failed, HTTP code: %d\n", httpCode);
}
http.end();
return userData;
}
//Function to enter user data into the database
bool enterUserData(const String& uid, const String& firstname, const String& lastname, const String& geburtsdatum, int alter) {
if (!backendOnline()) {
Serial.println("No internet connection, cannot enter user data.");
return false;
}
HTTPClient http;
http.begin(String(BACKEND_SERVER) + "/api/users/insert");
http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", String("Bearer ") + BACKEND_TOKEN);
// Create JSON payload
StaticJsonDocument<256> requestDoc;
requestDoc["uid"] = uid;
requestDoc["vorname"] = firstname;
requestDoc["nachname"] = lastname;
requestDoc["geburtsdatum"] = geburtsdatum;
requestDoc["alter"] = alter;
String requestBody;
serializeJson(requestDoc, requestBody);
int httpCode = http.POST(requestBody);
if (httpCode == HTTP_CODE_CREATED) {
Serial.println("User data entered successfully.");
http.end();
return true;
} else {
Serial.printf("Failed to enter user data, HTTP code: %d\n", httpCode);
http.end();
return false;
}
}
JsonDocument getAllLocations() {
JsonDocument locations; // Allocate memory for the JSON document
if (!backendOnline()) {
Serial.println("No internet connection, cannot fetch locations.");
return locations; // Return an empty document
}
HTTPClient http;
http.begin(String(BACKEND_SERVER) + "/api/location/");
http.addHeader("Authorization", String("Bearer ") + BACKEND_TOKEN);
int httpCode = http.GET();
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
DeserializationError error = deserializeJson(locations, payload);
if (error) {
Serial.println("Failed to parse locations JSON.");
}
} else {
Serial.printf("Failed to fetch locations, HTTP code: %d\n", httpCode);
}
http.end();
return locations; // Return the populated JSON document
}
// Keep this for backward compatibility
bool userExists(const String& uid) {
return checkUser(uid).exists;
}
//Routes from the Frontend into here and then into DB backend.
void setupBackendRoutes(AsyncWebServer& server) {
server.on("/api/health", HTTP_GET, [](AsyncWebServerRequest *request) {
DynamicJsonDocument doc(64);
doc["status"] = backendOnline() ? "connected" : "disconnected";
String response;
serializeJson(doc, response);
request->send(200, "application/json", response);
});
server.on("/api/users", HTTP_GET, [](AsyncWebServerRequest *request) {
if (!backendOnline()) {
request->send(503, "application/json", "{\"error\":\"Database not connected\"}");
return;
}
// Handle user retrieval logic here
});
//Location routes /api/location/
server.on("/api/location/", HTTP_GET, [](AsyncWebServerRequest *request){
String result;
serializeJson(getAllLocations(), result);
request->send(200, "application/json", result);
});
// Add more routes as needed
}