Remove deprecated HTML files and scripts, refactor API to support asynchronous requests, and improve WebSocket handling for scale actions.
This commit is contained in:
1 parent
823d1f8c7e
commit
13a0acf2ac
20 files changed
+260
-2147
No files matched your search
+130
-78
@@ -12,6 +12,20 @@
|
||||
volatile filamanApiStateType filamanApiState = API_IDLE;
|
||||
bool filamanConnected = false;
|
||||
|
||||
struct ApiRequest {
|
||||
FilamanApiRequestType type;
|
||||
int id1;
|
||||
int id2;
|
||||
String str1;
|
||||
String str2;
|
||||
float val;
|
||||
bool active = false;
|
||||
};
|
||||
|
||||
#define MAX_API_QUEUE 10
|
||||
ApiRequest apiQueue[MAX_API_QUEUE];
|
||||
SemaphoreHandle_t queueMutex;
|
||||
|
||||
void saveFilamanConfig() {
|
||||
Preferences preferences;
|
||||
preferences.begin(NVS_NAMESPACE_API, false);
|
||||
@@ -36,136 +50,174 @@ bool checkFilamanRegistration() {
|
||||
|
||||
bool registerDevice(const String& deviceCode) {
|
||||
if (filamanUrl.length() == 0) return false;
|
||||
|
||||
HTTPClient http;
|
||||
String url = filamanUrl + "/api/v1/devices/register";
|
||||
|
||||
http.begin(url);
|
||||
http.setTimeout(5000);
|
||||
http.begin(filamanUrl + "/api/v1/devices/register");
|
||||
http.addHeader("Content-Type", "application/json");
|
||||
http.addHeader("X-Device-Code", deviceCode);
|
||||
|
||||
int httpCode = http.POST("{}");
|
||||
bool success = false;
|
||||
|
||||
if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_CREATED) {
|
||||
String payload = http.getString();
|
||||
if (httpCode == 200 || httpCode == 201) {
|
||||
JsonDocument doc;
|
||||
DeserializationError error = deserializeJson(doc, payload);
|
||||
if (!error && doc["token"].is<String>()) {
|
||||
filamanToken = doc["token"].as<String>();
|
||||
filamanRegistered = true;
|
||||
saveFilamanConfig();
|
||||
success = true;
|
||||
Serial.println("Device successfully registered!");
|
||||
if (!deserializeJson(doc, http.getString())) {
|
||||
if (doc["token"].is<String>()) {
|
||||
filamanToken = doc["token"].as<String>();
|
||||
filamanRegistered = true;
|
||||
saveFilamanConfig();
|
||||
http.end();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Serial.printf("Registration failed, HTTP code: %d\n", httpCode);
|
||||
}
|
||||
|
||||
http.end();
|
||||
return success;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool sendHeartbeat() {
|
||||
if (!checkFilamanRegistration()) return false;
|
||||
|
||||
if (!checkFilamanRegistration() || WiFi.status() != WL_CONNECTED) return false;
|
||||
HTTPClient http;
|
||||
String url = filamanUrl + "/api/v1/devices/heartbeat";
|
||||
|
||||
http.begin(url);
|
||||
http.setTimeout(3000);
|
||||
http.begin(filamanUrl + "/api/v1/devices/heartbeat");
|
||||
http.addHeader("Content-Type", "application/json");
|
||||
http.addHeader("Authorization", "Device " + filamanToken);
|
||||
|
||||
JsonDocument doc;
|
||||
doc["ip_address"] = WiFi.localIP().toString();
|
||||
String payload;
|
||||
serializeJson(doc, payload);
|
||||
|
||||
int httpCode = http.POST(payload);
|
||||
bool success = (httpCode == HTTP_CODE_OK);
|
||||
|
||||
if (success) {
|
||||
filamanConnected = true;
|
||||
} else {
|
||||
Serial.printf("Heartbeat failed, HTTP code: %d\n", httpCode);
|
||||
if (httpCode == 401) {
|
||||
filamanRegistered = false; // Token might be invalid
|
||||
saveFilamanConfig();
|
||||
}
|
||||
filamanConnected = false;
|
||||
}
|
||||
|
||||
filamanConnected = (httpCode == 200);
|
||||
http.end();
|
||||
return success;
|
||||
return filamanConnected;
|
||||
}
|
||||
|
||||
bool sendWeight(int spoolId, String tagUuid, float measuredWeight) {
|
||||
if (!checkFilamanRegistration()) return false;
|
||||
|
||||
if (!checkFilamanRegistration() || WiFi.status() != WL_CONNECTED) return false;
|
||||
HTTPClient http;
|
||||
String url = filamanUrl + "/api/v1/devices/scale/weight";
|
||||
|
||||
http.begin(url);
|
||||
http.setTimeout(3000);
|
||||
http.begin(filamanUrl + "/api/v1/devices/scale/weight");
|
||||
http.addHeader("Content-Type", "application/json");
|
||||
http.addHeader("Authorization", "Device " + filamanToken);
|
||||
|
||||
JsonDocument doc;
|
||||
if (spoolId > 0) doc["spool_id"] = spoolId;
|
||||
if (tagUuid.length() > 0) doc["tag_uuid"] = tagUuid;
|
||||
doc["measured_weight_g"] = measuredWeight;
|
||||
|
||||
String payload;
|
||||
serializeJson(doc, payload);
|
||||
|
||||
int httpCode = http.POST(payload);
|
||||
bool success = (httpCode == HTTP_CODE_OK);
|
||||
|
||||
if (!success) {
|
||||
Serial.printf("Weight update failed, HTTP code: %d\n", httpCode);
|
||||
}
|
||||
|
||||
http.end();
|
||||
return success;
|
||||
return (httpCode == 200);
|
||||
}
|
||||
|
||||
bool sendLocation(int spoolId, String spoolTagUuid, int locationId, String locationTagUuid) {
|
||||
if (!checkFilamanRegistration()) return false;
|
||||
|
||||
if (!checkFilamanRegistration() || WiFi.status() != WL_CONNECTED) return false;
|
||||
HTTPClient http;
|
||||
String url = filamanUrl + "/api/v1/devices/scale/locate";
|
||||
|
||||
http.begin(url);
|
||||
http.setTimeout(3000);
|
||||
http.begin(filamanUrl + "/api/v1/devices/scale/locate");
|
||||
http.addHeader("Content-Type", "application/json");
|
||||
http.addHeader("Authorization", "Device " + filamanToken);
|
||||
|
||||
JsonDocument doc;
|
||||
if (spoolId > 0) doc["spool_id"] = spoolId;
|
||||
if (spoolTagUuid.length() > 0) doc["spool_tag_uuid"] = spoolTagUuid;
|
||||
if (locationId > 0) doc["location_id"] = locationId;
|
||||
if (locationTagUuid.length() > 0) doc["location_tag_uuid"] = locationTagUuid;
|
||||
|
||||
String payload;
|
||||
serializeJson(doc, payload);
|
||||
|
||||
int httpCode = http.POST(payload);
|
||||
bool success = (httpCode == HTTP_CODE_OK);
|
||||
|
||||
if (!success) {
|
||||
Serial.printf("Location update failed, HTTP code: %d\n", httpCode);
|
||||
}
|
||||
|
||||
http.end();
|
||||
return success;
|
||||
return (httpCode == 200);
|
||||
}
|
||||
|
||||
void filamanApiTask(void* pvParameters) {
|
||||
for (;;) {
|
||||
ApiRequest req;
|
||||
bool hasReq = false;
|
||||
|
||||
if (xSemaphoreTake(queueMutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
for(int i=0; i<MAX_API_QUEUE; i++) {
|
||||
if(apiQueue[i].active) {
|
||||
req = apiQueue[i];
|
||||
apiQueue[i].active = false;
|
||||
hasReq = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
xSemaphoreGive(queueMutex);
|
||||
}
|
||||
|
||||
if (hasReq) {
|
||||
filamanApiState = API_TRANSMITTING;
|
||||
switch (req.type) {
|
||||
case API_REQUEST_HEARTBEAT: sendHeartbeat(); break;
|
||||
case API_REQUEST_WEIGHT: sendWeight(req.id1, req.str1, req.val); break;
|
||||
case API_REQUEST_LOCATE: sendLocation(req.id1, req.str1, req.id2, req.str2); break;
|
||||
default: break;
|
||||
}
|
||||
filamanApiState = API_IDLE;
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(1000));
|
||||
}
|
||||
}
|
||||
|
||||
void sendHeartbeatAsync() {
|
||||
if (!checkFilamanRegistration()) return;
|
||||
if (xSemaphoreTake(queueMutex, pdMS_TO_TICKS(50)) == pdTRUE) {
|
||||
// Prevent duplicate heartbeats
|
||||
for(int i=0; i<MAX_API_QUEUE; i++) if(apiQueue[i].active && apiQueue[i].type == API_REQUEST_HEARTBEAT) {
|
||||
xSemaphoreGive(queueMutex);
|
||||
return;
|
||||
}
|
||||
for(int i=0; i<MAX_API_QUEUE; i++) if(!apiQueue[i].active) {
|
||||
apiQueue[i].type = API_REQUEST_HEARTBEAT;
|
||||
apiQueue[i].id1 = 0;
|
||||
apiQueue[i].id2 = 0;
|
||||
apiQueue[i].str1 = "";
|
||||
apiQueue[i].str2 = "";
|
||||
apiQueue[i].val = 0.0f;
|
||||
apiQueue[i].active = true;
|
||||
break;
|
||||
}
|
||||
xSemaphoreGive(queueMutex);
|
||||
}
|
||||
}
|
||||
|
||||
void sendWeightAsync(int spoolId, String tagUuid, float weight) {
|
||||
if (!checkFilamanRegistration()) return;
|
||||
if (xSemaphoreTake(queueMutex, pdMS_TO_TICKS(50)) == pdTRUE) {
|
||||
for(int i=0; i<MAX_API_QUEUE; i++) if(!apiQueue[i].active) {
|
||||
apiQueue[i].type = API_REQUEST_WEIGHT;
|
||||
apiQueue[i].id1 = spoolId;
|
||||
apiQueue[i].id2 = 0;
|
||||
apiQueue[i].str1 = tagUuid;
|
||||
apiQueue[i].str2 = "";
|
||||
apiQueue[i].val = weight;
|
||||
apiQueue[i].active = true;
|
||||
break;
|
||||
}
|
||||
xSemaphoreGive(queueMutex);
|
||||
}
|
||||
}
|
||||
|
||||
void sendLocationAsync(int spoolId, String spoolTagUuid, int locationId, String locationTagUuid) {
|
||||
if (!checkFilamanRegistration()) return;
|
||||
if (xSemaphoreTake(queueMutex, pdMS_TO_TICKS(50)) == pdTRUE) {
|
||||
for(int i=0; i<MAX_API_QUEUE; i++) if(!apiQueue[i].active) {
|
||||
apiQueue[i].type = API_REQUEST_LOCATE;
|
||||
apiQueue[i].id1 = spoolId;
|
||||
apiQueue[i].id2 = locationId;
|
||||
apiQueue[i].str1 = spoolTagUuid;
|
||||
apiQueue[i].str2 = locationTagUuid;
|
||||
apiQueue[i].val = 0.0f;
|
||||
apiQueue[i].active = true;
|
||||
break;
|
||||
}
|
||||
xSemaphoreGive(queueMutex);
|
||||
}
|
||||
}
|
||||
|
||||
bool initFilaman() {
|
||||
oledShowProgressBar(3, 7, DISPLAY_BOOT_TEXT, "FilaMan init");
|
||||
loadFilamanConfig();
|
||||
|
||||
if (checkFilamanRegistration()) {
|
||||
sendHeartbeat();
|
||||
}
|
||||
|
||||
oledShowTopRow();
|
||||
queueMutex = xSemaphoreCreateMutex();
|
||||
// Reduce stack size to 6k and set priority to 0 (lowest) to prevent starving WiFi stack
|
||||
xTaskCreatePinnedToCore(filamanApiTask, "FilaManApi", 6144, NULL, 0, NULL, 0);
|
||||
if (checkFilamanRegistration()) sendHeartbeatAsync();
|
||||
return true;
|
||||
}
|
||||
@@ -25,6 +25,11 @@ extern bool filamanConnected;
|
||||
// FilaMan API functions
|
||||
bool initFilaman();
|
||||
bool registerDevice(const String& deviceCode);
|
||||
void sendHeartbeatAsync();
|
||||
void sendWeightAsync(int spoolId, String tagUuid, float weight);
|
||||
void sendLocationAsync(int spoolId, String spoolTagUuid, int locationId, String locationTagUuid);
|
||||
|
||||
// Internal blocking functions (used by async task)
|
||||
bool sendHeartbeat();
|
||||
bool sendWeight(int spoolId, String tagUuid, float weight);
|
||||
bool sendLocation(int spoolId, String spoolTagUuid, int locationId, String locationTagUuid);
|
||||
|
||||
+7
-9
@@ -124,7 +124,7 @@ void loop() {
|
||||
// Periodic FilaMan heartbeat
|
||||
if (intervalElapsed(currentMillis, lastFilamanHeartbeatTime, FILAMAN_HEARTBEAT_INTERVAL))
|
||||
{
|
||||
sendHeartbeat();
|
||||
sendHeartbeatAsync();
|
||||
}
|
||||
|
||||
// If scale is not calibrated, only show a warning
|
||||
@@ -190,10 +190,9 @@ void loop() {
|
||||
// Get UID from nfcJsonData or similar (nfc.cpp should set it)
|
||||
// For now, use activeSpoolId if available
|
||||
int sId = activeSpoolId.toInt();
|
||||
if (sendWeight(sId, activeTagUuid, weight)) {
|
||||
weightSend = 1;
|
||||
Serial.println("Weight sent to FilaMan");
|
||||
}
|
||||
sendWeightAsync(sId, activeTagUuid, weight);
|
||||
weightSend = 1;
|
||||
Serial.println("Weight queued for FilaMan");
|
||||
}
|
||||
|
||||
// Handle successful tag write
|
||||
@@ -201,10 +200,9 @@ void loop() {
|
||||
{
|
||||
tagProcessed = true;
|
||||
int sId = activeSpoolId.toInt();
|
||||
if (sendWeight(sId, activeTagUuid, weight)) {
|
||||
weightSend = 1;
|
||||
Serial.println("Weight sent to FilaMan after tag write");
|
||||
}
|
||||
sendWeightAsync(sId, activeTagUuid, weight);
|
||||
weightSend = 1;
|
||||
Serial.println("Weight queued for FilaMan after tag write");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-13
@@ -1268,7 +1268,7 @@ bool decodeNdefAndReturnJson(const byte* encodedMessage, String uidString) {
|
||||
Serial.println("Location Tag found!");
|
||||
int locId = doc["location_id"].as<int>();
|
||||
int sId = lastSpoolId.toInt();
|
||||
sendLocation(sId, "", locId, "");
|
||||
sendLocationAsync(sId, "", locId, "");
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -1867,15 +1867,6 @@ void scanRfidTask(void * parameter) {
|
||||
|
||||
foundNfcTag(nullptr, success);
|
||||
|
||||
// Reset activeSpoolId and activeTagUuid immediately when no tag is detected
|
||||
if (!success) {
|
||||
activeSpoolId = "";
|
||||
activeTagUuid = "";
|
||||
Serial.println("Tag entfernt");
|
||||
oledShowWeight(weight);
|
||||
}
|
||||
|
||||
|
||||
// As long as there is still a tag on the reader, do not try to read it again
|
||||
if (success && nfcReaderState == NFC_IDLE)
|
||||
{
|
||||
@@ -1989,12 +1980,11 @@ void scanRfidTask(void * parameter) {
|
||||
|
||||
if (!success && nfcReaderState != NFC_IDLE && !nfcReadingTaskSuspendRequest)
|
||||
{
|
||||
Serial.printf("NFC: Tag removed (Previous state: %d)\n", nfcReaderState);
|
||||
nfcReaderState = NFC_IDLE;
|
||||
//uidString = "";
|
||||
nfcJsonData = "";
|
||||
activeSpoolId = "";
|
||||
activeTagUuid = "";
|
||||
Serial.println("Tag entfernt");
|
||||
oledShowWeight(weight);
|
||||
}
|
||||
|
||||
@@ -2012,7 +2002,7 @@ void scanRfidTask(void * parameter) {
|
||||
// Reduced from 5 seconds to 3 seconds
|
||||
} else {
|
||||
// Faster scanning when no tag or idle state
|
||||
vTaskDelay(pdMS_TO_TICKS(150));
|
||||
vTaskDelay(pdMS_TO_TICKS(250));
|
||||
// Faster scan interval
|
||||
}
|
||||
|
||||
|
||||
+11
-2
@@ -1,4 +1,5 @@
|
||||
#include "nfc.h"
|
||||
#include "scale.h"
|
||||
#include <Arduino.h>
|
||||
#include <ArduinoJson.h>
|
||||
#include "config.h"
|
||||
@@ -35,6 +36,7 @@ uint8_t pauseMainTask = 0;
|
||||
bool scaleCalibrated;
|
||||
bool autoTare = true;
|
||||
bool scaleCalibrationActive = false;
|
||||
volatile bool scaleCalibrationRequest = false;
|
||||
|
||||
// ##### Weight stabilization functions #####
|
||||
|
||||
@@ -178,6 +180,12 @@ void scale_loop(void * parameter) {
|
||||
weight = 0; // Reset global weight variable after tare
|
||||
}
|
||||
|
||||
// Check for calibration request
|
||||
if (scaleCalibrationRequest) {
|
||||
scaleCalibrationRequest = false;
|
||||
calibrate_scale();
|
||||
}
|
||||
|
||||
// Get raw weight reading
|
||||
float rawWeight = scale.get_units();
|
||||
|
||||
@@ -286,7 +294,8 @@ uint8_t calibrate_scale() {
|
||||
scaleCalibrationActive = true;
|
||||
|
||||
if (RfidReaderTask != NULL) vTaskSuspend(RfidReaderTask);
|
||||
if (ScaleTask != NULL) vTaskSuspend(ScaleTask);
|
||||
// Do not suspend ScaleTask if we are running inside it
|
||||
if (ScaleTask != NULL && xTaskGetCurrentTaskHandle() != ScaleTask) vTaskSuspend(ScaleTask);
|
||||
|
||||
pauseMainTask = 1;
|
||||
|
||||
@@ -393,7 +402,7 @@ uint8_t calibrate_scale() {
|
||||
}
|
||||
|
||||
if (RfidReaderTask != NULL) vTaskResume(RfidReaderTask);
|
||||
if (ScaleTask != NULL) vTaskResume(ScaleTask);
|
||||
if (ScaleTask != NULL && xTaskGetCurrentTaskHandle() != ScaleTask) vTaskResume(ScaleTask);
|
||||
pauseMainTask = 0;
|
||||
scaleCalibrationActive = false;
|
||||
|
||||
|
||||
+4
-3
@@ -5,7 +5,7 @@
|
||||
#include "HX711.h"
|
||||
|
||||
uint8_t setAutoTare(bool autoTareValue);
|
||||
uint8_t start_scale(bool touchSensorConnected);
|
||||
void start_scale(bool touchSensorConnected);
|
||||
uint8_t calibrate_scale();
|
||||
uint8_t tareScale();
|
||||
|
||||
@@ -20,12 +20,13 @@ extern HX711 scale;
|
||||
extern int16_t weight;
|
||||
extern uint8_t weightCounterToApi;
|
||||
extern uint8_t scale_tare_counter;
|
||||
extern uint8_t scaleTareRequest;
|
||||
extern bool scaleTareRequest;
|
||||
extern uint8_t pauseMainTask;
|
||||
extern bool scaleCalibrated;
|
||||
extern bool autoTare;
|
||||
extern bool scaleCalibrationActive;
|
||||
extern volatile bool scaleCalibrationRequest;
|
||||
|
||||
extern TaskHandle_t ScaleTask;
|
||||
|
||||
#endif
|
||||
#endif
|
||||
+98
-172
@@ -16,8 +16,7 @@
|
||||
#define VERSION "1.2.0"
|
||||
#endif
|
||||
|
||||
// Cache-Control Header definieren
|
||||
#define CACHE_CONTROL "max-age=604800" // Cache für 1 Woche
|
||||
#define NO_CACHE "no-cache, no-store, must-revalidate"
|
||||
|
||||
AsyncWebServer server(webserverPort);
|
||||
AsyncWebSocket ws("/ws");
|
||||
@@ -25,43 +24,26 @@ AsyncWebSocket ws("/ws");
|
||||
uint8_t lastSuccess = 0;
|
||||
nfcReaderStateType lastnfcReaderState = NFC_IDLE;
|
||||
|
||||
|
||||
void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) {
|
||||
HEAP_DEBUG_MESSAGE("onWsEvent begin");
|
||||
if (type == WS_EVT_CONNECT) {
|
||||
Serial.println("Neuer Client verbunden!");
|
||||
Serial.printf("WS Client #%u connected\n", client->id());
|
||||
sendNfcData();
|
||||
foundNfcTag(client, 0);
|
||||
sendWriteResult(client, 3);
|
||||
|
||||
// Clean up dead connections
|
||||
(*server).cleanupClients();
|
||||
Serial.println("Currently connected number of clients: " + String((*server).getClients().size()));
|
||||
} else if (type == WS_EVT_DISCONNECT) {
|
||||
Serial.println("Client getrennt.");
|
||||
} else if (type == WS_EVT_ERROR) {
|
||||
Serial.printf("WebSocket Client #%u error(%u): %s\n", client->id(), *((uint16_t*)arg), (char*)data);
|
||||
} else if (type == WS_EVT_PONG) {
|
||||
Serial.printf("WebSocket Client #%u pong\n", client->id());
|
||||
ws.text(client->id(), "{\"type\":\"nfcTag\", \"payload\":{\"found\": " + String(lastSuccess) + "}}");
|
||||
server->cleanupClients();
|
||||
} else if (type == WS_EVT_DATA) {
|
||||
JsonDocument doc;
|
||||
DeserializationError error = deserializeJson(doc, (char*)data, len);
|
||||
|
||||
if (error) {
|
||||
Serial.println("JSON deserialization failed: " + String(error.c_str()));
|
||||
return;
|
||||
}
|
||||
if (error) return;
|
||||
|
||||
if (doc["type"] == "heartbeat") {
|
||||
// Sende Heartbeat-Antwort
|
||||
ws.text(client->id(), "{"
|
||||
"\"type\":\"heartbeat\","
|
||||
"\"freeHeap\":" + String(ESP.getFreeHeap()/1024) + ","
|
||||
"\"filaman_connected\":" + String(filamanConnected) + ","
|
||||
"\"registered\":" + String(filamanRegistered) + ""
|
||||
"\"registered\":" + String(filamanRegistered) + ","
|
||||
"\"autoTare\":" + String(autoTare ? "true" : "false") + ""
|
||||
"}");
|
||||
}
|
||||
|
||||
else if (doc["type"] == "writeNfcTag") {
|
||||
if (doc["payload"].is<JsonObject>()) {
|
||||
String payloadString;
|
||||
@@ -69,222 +51,166 @@ void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventTyp
|
||||
startWriteJsonToTag((doc["tagType"] == "spool") ? true : false, payloadString.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
else if (doc["type"] == "scale") {
|
||||
uint8_t success = 0;
|
||||
if (doc["payload"] == "tare") {
|
||||
scaleTareRequest = true;
|
||||
success = 1;
|
||||
}
|
||||
|
||||
if (doc["payload"] == "calibrate") {
|
||||
success = calibrate_scale();
|
||||
}
|
||||
|
||||
if (doc["payload"] == "setAutoTare") {
|
||||
success = setAutoTare(doc["enabled"].as<bool>());
|
||||
}
|
||||
|
||||
if (success) {
|
||||
ws.textAll("{\"type\":\"scale\",\"payload\":\"success\"}");
|
||||
} else {
|
||||
ws.textAll("{\"type\":\"scale\",\"payload\":\"error\"}");
|
||||
}
|
||||
else if (doc["payload"] == "calibrate") {
|
||||
scaleCalibrationRequest = true;
|
||||
ws.textAll("{\"type\":\"scale\",\"payload\":\"success\"}");
|
||||
}
|
||||
else if (doc["payload"] == "setAutoTare") {
|
||||
setAutoTare(doc["enabled"].as<bool>());
|
||||
ws.textAll("{\"type\":\"scale\",\"payload\":\"success\"}");
|
||||
}
|
||||
}
|
||||
|
||||
else if (doc["type"] == "reconnect") {
|
||||
if (doc["payload"] == "filaman") {
|
||||
sendHeartbeat();
|
||||
sendHeartbeatAsync();
|
||||
}
|
||||
}
|
||||
|
||||
else {
|
||||
Serial.println("Unbekannter WebSocket-Typ: " + doc["type"].as<String>());
|
||||
}
|
||||
doc.clear();
|
||||
}
|
||||
HEAP_DEBUG_MESSAGE("onWsEvent end");
|
||||
}
|
||||
|
||||
String loadHtmlWithHeader(const char* filename) {
|
||||
Serial.println("Lade HTML-Datei: " + String(filename));
|
||||
if (!LittleFS.exists(filename)) {
|
||||
Serial.println("Fehler: Datei nicht gefunden!");
|
||||
return "Fehler: Datei nicht gefunden!";
|
||||
}
|
||||
|
||||
File file = LittleFS.open(filename, "r");
|
||||
String html = file.readString();
|
||||
file.close();
|
||||
|
||||
return html;
|
||||
}
|
||||
|
||||
void sendWriteResult(AsyncWebSocketClient *client, uint8_t success) {
|
||||
String response = "{\"type\":\"writeNfcTag\",\"success\":" + String(success ? "1" : "0") + "}";
|
||||
ws.textAll(response);
|
||||
if (client) client->text(response); else ws.textAll(response);
|
||||
}
|
||||
|
||||
void foundNfcTag(AsyncWebSocketClient *client, uint8_t success) {
|
||||
if (success == lastSuccess) return;
|
||||
if (success == lastSuccess && client == nullptr) return;
|
||||
ws.textAll("{\"type\":\"nfcTag\", \"payload\":{\"found\": " + String(success) + "}}");
|
||||
sendNfcData();
|
||||
lastSuccess = success;
|
||||
}
|
||||
|
||||
void sendNfcData() {
|
||||
if (lastnfcReaderState == nfcReaderState) return;
|
||||
switch(nfcReaderState){
|
||||
case NFC_IDLE:
|
||||
ws.textAll("{\"type\":\"nfcData\", \"payload\":{}}");
|
||||
break;
|
||||
case NFC_READ_SUCCESS:
|
||||
ws.textAll("{\"type\":\"nfcData\", \"payload\":" + nfcJsonData + "}");
|
||||
break;
|
||||
case NFC_READ_ERROR:
|
||||
ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"error\":\"Empty Tag or Data not readable\"}}");
|
||||
break;
|
||||
case NFC_WRITING:
|
||||
ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"info\":\"Schreibe Tag...\"}}");
|
||||
break;
|
||||
case NFC_WRITE_SUCCESS:
|
||||
ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"info\":\"Tag erfolgreich geschrieben\"}}");
|
||||
break;
|
||||
case NFC_WRITE_ERROR:
|
||||
ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"error\":\"Error writing to Tag\"}}");
|
||||
break;
|
||||
case DEFAULT:
|
||||
ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"error\":\"Something went wrong\"}}");
|
||||
case NFC_IDLE: ws.textAll("{\"type\":\"nfcData\", \"payload\":{}}"); break;
|
||||
case NFC_READ_SUCCESS: ws.textAll("{\"type\":\"nfcData\", \"payload\":" + nfcJsonData + "}"); break;
|
||||
case NFC_READ_ERROR: ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"error\":\"Read Error\"}}"); break;
|
||||
case NFC_WRITING: ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"info\":\"Writing...\"}}"); break;
|
||||
case NFC_WRITE_SUCCESS: ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"info\":\"Success\"}}"); break;
|
||||
case NFC_WRITE_ERROR: ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"error\":\"Write Error\"}}"); break;
|
||||
default: break;
|
||||
}
|
||||
lastnfcReaderState = nfcReaderState;
|
||||
}
|
||||
|
||||
void setupWebserver(AsyncWebServer &server) {
|
||||
oledShowProgressBar(2, 7, DISPLAY_BOOT_TEXT, "Webserver init");
|
||||
Serial.setDebugOutput(false);
|
||||
|
||||
ws.onEvent(onWsEvent);
|
||||
ws.enable(true);
|
||||
server.addHandler(&ws);
|
||||
|
||||
server.onRequestBody([](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total){});
|
||||
server.onFileUpload([](AsyncWebServerRequest *request, const String& filename, size_t index, uint8_t *data, size_t len, bool final){});
|
||||
|
||||
loadFilamanConfig();
|
||||
|
||||
// Route für Start (Index)
|
||||
// Static Routes
|
||||
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
String html = loadHtmlWithHeader("/index.html");
|
||||
request->send(200, "text/html", html);
|
||||
Serial.println("Web: Request /");
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/index.html", "text/html");
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
// Route für Waage
|
||||
server.on("/waage", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
String html = loadHtmlWithHeader("/waage.html");
|
||||
html.replace("{{autoTare}}", (autoTare) ? "checked" : "");
|
||||
request->send(200, "text/html", html);
|
||||
Serial.println("Web: Request /waage");
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/waage.html", "text/html");
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
// Route für Setup & Registration
|
||||
server.on("/setup", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
String html = loadHtmlWithHeader("/setup.html");
|
||||
html.replace("{{filamanUrl}}", filamanUrl);
|
||||
html.replace("{{registered}}", filamanRegistered ? "Yes" : "No");
|
||||
request->send(200, "text/html", html);
|
||||
Serial.println("Web: Request /setup");
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/setup.html", "text/html");
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
server.on("/wifi", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
Serial.println("Web: Request /wifi");
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/wifi.html", "text/html");
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
server.on("/upgrade", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
Serial.println("Web: Request /upgrade");
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/upgrade.html", "text/html");
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
server.on("/style.css", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/style.css", "text/css");
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
server.on("/logo.png", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/logo.png", "image/png");
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
server.on("/favicon.ico", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/favicon.ico", "image/x-icon");
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
// API Routes
|
||||
server.on("/api/config", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
JsonDocument doc;
|
||||
doc["url"] = filamanUrl;
|
||||
doc["registered"] = filamanRegistered;
|
||||
String response;
|
||||
serializeJson(doc, response);
|
||||
request->send(200, "application/json", response);
|
||||
});
|
||||
|
||||
server.on("/api/register", HTTP_POST, [](AsyncWebServerRequest *request){}, NULL, [](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total){
|
||||
JsonDocument doc;
|
||||
deserializeJson(doc, (const char*)data);
|
||||
|
||||
DeserializationError error = deserializeJson(doc, (const uint8_t*)data, len);
|
||||
if (error) {
|
||||
request->send(400, "application/json", "{\"success\": false, \"error\": \"Invalid JSON\"}");
|
||||
return;
|
||||
}
|
||||
if (doc["url"].is<String>()) filamanUrl = doc["url"].as<String>();
|
||||
String code = doc["code"].as<String>();
|
||||
|
||||
saveFilamanConfig();
|
||||
|
||||
if (registerDevice(code)) {
|
||||
if (registerDevice(doc["code"].as<String>())) {
|
||||
request->send(200, "application/json", "{\"success\": true}");
|
||||
} else {
|
||||
request->send(400, "application/json", "{\"success\": false}");
|
||||
}
|
||||
});
|
||||
|
||||
// API for Backend to trigger Tag write
|
||||
server.on("/api/v1/rfid/write", HTTP_POST, [](AsyncWebServerRequest *request){}, NULL, [](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total){
|
||||
// Check Authorization? (TBD)
|
||||
JsonDocument doc;
|
||||
deserializeJson(doc, (const char*)data);
|
||||
|
||||
DeserializationError error = deserializeJson(doc, (const uint8_t*)data, len);
|
||||
if (error) {
|
||||
request->send(400, "application/json", "{\"success\": false, \"error\": \"Invalid JSON\"}");
|
||||
return;
|
||||
}
|
||||
String payloadString;
|
||||
serializeJson(doc, payloadString);
|
||||
|
||||
bool isSpool = !doc["spool_id"].isNull();
|
||||
startWriteJsonToTag(isSpool, payloadString.c_str());
|
||||
|
||||
startWriteJsonToTag(!doc["spool_id"].isNull(), payloadString.c_str());
|
||||
request->send(200, "application/json", "{\"status\": \"writing\"}");
|
||||
});
|
||||
|
||||
// Route für WiFi
|
||||
server.on("/wifi", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/wifi.html.gz", "text/html");
|
||||
response->addHeader("Content-Encoding", "gzip");
|
||||
response->addHeader("Cache-Control", CACHE_CONTROL);
|
||||
request->send(response);
|
||||
server.on("/api/version", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
request->send(200, "application/json", "{\"version\": \"" VERSION "\"}");
|
||||
});
|
||||
|
||||
server.on("/reboot", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
request->send(200, "text/plain", "Rebooting...");
|
||||
delay(500);
|
||||
ESP.restart();
|
||||
});
|
||||
|
||||
server.on("/style.css", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/style.css.gz", "text/css");
|
||||
response->addHeader("Content-Encoding", "gzip");
|
||||
response->addHeader("Cache-Control", CACHE_CONTROL);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
server.on("/logo.png", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/logo.png.gz", "image/png");
|
||||
response->addHeader("Content-Encoding", "gzip");
|
||||
response->addHeader("Cache-Control", CACHE_CONTROL);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
server.on("/favicon.ico", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/favicon.ico", "image/x-icon");
|
||||
response->addHeader("Cache-Control", CACHE_CONTROL);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
server.on("/rfid.js", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS,"/rfid.js.gz", "text/javascript");
|
||||
response->addHeader("Content-Encoding", "gzip");
|
||||
response->addHeader("Cache-Control", CACHE_CONTROL);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
server.on("/upgrade", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/upgrade.html.gz", "text/html");
|
||||
response->addHeader("Content-Encoding", "gzip");
|
||||
response->addHeader("Cache-Control", "no-store");
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
handleUpdate(server);
|
||||
|
||||
server.on("/api/version", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
String fm_version = VERSION;
|
||||
String jsonResponse = "{\"version\": \""+ fm_version +"\"}";
|
||||
request->send(200, "application/json", jsonResponse);
|
||||
});
|
||||
|
||||
server.onNotFound([](AsyncWebServerRequest *request){
|
||||
request->send(404, "text/plain", "Seite nicht gefunden");
|
||||
request->send(404, "text/plain", "Not found");
|
||||
});
|
||||
|
||||
ws.onEvent(onWsEvent);
|
||||
server.addHandler(&ws);
|
||||
ws.enable(true);
|
||||
|
||||
server.begin();
|
||||
Serial.println("Webserver gestartet");
|
||||
}
|
||||
Reference in new issue
Block a user