diff --git a/src/api.cpp b/src/api.cpp index acf7a88..3a641f6 100644 --- a/src/api.cpp +++ b/src/api.cpp @@ -19,6 +19,8 @@ struct ApiRequest { String str1; String str2; float val; + bool bool1; // success + String str3; // error message bool active = false; }; @@ -126,6 +128,28 @@ bool sendLocation(int spoolId, String spoolTagUuid, int locationId, String locat return (httpCode == 200); } +bool sendRfidResult(String tagUuid, int spoolId, int locationId, bool success, String errorMessage) { + if (!checkFilamanRegistration() || WiFi.status() != WL_CONNECTED) return false; + HTTPClient http; + http.setTimeout(5000); + http.begin(filamanUrl + "/api/v1/devices/rfid-result"); + http.addHeader("Content-Type", "application/json"); + http.addHeader("Authorization", "Device " + filamanToken); + + JsonDocument doc; + doc["success"] = success; + if (tagUuid.length() > 0) doc["tag_uuid"] = tagUuid; + if (spoolId > 0) doc["spool_id"] = spoolId; + if (locationId > 0) doc["location_id"] = locationId; + if (errorMessage.length() > 0) doc["error_message"] = errorMessage; + + String payload; + serializeJson(doc, payload); + int httpCode = http.POST(payload); + http.end(); + return (httpCode == 200); +} + void filamanApiTask(void* pvParameters) { for (;;) { ApiRequest req; @@ -149,6 +173,7 @@ void filamanApiTask(void* pvParameters) { 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; + case API_REQUEST_RFID_RESULT: sendRfidResult(req.str1, req.id1, req.id2, req.bool1, req.str3); break; default: break; } filamanApiState = API_IDLE; @@ -213,6 +238,23 @@ void sendLocationAsync(int spoolId, String spoolTagUuid, int locationId, String } } +void sendRfidResultAsync(String tagUuid, int spoolId, int locationId, bool success, String errorMessage) { + if (!checkFilamanRegistration()) return; + if (xSemaphoreTake(queueMutex, pdMS_TO_TICKS(50)) == pdTRUE) { + for(int i=0; ispoolId, params->locationId, true, ""); + + // vTaskResume(RfidReaderTask); // Don't resume as it was not suspended vTaskDelay(pdMS_TO_TICKS(500)); } else @@ -1719,6 +1723,10 @@ void writeJsonToTag(void *parameter) { oledShowIcon("failed"); vTaskDelay(pdMS_TO_TICKS(2000)); nfcReaderState = NFC_WRITE_ERROR; + + // Send error response to API + Serial.println("Sending failure result to API via fire-and-forget..."); + sendRfidResultAsync("", params->spoolId, params->locationId, false, "Write failed"); } } else @@ -1727,13 +1735,22 @@ void writeJsonToTag(void *parameter) { oledShowProgressBar(1, 1, "Failure!", "No tag found"); vTaskDelay(pdMS_TO_TICKS(2000)); nfcReaderState = NFC_IDLE; + + // Send timeout response to API + Serial.println("Sending timeout result to API via fire-and-forget..."); + sendRfidResultAsync("", params->spoolId, params->locationId, false, "Timeout - no tag found"); } sendWriteResult(nullptr, success); sendNfcData(); - // Only reset the write protection flag - reading task was never suspended + // Reset write protection and cleanup nfcWriteInProgress = false; // Re-enable high-level tag operations + + // Make sure we are in a safe state + if (nfcReaderState == NFC_WRITING) { + nfcReaderState = NFC_IDLE; + } free(params->payload); delete params; @@ -1788,29 +1805,52 @@ String optimizeJsonForFastPath(const char* payload) { return optimizedJson; } -void startWriteJsonToTag(const bool isSpoolTag, const char* payload) { +void startWriteJsonToTag(const bool isSpoolTag, const char* payload, int spoolId, int locationId) { + Serial.printf("startWriteJsonToTag called for spoolId=%d locationId=%d\n", spoolId, locationId); + + // Prevent immediate re-entry before task starts + if (nfcWriteInProgress) { + Serial.println("startWriteJsonToTag: NFC Busy (nfcWriteInProgress=true)"); + return; + } + // Optimize JSON to ensure sm_id is first key for fast-path detection String optimizedPayload = optimizeJsonForFastPath(payload); NfcWriteParameterType* parameters = new NfcWriteParameterType(); parameters->tagType = isSpoolTag; parameters->payload = strdup(optimizedPayload.c_str()); // Use optimized payload + parameters->spoolId = spoolId; + parameters->locationId = locationId; // Task nicht mehrfach starten if (nfcReaderState == NFC_IDLE || nfcReaderState == NFC_READ_ERROR || nfcReaderState == NFC_READ_SUCCESS) { + nfcWriteInProgress = true; // Lock immediately to prevent race conditions + Serial.println("startWriteJsonToTag: Starting task, lock acquired."); + oledShowProgressBar(0, 1, "Write Tag", "Place tag now"); // Erstelle die Task - xTaskCreate( + BaseType_t result = xTaskCreatePinnedToCore( writeJsonToTag, // Task-Funktion "WriteJsonToTagTask", // Task-Name - 5115, // Stackgröße in Bytes + 8192, // Stackgröße in Bytes (void*)parameters, // Parameter rfidWriteTaskPrio, // Priorität - NULL // Task-Handle (nicht benötigt) + NULL, // Task-Handle (nicht benötigt) + 1 // Core 1 (Arduino Core) ); + + if (result != pdPASS) { + Serial.println("Failed to create write task!"); + nfcWriteInProgress = false; // Release lock if task creation failed + free(parameters->payload); + delete parameters; + } }else{ + Serial.printf("startWriteJsonToTag: State mismatch (State: %d)\n", nfcReaderState); oledShowProgressBar(0, 1, "FAILURE", "NFC busy!"); - // TBD: Add proper error handling (website) + free(parameters->payload); + delete parameters; } } @@ -2029,6 +2069,7 @@ void scanRfidTask(void * parameter) { } void startNfc() { + nfcRequestMutex = xSemaphoreCreateMutex(); oledShowProgressBar(5, 7, DISPLAY_BOOT_TEXT, "NFC init"); nfc.begin(); // Beginne Kommunikation mit RFID Leser diff --git a/src/nfc.h b/src/nfc.h index f496a51..29a7530 100644 --- a/src/nfc.h +++ b/src/nfc.h @@ -2,6 +2,7 @@ #define NFC_H #include +#include typedef enum{ NFC_IDLE, @@ -13,9 +14,16 @@ typedef enum{ NFC_WRITE_ERROR } nfcReaderStateType; +struct NfcWriteParameterType { + bool tagType; + char* payload; + int spoolId; + int locationId; +}; + void startNfc(); void scanRfidTask(void * parameter); -void startWriteJsonToTag(const bool isSpoolTag, const char* payload); +void startWriteJsonToTag(const bool isSpoolTag, const char* payload, int spoolId = 0, int locationId = 0); bool quickSpoolIdCheck(String uidString); bool readCompleteJsonForFastPath(); // Read complete JSON data for fast-path web interface display diff --git a/src/website.cpp b/src/website.cpp index b910c28..c6dedaa 100644 --- a/src/website.cpp +++ b/src/website.cpp @@ -205,10 +205,24 @@ void setupWebserver(AsyncWebServer &server) { request->send(400, "application/json", "{\"error\": \"Invalid JSON\"}"); return; } + + // Check if NFC is busy + if (nfcWriteInProgress) { + request->send(503, "application/json", "{\"error\": \"NFC busy\"}"); + return; + } + String payloadString; serializeJson(doc, payloadString); - // Pass request to NFC task - it will handle the response - startWriteJsonToTag(!doc["spool_id"].isNull(), payloadString.c_str(), request); + + int spoolId = doc["spool_id"] | 0; + int locationId = doc["location_id"] | 0; + + // Start write task (fire and forget) + startWriteJsonToTag(!doc["spool_id"].isNull(), payloadString.c_str(), spoolId, locationId); + + // Respond immediately + request->send(200, "application/json", "{\"success\": true, \"message\": \"Schreibvorgang wurde gestartet. Bitte Tag bereit halten...\"}"); }); server.on("/api/version", HTTP_GET, [](AsyncWebServerRequest *request){