Formatting all c files

This commit is contained in:
Carsten Graf
2025-07-12 17:32:16 +02:00
parent 94b30ed7a3
commit 585d2d7d5d
13 changed files with 1129 additions and 1118 deletions

View File

@@ -1,32 +1,35 @@
#pragma once
#include <Arduino.h>
#include "master.h"
#include <Arduino.h>
// Aquacross Timer - ESP32 Master (Webserver + ESP-NOW + Anlernmodus)
#include <ESPAsyncWebServer.h>
void handleLearningMode(const uint8_t* mac) {
void handleLearningMode(const uint8_t *mac) {
// Prüfen ob MAC bereits einem anderen Button zugewiesen ist
if (buttonConfigs.start1.isAssigned && memcmp(buttonConfigs.start1.mac, mac, 6) == 0) {
if (buttonConfigs.start1.isAssigned &&
memcmp(buttonConfigs.start1.mac, mac, 6) == 0) {
Serial.println("Diese MAC ist bereits zugewiesen - wird ignoriert");
return;
}
if (buttonConfigs.stop1.isAssigned && memcmp(buttonConfigs.stop1.mac, mac, 6) == 0) {
if (buttonConfigs.stop1.isAssigned &&
memcmp(buttonConfigs.stop1.mac, mac, 6) == 0) {
Serial.println("Diese MAC ist bereits zugewiesen - wird ignoriert");
return;
}
if (buttonConfigs.start2.isAssigned && memcmp(buttonConfigs.start2.mac, mac, 6) == 0) {
if (buttonConfigs.start2.isAssigned &&
memcmp(buttonConfigs.start2.mac, mac, 6) == 0) {
Serial.println("Diese MAC ist bereits zugewiesen - wird ignoriert");
return;
}
if (buttonConfigs.stop2.isAssigned && memcmp(buttonConfigs.stop2.mac, mac, 6) == 0) {
if (buttonConfigs.stop2.isAssigned &&
memcmp(buttonConfigs.stop2.mac, mac, 6) == 0) {
Serial.println("Diese MAC ist bereits zugewiesen - wird ignoriert");
return;
}
// MAC ist noch nicht zugewiesen, normal fortfahren
switch(learningStep) {
switch (learningStep) {
case 0: // Start1
memcpy(buttonConfigs.start1.mac, mac, 6);
buttonConfigs.start1.isAssigned = true;
@@ -63,14 +66,19 @@ void handleStartLearning() {
// Count assigned buttons and set appropriate learning step
int assignedButtons = 0;
if (buttonConfigs.start1.isAssigned) assignedButtons++;
if (buttonConfigs.stop1.isAssigned) assignedButtons++;
if (buttonConfigs.start2.isAssigned) assignedButtons++;
if (buttonConfigs.stop2.isAssigned) assignedButtons++;
if (buttonConfigs.start1.isAssigned)
assignedButtons++;
if (buttonConfigs.stop1.isAssigned)
assignedButtons++;
if (buttonConfigs.start2.isAssigned)
assignedButtons++;
if (buttonConfigs.stop2.isAssigned)
assignedButtons++;
learningStep = assignedButtons;
Serial.printf("Learning mode started - %d buttons already assigned, continuing at step %d\n",
Serial.printf("Learning mode started - %d buttons already assigned, "
"continuing at step %d\n",
assignedButtons, learningStep);
}

View File

@@ -1,18 +1,20 @@
#pragma once
#include <Arduino.h>
#include "master.h"
#include <Arduino.h>
#include <ArduinoJson.h>
#include <PicoMQTT.h>
#include "buttonassigh.h"
#include "databasebackend.h"
#include "debug.h"
#include "helper.h"
#include "statusled.h"
#include "timesync.h"
#include "buttonassigh.h"
#include "helper.h"
#include "debug.h"
#include <map>
#include "databasebackend.h"
#include "webserverrouter.h"
#include <map>
struct TimestampData {
uint64_t lastMessageTimestamp; // Timestamp from the device
@@ -23,8 +25,6 @@ struct TimestampData {
// Map to store timestamp data for each MAC address
std::map<String, TimestampData> deviceTimestamps;
// Datenstruktur für ESP-NOW Nachrichten
// Datenstruktur für ESP-NOW Nachrichten
typedef struct {
@@ -37,9 +37,9 @@ typedef struct {
PicoMQTT::Server mqtt;
void readButtonJSON(const char * topic, const char * payload) {
void readButtonJSON(const char *topic, const char *payload) {
const char* prefix = "aquacross/button/";
const char *prefix = "aquacross/button/";
size_t prefixLen = strlen(prefix);
if (strncmp(topic, prefix, prefixLen) != 0) {
return;
@@ -68,7 +68,6 @@ void readButtonJSON(const char * topic, const char * payload) {
Serial.printf(" Button MAC: %s\n", buttonId.c_str());
Serial.printf(" Timestamp: %llu\n", timestamp);
auto macBytes = macStringToBytes(buttonId.c_str());
if (learningMode) {
@@ -77,27 +76,30 @@ void readButtonJSON(const char * topic, const char * payload) {
}
// Button-Zuordnung prüfen und entsprechende Aktion ausführen
if (memcmp(macBytes.data(), buttonConfigs.start1.mac, 6) == 0 && (pressType == 2)) {
if (memcmp(macBytes.data(), buttonConfigs.start1.mac, 6) == 0 &&
(pressType == 2)) {
handleStart1(timestamp);
} else if (memcmp(macBytes.data(), buttonConfigs.stop1.mac, 6) == 0 && (pressType == 1)) {
} else if (memcmp(macBytes.data(), buttonConfigs.stop1.mac, 6) == 0 &&
(pressType == 1)) {
handleStop1(timestamp);
} else if (memcmp(macBytes.data(), buttonConfigs.start2.mac, 6) == 0 && (pressType == 2)) {
} else if (memcmp(macBytes.data(), buttonConfigs.start2.mac, 6) == 0 &&
(pressType == 2)) {
handleStart2(timestamp);
} else if (memcmp(macBytes.data(), buttonConfigs.stop2.mac, 6) == 0 && (pressType == 1)) {
} else if (memcmp(macBytes.data(), buttonConfigs.stop2.mac, 6) == 0 &&
(pressType == 1)) {
handleStop2(timestamp);
}
// Flash status LED to indicate received message
updateStatusLED(3);
}
void handleHeartbeatTopic(const char* topic, const char* payload) {
void handleHeartbeatTopic(const char *topic, const char *payload) {
// Topic-Format: heartbeat/alive/CC:DB:A7:2F:95:08
String topicStr(topic);
int lastSlash = topicStr.lastIndexOf('/');
if (lastSlash < 0) return;
if (lastSlash < 0)
return;
String macStr = topicStr.substring(lastSlash + 1);
auto macBytes = macStringToBytes(macStr.c_str());
@@ -116,7 +118,8 @@ void handleHeartbeatTopic(const char* topic, const char* payload) {
// Parse payload for timestamp (optional, falls im Payload enthalten)
uint64_t timestamp = millis();
StaticJsonDocument<128> payloadDoc;
if (payload && strlen(payload) > 0 && deserializeJson(payloadDoc, payload) == DeserializationError::Ok) {
if (payload && strlen(payload) > 0 &&
deserializeJson(payloadDoc, payload) == DeserializationError::Ok) {
if (payloadDoc.containsKey("timestamp")) {
timestamp = payloadDoc["timestamp"];
}
@@ -130,15 +133,17 @@ void handleHeartbeatTopic(const char* topic, const char* payload) {
String json;
serializeJson(doc, json);
pushUpdateToFrontend(json); // Diese Funktion schickt das JSON an alle WebSocket-Clients
//Serial.printf("Published heartbeat JSON: %s\n", json.c_str());
pushUpdateToFrontend(
json); // Diese Funktion schickt das JSON an alle WebSocket-Clients
// Serial.printf("Published heartbeat JSON: %s\n", json.c_str());
}
void handleBatteryTopic(const char* topic, const char* payload) {
void handleBatteryTopic(const char *topic, const char *payload) {
int batteryLevel = 0;
String topicStr(topic);
int lastSlash = topicStr.lastIndexOf('/');
if (lastSlash < 0) return;
if (lastSlash < 0)
return;
String macStr = topicStr.substring(lastSlash + 1);
auto macBytes = macStringToBytes(macStr.c_str());
@@ -156,15 +161,18 @@ void handleBatteryTopic(const char* topic, const char* payload) {
// Parse payload for timestamp (optional, falls im Payload enthalten)
StaticJsonDocument<128> payloadDoc;
if (payload && strlen(payload) > 0 && deserializeJson(payloadDoc, payload) == DeserializationError::Ok) {
if (payload && strlen(payload) > 0 &&
deserializeJson(payloadDoc, payload) == DeserializationError::Ok) {
if (payloadDoc.containsKey("voltage")) {
batteryLevel = payloadDoc["voltage"];
}
}
//Berechne die Prozentzahl des Batteriestands für eine 1S LIPO batteryLevel sind Volts
// Berechne die Prozentzahl des Batteriestands für eine 1S LIPO batteryLevel
// sind Volts
// Hier wird angenommen, dass 3.7V 100% entspricht und 3.0V 0%
batteryLevel = batteryLevel * 1000; // Umwandlung von V in mV für genauere Berechnung
batteryLevel =
batteryLevel * 1000; // Umwandlung von V in mV für genauere Berechnung
if (batteryLevel < 3200) {
batteryLevel = 0; // 0% bei 3.0V
} else if (batteryLevel > 3700) {
@@ -181,19 +189,18 @@ void handleBatteryTopic(const char* topic, const char* payload) {
String json;
serializeJson(doc, json);
pushUpdateToFrontend(json); // Diese Funktion schickt das JSON an alle WebSocket-Clients
//Serial.printf("Published heartbeat JSON: %s\n", json.c_str());
pushUpdateToFrontend(
json); // Diese Funktion schickt das JSON an alle WebSocket-Clients
// Serial.printf("Published heartbeat JSON: %s\n", json.c_str());
}
void readRFIDfromButton(const char * topic, const char * payload) {
void readRFIDfromButton(const char *topic, const char *payload) {
// Create a JSON document to hold the button press data
StaticJsonDocument<256> doc;
DeserializationError error = deserializeJson(doc, payload);
if (!error) {
const char* mac = doc["buttonmac"] | "unknown";
const char* uid = doc["uid"] | "unknown";
const char *mac = doc["buttonmac"] | "unknown";
const char *uid = doc["uid"] | "unknown";
Serial.printf("RFID Read from Button:\n");
Serial.printf(" Button MAC: %s\n", mac);
@@ -209,8 +216,7 @@ void readRFIDfromButton(const char * topic, const char * payload) {
if (userData.exists) {
// Log user data
Serial.printf("User found for start1: %s %s, Alter: %d\n",
userData.firstname.c_str(),
userData.lastname.c_str(),
userData.firstname.c_str(), userData.lastname.c_str(),
userData.alter);
// Create JSON message to send to the frontend
@@ -224,7 +230,8 @@ void readRFIDfromButton(const char * topic, const char * payload) {
// Push the message to the frontend
pushUpdateToFrontend(message);
Serial.printf("Pushed user data for start1 to frontend: %s\n", message.c_str());
Serial.printf("Pushed user data for start1 to frontend: %s\n",
message.c_str());
} else {
Serial.println("User not found for UID: " + String(uid));
}
@@ -236,8 +243,7 @@ void readRFIDfromButton(const char * topic, const char * payload) {
if (userData.exists) {
// Log user data
Serial.printf("User found for start2: %s %s, Alter: %d\n",
userData.firstname.c_str(),
userData.lastname.c_str(),
userData.firstname.c_str(), userData.lastname.c_str(),
userData.alter);
// Create JSON message to send to the frontend
@@ -251,7 +257,8 @@ void readRFIDfromButton(const char * topic, const char * payload) {
// Push the message to the frontend
pushUpdateToFrontend(message);
Serial.printf("Pushed user data for start2 to frontend: %s\n", message.c_str());
Serial.printf("Pushed user data for start2 to frontend: %s\n",
message.c_str());
} else {
Serial.println("User not found for UID: " + String(uid));
}
@@ -267,20 +274,17 @@ void setupMqttServer() {
// Set up the MQTT server with the desired port
// Subscribe to a topic pattern and attach a callback
mqtt.subscribe("#", [](const char * topic, const char * payload) {
//Message received callback
//Serial.printf("Received message on topic '%s': %s\n", topic, payload);
mqtt.subscribe("#", [](const char *topic, const char *payload) {
// Message received callback
// Serial.printf("Received message on topic '%s': %s\n", topic, payload);
if (strncmp(topic, "aquacross/button/", 17) == 0) {
readButtonJSON(topic, payload);
}
else if (strncmp(topic, "aquacross/button/rfid/", 22) == 0) {
} else if (strncmp(topic, "aquacross/button/rfid/", 22) == 0) {
readRFIDfromButton(topic, payload);
// Handle RFID read messages
}
else if (strncmp(topic, "aquacross/battery/", 17) == 0) {
} else if (strncmp(topic, "aquacross/battery/", 17) == 0) {
handleBatteryTopic(topic, payload);
}
else if (strncmp(topic, "heartbeat/alive/", 16) == 0) {
} else if (strncmp(topic, "heartbeat/alive/", 16) == 0) {
handleHeartbeatTopic(topic, payload);
}
updateStatusLED(3);
@@ -292,8 +296,6 @@ void setupMqttServer() {
Serial.println("MQTT server started on port 1883");
}
void loopMqttServer() {
mqtt.loop();
@@ -305,16 +307,15 @@ void loopMqttServer() {
mqtt.publish("sync/time", timeStr);
lastPublish = millis();
}
}
void sendMQTTMessage(const char * topic, const char * message) {
void sendMQTTMessage(const char *topic, const char *message) {
// Publish a message to the specified topic
mqtt.publish(topic, message);
Serial.printf("Published message to topic '%s': %s\n", topic, message);
}
void sendMQTTJSONMessage(const char * topic, const JsonDocument & doc) {
void sendMQTTJSONMessage(const char *topic, const JsonDocument &doc) {
String jsonString;
serializeJson(doc, jsonString);
@@ -322,8 +323,6 @@ void sendMQTTJSONMessage(const char * topic, const JsonDocument & doc) {
auto publish = mqtt.begin_publish(topic, measureJson(doc));
serializeJson(doc, publish);
publish.send();
Serial.printf("Published JSON message to topic '%s': %s\n", topic, jsonString.c_str());
Serial.printf("Published JSON message to topic '%s': %s\n", topic,
jsonString.c_str());
}

View File

@@ -1,12 +1,11 @@
#pragma once
#include "master.h"
#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
const char *BACKEND_SERVER = "http://db.reptilfpv.de:3000";
String BACKEND_TOKEN =
licence; // Use the licence as the token for authentication
bool backendOnline() {
@@ -42,8 +41,9 @@ struct UserData {
bool exists;
};
// UserData checkUser(const String& uid) is defined only once to avoid redefinition errors.
UserData checkUser(const String& uid) {
// UserData checkUser(const String& uid) is defined only once to avoid
// redefinition errors.
UserData checkUser(const String &uid) {
UserData userData = {"", "", "", 0, false};
@@ -85,8 +85,10 @@ UserData checkUser(const String& uid) {
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) {
// 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;
@@ -151,17 +153,13 @@ JsonDocument getAllLocations() {
}
// Keep this for backward compatibility
bool userExists(const String& uid) {
return checkUser(uid).exists;
}
bool userExists(const String &uid) { return checkUser(uid).exists; }
// Routes from the Frontend into here and then into DB backend.
//Routes from the Frontend into here and then into DB backend.
void setupBackendRoutes(AsyncWebServer& server) {
void setupBackendRoutes(AsyncWebServer &server) {
server.on("/api/health", HTTP_GET, [](AsyncWebServerRequest *request) {
DynamicJsonDocument doc(64);
doc["status"] = backendOnline() ? "connected" : "disconnected";
String response;
@@ -171,21 +169,19 @@ void setupBackendRoutes(AsyncWebServer& server) {
server.on("/api/users", HTTP_GET, [](AsyncWebServerRequest *request) {
if (!backendOnline()) {
request->send(503, "application/json", "{\"error\":\"Database not connected\"}");
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){
// 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
}

View File

@@ -1,49 +1,41 @@
// Zeit-bezogene Variablen und Includes
#pragma once
#include <Arduino.h>
#include <master.h>
#include <ESPAsyncWebServer.h>
#include <ArduinoJson.h>
#include <time.h>
#include <ESPAsyncWebServer.h>
#include <master.h>
#include <sys/time.h>
#include <time.h>
#include "communication.h"
void setupDebugAPI(AsyncWebServer &server);
void setupDebugAPI(AsyncWebServer &server) {
void setupDebugAPI(AsyncWebServer& server);
void setupDebugAPI(AsyncWebServer& server) {
//DEBUG
server.on("/api/debug/start1", HTTP_GET, [](AsyncWebServerRequest *request){
// DEBUG
server.on("/api/debug/start1", HTTP_GET, [](AsyncWebServerRequest *request) {
handleStart1(0);
request->send(200, "text/plain", "handleStart1() called");
});
});
server.on("/api/debug/stop1", HTTP_GET, [](AsyncWebServerRequest *request){
server.on("/api/debug/stop1", HTTP_GET, [](AsyncWebServerRequest *request) {
handleStop1(0);
request->send(200, "text/plain", "handleStop1() called");
});
});
server.on("/api/debug/start2", HTTP_GET, [](AsyncWebServerRequest *request){
server.on("/api/debug/start2", HTTP_GET, [](AsyncWebServerRequest *request) {
handleStart2(0);
request->send(200, "text/plain", "handleStart2() called");
});
});
server.on("/api/debug/stop2", HTTP_GET, [](AsyncWebServerRequest *request){
server.on("/api/debug/stop2", HTTP_GET, [](AsyncWebServerRequest *request) {
handleStop2(0);
request->send(200, "text/plain", "handleStop2() called");
});
});
Serial.println("Debug-API initialisiert");
Serial.println("Debug-API initialisiert");
}
//DEBUG END
// DEBUG END

View File

@@ -1,10 +1,11 @@
#pragma once
#include <Arduino.h>
#include "master.h"
#include <Arduino.h>
std::array<uint8_t, 6> macStringToBytes(const char* macStr) {
std::array<uint8_t, 6> macStringToBytes(const char *macStr) {
std::array<uint8_t, 6> bytes;
sscanf(macStr, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
&bytes[0], &bytes[1], &bytes[2], &bytes[3], &bytes[4], &bytes[5]);
sscanf(macStr, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", &bytes[0], &bytes[1],
&bytes[2], &bytes[3], &bytes[4], &bytes[5]);
return bytes;
}

View File

@@ -1,47 +1,49 @@
#pragma once
#include "mbedtls/md.h"
#include <Arduino.h>
#include <ArduinoJson.h>
#include <ESPAsyncWebServer.h>
#include <Preferences.h>
#include <esp_wifi.h>
#include <master.h>
#include <Preferences.h>
#include <ArduinoJson.h>
#include "mbedtls/md.h"
const char* secret = "542ff224606c61fb3024e22f76ef9ac8";
const char *secret = "542ff224606c61fb3024e22f76ef9ac8";
// Preferences für persistente Speicherung
Preferences preferences;
String licence;
//Prototype für Funktionen
// Prototype für Funktionen
String getUniqueDeviceID();
String hmacSHA256(const String& key, const String& message);
bool checkLicense(const String& deviceID, const String& licenseKey);
void setupLicenceAPI(AsyncWebServer& server);
String hmacSHA256(const String &key, const String &message);
bool checkLicense(const String &deviceID, const String &licenseKey);
void setupLicenceAPI(AsyncWebServer &server);
void saveLicenceToPrefs();
void loadLicenceFromPrefs();
String getUniqueDeviceID() {
uint8_t mac[6];
esp_wifi_get_mac(WIFI_IF_STA, mac); // Use STA MAC for uniqueness
char id[13];
sprintf(id, "%02X%02X%02X%02X%02X%02X",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
sprintf(id, "%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3],
mac[4], mac[5]);
return String(id);
}
String hmacSHA256(const String& key, const String& message) {
String hmacSHA256(const String &key, const String &message) {
byte hmacResult[32];
mbedtls_md_context_t ctx;
mbedtls_md_type_t md_type = MBEDTLS_MD_SHA256;
mbedtls_md_init(&ctx);
const mbedtls_md_info_t* md_info = mbedtls_md_info_from_type(md_type);
const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(md_type);
mbedtls_md_setup(&ctx, md_info, 1);
mbedtls_md_hmac_starts(&ctx, (const unsigned char*)key.c_str(), key.length());
mbedtls_md_hmac_update(&ctx, (const unsigned char*)message.c_str(), message.length());
mbedtls_md_hmac_starts(&ctx, (const unsigned char *)key.c_str(),
key.length());
mbedtls_md_hmac_update(&ctx, (const unsigned char *)message.c_str(),
message.length());
mbedtls_md_hmac_finish(&ctx, hmacResult);
mbedtls_md_free(&ctx);
@@ -54,7 +56,7 @@ String hmacSHA256(const String& key, const String& message) {
return result;
}
int getLicenseTier(const String& deviceID, const String& licenseKey) {
int getLicenseTier(const String &deviceID, const String &licenseKey) {
for (int tier = 1; tier <= 4; ++tier) {
String data = deviceID + ":" + String(tier);
String expected = hmacSHA256(secret, data);
@@ -65,20 +67,22 @@ int getLicenseTier(const String& deviceID, const String& licenseKey) {
return 0; // No valid tier found
}
void setupLicenceAPI(AsyncWebServer& server) {
void setupLicenceAPI(AsyncWebServer &server) {
server.on("/api/get-licence", HTTP_GET, [](AsyncWebServerRequest *request){
server.on("/api/get-licence", HTTP_GET, [](AsyncWebServerRequest *request) {
Serial.println("Received request to get licence");
loadLicenceFromPrefs();
String deviceID = getUniqueDeviceID();
int tier = getLicenseTier(deviceID, licence);
String json = "{\"licence\":\"" + licence + "\","
"\"valid\":" + String(tier > 0 ? "true" : "false") +
String json = "{\"licence\":\"" + licence +
"\","
"\"valid\":" +
String(tier > 0 ? "true" : "false") +
",\"tier\":" + String(tier) + "}";
request->send(200, "application/json", json);
});
server.on("/api/set-licence", HTTP_POST, [](AsyncWebServerRequest *request){
server.on("/api/set-licence", HTTP_POST, [](AsyncWebServerRequest *request) {
Serial.println("Received request to set licence");
if (request->hasParam("licence", true)) {
licence = request->getParam("licence", true)->value();

View File

@@ -1,28 +1,30 @@
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#include <Arduino.h>
#include "master.h"
#include <Arduino.h>
// Aquacross Timer - ESP32 Master (Webserver + ESP-NOW + Anlernmodus)
#include <ESPAsyncWebServer.h>
#include <SPIFFS.h>
#include <esp_now.h>
#include <ArduinoJson.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <Preferences.h>
#include <PrettyOTA.h>
#include <SPIFFS.h>
#include <esp_now.h>
#include <esp_wifi.h>
#include <AsyncTCP.h>
#include <timesync.h>
#include <licenceing.h>
#include <debug.h>
#include <wificlass.h>
#include <webserverrouter.h>
#include <communication.h>
#include <databasebackend.h>
#include <debug.h>
#include <licenceing.h>
#include <rfid.h>
#include <timesync.h>
#include <webserverrouter.h>
#include <wificlass.h>
const char* firmwareversion = "1.0.0"; // Version der Firmware
const char *firmwareversion = "1.0.0"; // Version der Firmware
void handleStart1(uint64_t timestamp = 0) {
if (!timerData.isRunning1 && timerData.isReady1) {
@@ -46,7 +48,8 @@ void handleStop1(uint64_t timestamp = 0) {
timerData.bestTime1 = currentTime;
saveBestTimes();
}
Serial.println("Bahn 1 gestoppt - Zeit: " + String(currentTime/1000.0) + "s");
Serial.println("Bahn 1 gestoppt - Zeit: " + String(currentTime / 1000.0) +
"s");
}
}
@@ -72,27 +75,31 @@ void handleStop2(uint64_t timestamp = 0) {
timerData.bestTime2 = currentTime;
saveBestTimes();
}
Serial.println("Bahn 2 gestoppt - Zeit: " + String(currentTime/1000.0) + "s");
Serial.println("Bahn 2 gestoppt - Zeit: " + String(currentTime / 1000.0) +
"s");
}
}
void checkAutoReset() {
unsigned long currentTime = millis();
if (timerData.isRunning1 && (currentTime - timerData.localStartTime1 > maxTimeBeforeReset)) {
if (timerData.isRunning1 &&
(currentTime - timerData.localStartTime1 > maxTimeBeforeReset)) {
timerData.isRunning1 = false;
timerData.startTime1 = 0;
Serial.println("Bahn 1 automatisch zurückgesetzt");
}
if (timerData.isRunning2 && (currentTime - timerData.localStartTime2 > maxTimeBeforeReset)) {
if (timerData.isRunning2 &&
(currentTime - timerData.localStartTime2 > maxTimeBeforeReset)) {
timerData.isRunning2 = false;
timerData.startTime2 = 0;
Serial.println("Bahn 2 automatisch zurückgesetzt");
}
// Automatischer Reset nach 10 Sekunden "Beendet"
if (!timerData.isRunning1 && timerData.endTime1 > 0 && timerData.finishedSince1 > 0) {
if (!timerData.isRunning1 && timerData.endTime1 > 0 &&
timerData.finishedSince1 > 0) {
if (millis() - timerData.finishedSince1 > maxTimeDisplay) {
timerData.startTime1 = 0;
timerData.endTime1 = 0;
@@ -100,7 +107,7 @@ void checkAutoReset() {
timerData.isReady1 = true; // Zurücksetzen auf "Bereit"
JsonDocument messageDoc;
messageDoc["firstname"] ="";
messageDoc["firstname"] = "";
messageDoc["lastname"] = "";
messageDoc["lane"] = "start1"; // Add lane information
@@ -114,7 +121,8 @@ void checkAutoReset() {
}
}
if (!timerData.isRunning2 && timerData.endTime2 > 0 && timerData.finishedSince2 > 0) {
if (!timerData.isRunning2 && timerData.endTime2 > 0 &&
timerData.finishedSince2 > 0) {
if (currentTime - timerData.finishedSince2 > maxTimeDisplay) {
timerData.startTime2 = 0;
timerData.endTime2 = 0;
@@ -132,7 +140,6 @@ void checkAutoReset() {
// Push the message to the frontend
pushUpdateToFrontend(message);
Serial.println("Bahn 2 automatisch auf 'Bereit' zurückgesetzt");
}
}
@@ -211,10 +218,6 @@ void loadWifiSettings() {
preferences.end();
}
int checkLicence() {
loadLicenceFromPrefs();
String id = getUniqueDeviceID();
@@ -257,7 +260,8 @@ String getTimerDataJSON() {
// Lernmodus
doc["learningMode"] = learningMode;
if (learningMode) {
String buttons[] = {"Start Bahn 1", "Stop Bahn 1", "Start Bahn 2", "Stop Bahn 2"};
String buttons[] = {"Start Bahn 1", "Stop Bahn 1", "Start Bahn 2",
"Stop Bahn 2"};
doc["learningButton"] = buttons[learningStep];
}
@@ -266,24 +270,21 @@ String getTimerDataJSON() {
return result;
}
void setup() {
Serial.begin(115200);
if (!SPIFFS.begin(true)) {
Serial.println("SPIFFS Mount Failed");
return;
}
//setup API libararies
// setup API libararies
setupTimeAPI(server);
setupLicenceAPI(server);
setupDebugAPI(server);
setupBackendRoutes(server);
setupRFIDRoute(server);
// Gespeicherte Daten laden
loadButtonConfig();
loadBestTimes();
@@ -299,8 +300,6 @@ void setup() {
setupLED();
setupMqttServer(); // MQTT Server initialisieren
setupRFID();
}
void loop() {

View File

@@ -1,15 +1,16 @@
#pragma once
#include <Arduino.h>
#include <ESPAsyncWebServer.h>
#include <ArduinoJson.h>
#include <time.h>
#include <ESPAsyncWebServer.h>
#include <sys/time.h>
#include <time.h>
const char* ssidAP;
const char* passwordAP = nullptr;
char* ssidSTA = nullptr;
char* passwordSTA = nullptr;
const char *ssidAP;
const char *passwordAP = nullptr;
char *ssidSTA = nullptr;
char *passwordSTA = nullptr;
// Timer Struktur
struct TimerData {
@@ -42,7 +43,7 @@ struct ButtonConfigs {
ButtonConfig stop2;
};
extern const char* firmwareversion;
extern const char *firmwareversion;
// Globale Variablen
TimerData timerData;
@@ -54,9 +55,9 @@ unsigned long maxTimeDisplay = 20000; // 20 Sekunden Standard (in ms)
bool wifimodeAP = false; // AP-Modus deaktiviert
String masterlocation;
//Function Declarations
void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len);
void handleLearningMode(const uint8_t* mac);
// Function Declarations
void OnDataRecv(const uint8_t *mac, const uint8_t *incomingData, int len);
void handleLearningMode(const uint8_t *mac);
void handleStartLearning();
void handleStart1(uint64_t timestamp);
void handleStop1(uint64_t timestamp);

View File

@@ -1,16 +1,17 @@
#pragma once
#include <Arduino.h>
#include <ArduinoJson.h>
#include <SPI.h>
#include <MFRC522.h>
#include <SPI.h>
// RFID Konfiguration
#define RST_PIN 21 // Configurable, see typical pin layout above
#define SS_PIN 5 // Configurable, see typical pin layout above
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
std::map<String, unsigned long> blockedUIDs; // Map to store blocked UIDs and their timestamps
std::map<String, unsigned long>
blockedUIDs; // Map to store blocked UIDs and their timestamps
const unsigned long BLOCK_DURATION = 10 * 1000; // 10 Seconds in milliseconds
// Neue Variablen für API-basiertes Lesen
@@ -18,8 +19,8 @@ bool rfidReadRequested = false;
String lastReadUID = "";
bool rfidReadSuccess = false;
unsigned long rfidReadStartTime = 0;
const unsigned long RFID_READ_TIMEOUT = 10000; // 10 Sekunden Timeout für API Requests
const unsigned long RFID_READ_TIMEOUT =
10000; // 10 Sekunden Timeout für API Requests
void setupRFID() {
@@ -27,11 +28,10 @@ void setupRFID() {
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522
delay(4); // Optional delay. Some boards need more time after init to be ready
mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card
// Reader details
}
void handleAutomaticRFID() {
if (!mfrc522.PICC_IsNewCardPresent()) {
return;
@@ -73,7 +73,7 @@ void handleAutomaticRFID() {
// Block the UID for 10 seconds
blockedUIDs[uid] = currentTime;
//show the remaining time for the block
// show the remaining time for the block
Serial.print(F("UID blocked for 10 seconds. Remaining time: "));
Serial.print((BLOCK_DURATION - (currentTime - blockedUIDs[uid])) / 1000);
Serial.println(F(" seconds."));
@@ -139,17 +139,15 @@ void startRFIDRead() {
}
// API Funktion: Prüfen ob Lesevorgang abgeschlossen
bool isRFIDReadComplete() {
return !rfidReadRequested;
}
bool isRFIDReadComplete() { return !rfidReadRequested; }
// API Funktion: Ergebnis des Lesevorgangs abrufen
String getRFIDReadResult(bool& success) {
String getRFIDReadResult(bool &success) {
success = rfidReadSuccess;
return lastReadUID;
}
void setupRFIDRoute(AsyncWebServer& server) {
void setupRFIDRoute(AsyncWebServer &server) {
server.on("/api/rfid/read", HTTP_GET, [](AsyncWebServerRequest *request) {
Serial.println("api/rfid/read");
@@ -182,7 +180,11 @@ void setupRFIDRoute(AsyncWebServer& server) {
request->send(200, "application/json", jsonString);
});
server.on("/api/users/insert", HTTP_POST, [](AsyncWebServerRequest *request) {}, NULL, [](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) {
server.on(
"/api/users/insert", HTTP_POST, [](AsyncWebServerRequest *request) {},
NULL,
[](AsyncWebServerRequest *request, uint8_t *data, size_t len,
size_t index, size_t total) {
Serial.println("/api/users/insert");
// Parse the incoming JSON payload
@@ -204,7 +206,8 @@ server.on("/api/users/insert", HTTP_POST, [](AsyncWebServerRequest *request) {},
int alter = doc["alter"] | 0;
// Validate the data
if (uid.isEmpty() || vorname.isEmpty() || nachname.isEmpty() || geburtsdatum.isEmpty() || alter <= 0) {
if (uid.isEmpty() || vorname.isEmpty() || nachname.isEmpty() ||
geburtsdatum.isEmpty() || alter <= 0) {
Serial.println("Ungültige Eingabedaten");
response["success"] = false;
response["error"] = "Ungültige Eingabedaten";
@@ -216,7 +219,8 @@ server.on("/api/users/insert", HTTP_POST, [](AsyncWebServerRequest *request) {},
Serial.println("Nachname: " + nachname);
Serial.println("Alter: " + String(alter));
bool dbSuccess = enterUserData(uid, vorname, nachname, geburtsdatum, alter);
bool dbSuccess =
enterUserData(uid, vorname, nachname, geburtsdatum, alter);
if (dbSuccess) {
response["success"] = true;
@@ -232,11 +236,9 @@ server.on("/api/users/insert", HTTP_POST, [](AsyncWebServerRequest *request) {},
String jsonString;
serializeJson(response, jsonString);
request->send(200, "application/json", jsonString);
});
});
}
// API Funktion: RFID Reader Status prüfen
bool checkRFIDReaderStatus() {
byte version = mfrc522.PCD_ReadRegister(mfrc522.VersionReg);
@@ -246,7 +248,8 @@ bool checkRFIDReaderStatus() {
Serial.println("RFID Reader OK (Version: 0x" + String(version, HEX) + ")");
return true;
} else {
Serial.println("RFID Reader Fehler (Version: 0x" + String(version, HEX) + ")");
Serial.println("RFID Reader Fehler (Version: 0x" + String(version, HEX) +
")");
return false;
}
}
@@ -265,7 +268,7 @@ void cleanupBlockedUIDs() {
}
}
void loopRFID(){
void loopRFID() {
// Originale Funktionalität für automatisches Lesen
if (!rfidReadRequested) {
handleAutomaticRFID();
@@ -276,5 +279,3 @@ void loopRFID(){
handleAPIRFIDRead();
}
}

View File

@@ -1,6 +1,5 @@
#include <Arduino.h>
#define LED_PIN 13
// Status LED
@@ -52,7 +51,6 @@ void updateStatusLED(int blinkPattern) {
digitalWrite(LED_PIN, HIGH);
delay(100);
digitalWrite(LED_PIN, LOW);
}
break;
} break;
}
}

View File

@@ -1,12 +1,13 @@
// Zeit-bezogene Variablen und Includes
#pragma once
#include <Arduino.h>
#include <ESPAsyncWebServer.h>
#include <ArduinoJson.h>
#include <time.h>
#include <sys/time.h>
#include <Wire.h>
#include "RTClib.h"
#include <Arduino.h>
#include <ArduinoJson.h>
#include <ESPAsyncWebServer.h>
#include <Wire.h>
#include <sys/time.h>
#include <time.h>
RTC_PCF8523 rtc;
@@ -16,8 +17,8 @@ struct timezone tz;
time_t now;
struct tm timeinfo;
//Prototypen für Zeit-Management-Funktionen
void setupTimeAPI(AsyncWebServer& server);
// Prototypen für Zeit-Management-Funktionen
void setupTimeAPI(AsyncWebServer &server);
String getCurrentTimeJSON();
bool setSystemTime(long timestamp);
@@ -61,18 +62,18 @@ bool setSystemTime(long timestamp) {
}
}
void setupTimeAPI(AsyncWebServer& server) {
void setupTimeAPI(AsyncWebServer &server) {
//setupRTC();
// setupRTC();
// API-Endpunkt: Aktuelle Zeit abrufen
server.on("/api/time", HTTP_GET, [](AsyncWebServerRequest *request){
// API-Endpunkt: Aktuelle Zeit abrufen
server.on("/api/time", HTTP_GET, [](AsyncWebServerRequest *request) {
String response = getCurrentTimeJSON();
request->send(200, "application/json", response);
});
});
// API-Endpunkt: Zeit setzen
server.on("/api/set-time", HTTP_POST, [](AsyncWebServerRequest *request){
// API-Endpunkt: Zeit setzen
server.on("/api/set-time", HTTP_POST, [](AsyncWebServerRequest *request) {
StaticJsonDocument<100> doc;
if (request->hasParam("timestamp", true)) {
@@ -101,21 +102,20 @@ server.on("/api/set-time", HTTP_POST, [](AsyncWebServerRequest *request){
String response;
serializeJson(doc, response);
request->send(200, "application/json", response);
});
});
// Alternative Implementierung für manuelle Datum/Zeit-Eingabe
server.on("/api/set-datetime", HTTP_POST, [](AsyncWebServerRequest *request){
// Alternative Implementierung für manuelle Datum/Zeit-Eingabe
server.on("/api/set-datetime", HTTP_POST, [](AsyncWebServerRequest *request) {
StaticJsonDocument<150> doc;
if (request->hasParam("year", true) &&
request->hasParam("month", true) &&
request->hasParam("day", true) &&
request->hasParam("hour", true) &&
if (request->hasParam("year", true) && request->hasParam("month", true) &&
request->hasParam("day", true) && request->hasParam("hour", true) &&
request->hasParam("minute", true) &&
request->hasParam("second", true)) {
struct tm timeinfo;
timeinfo.tm_year = request->getParam("year", true)->value().toInt() - 1900;
timeinfo.tm_year =
request->getParam("year", true)->value().toInt() - 1900;
timeinfo.tm_mon = request->getParam("month", true)->value().toInt() - 1;
timeinfo.tm_mday = request->getParam("day", true)->value().toInt();
timeinfo.tm_hour = request->getParam("hour", true)->value().toInt();
@@ -146,10 +146,10 @@ server.on("/api/set-datetime", HTTP_POST, [](AsyncWebServerRequest *request){
String response;
serializeJson(doc, response);
request->send(200, "application/json", response);
});
});
// Erweiterte Zeit-Informationen (optional)
server.on("/api/time/info", HTTP_GET, [](AsyncWebServerRequest *request){
// Erweiterte Zeit-Informationen (optional)
server.on("/api/time/info", HTTP_GET, [](AsyncWebServerRequest *request) {
gettimeofday(&tv, &tz);
now = tv.tv_sec;
gmtime_r(&now, &timeinfo);
@@ -180,18 +180,25 @@ server.on("/api/time/info", HTTP_GET, [](AsyncWebServerRequest *request){
String response;
serializeJson(doc, response);
request->send(200, "application/json", response);
});
Serial.println("Zeit-API initialisiert");
});
Serial.println("Zeit-API initialisiert");
}
// Hilfsfunktion: Zeit-Validierung
bool isValidDateTime(int year, int month, int day, int hour, int minute, int second) {
if (year < 2020 || year > 2099) return false;
if (month < 1 || month > 12) return false;
if (day < 1 || day > 31) return false;
if (hour < 0 || hour > 23) return false;
if (minute < 0 || minute > 59) return false;
if (second < 0 || second > 59) return false;
bool isValidDateTime(int year, int month, int day, int hour, int minute,
int second) {
if (year < 2020 || year > 2099)
return false;
if (month < 1 || month > 12)
return false;
if (day < 1 || day > 31)
return false;
if (hour < 0 || hour > 23)
return false;
if (minute < 0 || minute > 59)
return false;
if (second < 0 || second > 59)
return false;
// Erweiterte Validierung für Monatstage
int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

View File

@@ -1,33 +1,35 @@
#pragma once
#include <Arduino.h>
void sendMQTTMessage(const char * topic, const char * message);
void sendMQTTMessage(const char *topic, const char *message);
#include "master.h"
#include <ESPAsyncWebServer.h>
#include <AsyncWebSocket.h>
#include <ArduinoJson.h>
#include <AsyncWebSocket.h>
#include <ESPAsyncWebServer.h>
#include <SPIFFS.h>
#include <esp_wifi.h>
#include "communication.h"
#include <buttonassigh.h>
#include <wificlass.h>
#include "communication.h"
AsyncWebServer server(80);
AsyncWebSocket ws("/ws");
void setupRoutes(){
void setupRoutes() {
// Web Server Routes
// Attach WebSocket to the server
server.addHandler(&ws);
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(SPIFFS, "/index.html", "text/html");
});
server.on("/settings", HTTP_GET, [](AsyncWebServerRequest *request){
server.on("/settings", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(SPIFFS, "/settings.html", "text/html");
});
@@ -43,13 +45,13 @@ void setupRoutes(){
request->send(404, "application/json", "{\"error\":\"File not found\"}");
Serial.println("Firmware file not found: /firmware.bin");
}
});
});
server.on("/api/data", HTTP_GET, [](AsyncWebServerRequest *request){
server.on("/api/data", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(200, "application/json", getTimerDataJSON());
});
server.on("/api/reset-best", HTTP_POST, [](AsyncWebServerRequest *request){
server.on("/api/reset-best", HTTP_POST, [](AsyncWebServerRequest *request) {
Serial.println("/api/reset-best called");
timerData.bestTime1 = 0;
timerData.bestTime2 = 0;
@@ -61,23 +63,24 @@ void setupRoutes(){
request->send(200, "application/json", result);
});
server.on("/api/unlearn-button", HTTP_POST, [](AsyncWebServerRequest *request){
server.on("/api/unlearn-button", HTTP_POST,
[](AsyncWebServerRequest *request) {
Serial.println("/api/unlearn-button called");
unlearnButton();
request->send(200, "application/json", "{\"success\":true}");
});
});
server.on("/api/set-max-time", HTTP_POST, [](AsyncWebServerRequest *request){
server.on("/api/set-max-time", HTTP_POST, [](AsyncWebServerRequest *request) {
Serial.println("/api/set-max-time called");
bool changed = false;
if (request->hasParam("maxTime", true)) {
maxTimeBeforeReset = request->getParam("maxTime", true)->value().toInt() * 1000;
maxTimeBeforeReset =
request->getParam("maxTime", true)->value().toInt() * 1000;
changed = true;
}
if (request->hasParam("maxTimeDisplay", true)) {
maxTimeDisplay = request->getParam("maxTimeDisplay", true)->value().toInt() * 1000;
maxTimeDisplay =
request->getParam("maxTimeDisplay", true)->value().toInt() * 1000;
changed = true;
}
if (changed) {
@@ -92,7 +95,7 @@ void setupRoutes(){
}
});
server.on("/api/get-settings", HTTP_GET, [](AsyncWebServerRequest *request){
server.on("/api/get-settings", HTTP_GET, [](AsyncWebServerRequest *request) {
Serial.println("/api/get-settings called");
DynamicJsonDocument doc(256);
doc["maxTime"] = maxTimeBeforeReset / 1000;
@@ -102,7 +105,8 @@ void setupRoutes(){
request->send(200, "application/json", result);
});
server.on("/api/start-learning", HTTP_POST, [](AsyncWebServerRequest *request){
server.on("/api/start-learning", HTTP_POST,
[](AsyncWebServerRequest *request) {
Serial.println("/api/start-learning called");
learningMode = true;
learningStep = 0;
@@ -112,9 +116,10 @@ void setupRoutes(){
serializeJson(doc, result);
Serial.println("Learning mode started");
request->send(200, "application/json", result);
});
});
server.on("/api/stop-learning", HTTP_POST, [](AsyncWebServerRequest *request){
server.on("/api/stop-learning", HTTP_POST,
[](AsyncWebServerRequest *request) {
Serial.println("/api/stop-learning called");
learningMode = false;
learningStep = 0;
@@ -126,7 +131,7 @@ void setupRoutes(){
request->send(200, "application/json", result);
});
server.on("/api/learn/status", HTTP_GET, [](AsyncWebServerRequest *request){
server.on("/api/learn/status", HTTP_GET, [](AsyncWebServerRequest *request) {
DynamicJsonDocument doc(256);
doc["active"] = learningMode;
doc["step"] = learningStep;
@@ -135,7 +140,8 @@ void setupRoutes(){
request->send(200, "application/json", response);
});
server.on("/api/buttons/status", HTTP_GET, [](AsyncWebServerRequest *request){
server.on("/api/buttons/status", HTTP_GET,
[](AsyncWebServerRequest *request) {
DynamicJsonDocument doc(128);
doc["lane1Start"] = buttonConfigs.start1.isAssigned;
doc["lane1Stop"] = buttonConfigs.stop1.isAssigned;
@@ -146,7 +152,7 @@ void setupRoutes(){
request->send(200, "application/json", result);
});
server.on("/api/info", HTTP_GET, [](AsyncWebServerRequest *request){
server.on("/api/info", HTTP_GET, [](AsyncWebServerRequest *request) {
DynamicJsonDocument doc(256);
// IP address
@@ -158,7 +164,8 @@ void setupRoutes(){
uint8_t mac[6];
esp_wifi_get_mac(WIFI_IF_STA, mac);
char macStr[18];
sprintf(macStr, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
sprintf(macStr, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2],
mac[3], mac[4], mac[5]);
doc["mac"] = macStr;
// Free memory
@@ -166,20 +173,23 @@ void setupRoutes(){
// Connected buttons (count assigned)
int connected = 0;
if (buttonConfigs.start1.isAssigned) connected++;
if (buttonConfigs.stop1.isAssigned) connected++;
if (buttonConfigs.start2.isAssigned) connected++;
if (buttonConfigs.stop2.isAssigned) connected++;
if (buttonConfigs.start1.isAssigned)
connected++;
if (buttonConfigs.stop1.isAssigned)
connected++;
if (buttonConfigs.start2.isAssigned)
connected++;
if (buttonConfigs.stop2.isAssigned)
connected++;
doc["connectedButtons"] = connected;
doc["valid"] = checkLicence() > 0 ? "Ja" : "Nein";
doc["tier"] = checkLicence() ;
doc["tier"] = checkLicence();
String result;
serializeJson(doc, result);
request->send(200, "application/json", result);
});
});
// Setze WLAN-Name und Passwort (POST)
server.on("/api/set-wifi", HTTP_POST, [](AsyncWebServerRequest *request) {
@@ -209,12 +219,13 @@ void setupRoutes(){
serializeJson(doc, result);
request->send(200, "application/json", result);
} else {
request->send(400, "application/json", "{\"success\":false,\"error\":\"SSID fehlt\"}");
request->send(400, "application/json",
"{\"success\":false,\"error\":\"SSID fehlt\"}");
}
});
});
// Liefert aktuelle WLAN-Einstellungen (GET)
server.on("/api/get-wifi", HTTP_GET, [](AsyncWebServerRequest *request){
server.on("/api/get-wifi", HTTP_GET, [](AsyncWebServerRequest *request) {
DynamicJsonDocument doc(128);
doc["ssid"] = ssidSTA ? ssidSTA : "";
doc["password"] = passwordSTA ? passwordSTA : "";
@@ -223,7 +234,7 @@ void setupRoutes(){
request->send(200, "application/json", result);
});
server.on("/api/set-location", HTTP_POST, [](AsyncWebServerRequest *request) {
server.on("/api/set-location", HTTP_POST, [](AsyncWebServerRequest *request) {
Serial.println("/api/set-location called");
String id, name;
@@ -244,10 +255,9 @@ server.on("/api/set-location", HTTP_POST, [](AsyncWebServerRequest *request) {
String result;
serializeJson(doc, result);
request->send(200, "application/json", result);
});
});
server.on("/api/get-location", HTTP_GET, [](AsyncWebServerRequest *request){
server.on("/api/get-location", HTTP_GET, [](AsyncWebServerRequest *request) {
DynamicJsonDocument doc(128);
loadLocationSettings();
doc["locationid"] = masterlocation ? masterlocation : "";
@@ -256,26 +266,24 @@ server.on("/api/set-location", HTTP_POST, [](AsyncWebServerRequest *request) {
request->send(200, "application/json", result);
});
server.on("/api/updateButtons", HTTP_GET, [](AsyncWebServerRequest *request){
server.on("/api/updateButtons", HTTP_GET, [](AsyncWebServerRequest *request) {
Serial.println("/api/updateButtons called");
// MQTT publish on aquacross/update/flag with raw payload "1"
sendMQTTMessage("aquacross/update/flag", "1");
Serial.println("MQTT published: aquacross/update/flag -> 1");
request->send(200, "application/json", "{\"success\":true}");
});
});
// Statische Dateien
// Statische Dateien
server.serveStatic("/", SPIFFS, "/");
server.begin();
Serial.println("Web Server gestartet");
}
void setupWebSocket() {
ws.onEvent([](AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) {
ws.onEvent([](AsyncWebSocket *server, AsyncWebSocketClient *client,
AwsEventType type, void *arg, uint8_t *data, size_t len) {
if (type == WS_EVT_CONNECT) {
Serial.printf("WebSocket client connected: %u\n", client->id());
} else if (type == WS_EVT_DISCONNECT) {

View File

@@ -1,13 +1,15 @@
#pragma once
#include <Arduino.h>
#include <esp_wifi.h>
#include <PrettyOTA.h>
#include <esp_now.h>
#include <WiFi.h>
#include <ESPmDNS.h> // <-- mDNS hinzufügen
#include <PrettyOTA.h>
#include <WiFi.h>
#include <esp_now.h>
#include <esp_wifi.h>
#include "master.h"
#include "licenceing.h"
#include "master.h"
String uniqueSSID;
@@ -19,13 +21,12 @@ void setupWifi() {
uniqueSSID = getUniqueSSID();
ssidAP = uniqueSSID.c_str();
if (ssidSTA == nullptr || passwordSTA == nullptr || String(ssidSTA).isEmpty() || String(passwordSTA).isEmpty() ) {
if (ssidSTA == nullptr || passwordSTA == nullptr ||
String(ssidSTA).isEmpty() || String(passwordSTA).isEmpty()) {
Serial.println("Fehler: ssidSTA oder passwordSTA ist null!");
WiFi.mode(WIFI_MODE_AP);
WiFi.softAP(ssidAP, passwordAP);
}
else
{
} else {
WiFi.mode(WIFI_MODE_APSTA);
WiFi.begin(ssidSTA, passwordSTA);
@@ -38,29 +39,26 @@ void setupWifi() {
millis() - startAttemptTime < 10000) { // 10 seconds timeout
delay(500);
Serial.print(".");
}
if (WiFi.status() != WL_CONNECTED) {
Serial.println("Fehler: Verbindung zum WLAN fehlgeschlagen!");
Serial.println("Starte Access Point...");
WiFi.mode(WIFI_MODE_AP);
WiFi.softAP(ssidAP, passwordAP);
}
else {
} else {
Serial.println("Erfolgreich mit WLAN verbunden!");
Serial.print("IP Adresse: ");
Serial.println(WiFi.localIP());
}
//Only wait for connection if ssidSTA and passwordSTA are set
// Only wait for connection if ssidSTA and passwordSTA are set
Serial.println("WiFi AP gestartet");
Serial.print("SSID: ");
Serial.println(WiFi.softAPSSID());
Serial.print("IP Adresse: ");
Serial.println(WiFi.softAPIP());
Serial.println("PrettyOTA can be accessed at: http://" + WiFi.softAPIP().toString() + "/update");
Serial.println("PrettyOTA can be accessed at: http://" +
WiFi.softAPIP().toString() + "/update");
// mDNS starten
if (MDNS.begin("aquacross-timer")) { // z.B. http://aquacross-timer.local/
@@ -96,5 +94,4 @@ String getUniqueSSID() {
return String("AquaCross-") + String(uniqueId);
}
// WiFi als Access Point