Add RFID result handling: implement API for sending RFID write results and integrate with NFC task

This commit is contained in:
Manuel Weiser committed 2026-02-20 10:24:50 +01:00
1 parent 7897496481
commit f29e6aeded
5 files changed
+129 -21

No files matched your search

+42
View File
@@ -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; i<MAX_API_QUEUE; i++) if(!apiQueue[i].active) {
apiQueue[i].type = API_REQUEST_RFID_RESULT;
apiQueue[i].str1 = tagUuid;
apiQueue[i].id1 = spoolId;
apiQueue[i].id2 = locationId;
apiQueue[i].bool1 = success;
apiQueue[i].str3 = errorMessage;
apiQueue[i].active = true;
break;
}
xSemaphoreGive(queueMutex);
}
}
bool initFilaman() {
loadFilamanConfig();
queueMutex = xSemaphoreCreateMutex();
+4 -1
View File
@@ -16,7 +16,8 @@ typedef enum {
API_REQUEST_REGISTER,
API_REQUEST_HEARTBEAT,
API_REQUEST_WEIGHT,
API_REQUEST_LOCATE
API_REQUEST_LOCATE,
API_REQUEST_RFID_RESULT
} FilamanApiRequestType;
extern volatile filamanApiStateType filamanApiState;
@@ -28,11 +29,13 @@ 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);
void sendRfidResultAsync(String tagUuid, int spoolId, int locationId, bool success, String errorMessage);
// 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);
bool sendRfidResult(String tagUuid, int spoolId, int locationId, bool success, String errorMessage);
// Helper functions
void saveFilamanConfig();
+58 -17
View File
@@ -13,6 +13,8 @@
Adafruit_PN532 nfc(PN532_IRQ, PN532_RESET);
TaskHandle_t RfidReaderTask;
// AsyncWebServerRequest* volatile activeNfcWriteRequest = nullptr; // Removed
SemaphoreHandle_t nfcRequestMutex = NULL;
JsonDocument rfidData;
String activeSpoolId = "";
@@ -24,11 +26,6 @@ volatile bool nfcReadingTaskSuspendRequest = false;
volatile bool nfcReadingTaskSuspendState = false;
volatile bool nfcWriteInProgress = false; // Prevent any tag operations during write
struct NfcWriteParameterType {
bool tagType;
char* payload;
};
volatile nfcReaderStateType nfcReaderState = NFC_IDLE;
// 0 = nicht gelesen
// 1 = erfolgreich gelesen
@@ -1590,22 +1587,25 @@ void writeJsonToTag(void *parameter) {
// Show waiting message for tag detection
oledShowProgressBar(0, 1, "Write Tag", "Warte auf Tag");
// Wait 10sec for tag
// Wait up to 30 seconds for tag
uint8_t success = 0;
String uidString = "";
for (uint16_t i = 0; i < 20; i++) {
unsigned long startTime = millis();
while (millis() - startTime < 30000) {
uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 }; // Buffer to store the returned UID
uint8_t uidLength;
// yield before potentially waiting for 400ms
yield();
esp_task_wdt_reset();
success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength, 400);
if (success) {
for (uint8_t i = 0; i < uidLength; i++) {
//TBD: Rework to remove all the string operations
uidString += String(uid[i], HEX);
if (i < uidLength - 1) {
uidString += ":"; // Optional: Trennzeichen hinzufügen
uidString += ":"; // Trennzeichen hinzufügen
}
}
foundNfcTag(nullptr, success);
@@ -1614,7 +1614,7 @@ void writeJsonToTag(void *parameter) {
yield();
esp_task_wdt_reset();
vTaskDelay(pdMS_TO_TICKS(1));
vTaskDelay(pdMS_TO_TICKS(50));
}
if (success)
@@ -1710,7 +1710,11 @@ void writeJsonToTag(void *parameter) {
Serial.println("=========================================");
vTaskResume(RfidReaderTask);
// Send success response to API with tag_uuid (with separators)
Serial.println("Sending result to API via fire-and-forget...");
sendRfidResultAsync(uidString, params->spoolId, 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
+9 -1
View File
@@ -2,6 +2,7 @@
#define NFC_H
#include <Arduino.h>
#include <ESPAsyncWebServer.h>
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
+16 -2
View File
@@ -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){