diff --git a/.gitignore b/.gitignore index 895245a..8d66b6e 100644 --- a/.gitignore +++ b/.gitignore @@ -27,8 +27,7 @@ test/README # important html/bambu_credentials.json html/spoolman_url.json -_local/* website/* release.sh wiki -_layout \ No newline at end of file +_* \ No newline at end of file diff --git a/API-DEVICES.md b/API-DEVICES.md index 83fe73b..d4703cd 100644 --- a/API-DEVICES.md +++ b/API-DEVICES.md @@ -57,12 +57,12 @@ Geräte sollten regelmäßig einen Heartbeat senden, um ihren Status auf "Online - **Request Body:** ```json { - "spool_id": 123, // Optional: Interne ID der Spule - "tag_uuid": "E280...", // Optional: RFID Tag UID + "tag_uuid": "sf:25:s5:...", // Optional: RFID Tag UID (bevorzugt) + "spool_id": 123, // Optional: Interne ID der Spule (Fallback) "measured_weight_g": 850.5 // Aktuelles Gesamtgewicht in Gramm } ``` - *Hinweis: Mindestens `spool_id` oder `tag_uuid` muss angegeben werden.* + *Hinweis: Mindestens `tag_uuid` oder `spool_id` muss angegeben werden. `tag_uuid` hat Vorrang vor `spool_id`.* - **Response:** ```json @@ -80,12 +80,14 @@ Verknüpft eine Spule mit einem Lagerort. - **Request Body:** ```json { - "spool_id": 123, // Optional: ID der Spule - "spool_tag_uuid": "E280...", // Optional: RFID UID der Spule - "location_id": 1, // Optional: ID des Ortes - "location_tag_uuid": "LOC-1" // Optional: RFID UID des Ortes + "spool_tag_uuid": "sf:25:s5:...", // Optional: RFID UID der Spule (bevorzugt) + "spool_id": 123, // Optional: ID der Spule (Fallback) + "location_tag_uuid": "LOC-1" // Optional: RFID UID des Ortes (bevorzugt) + "location_id": 1 // Optional: ID des Ortes (Fallback) } ``` + *Hinweis: RFID UUIDs haben Vorrang vor IDs. Mindestens Spule und Standort müssen durch UUID oder ID identifiziert werden.* + - **Response:** ```json { @@ -115,10 +117,33 @@ Das System sendet eine Anfrage an die IP des Geräts. - **Erwartete Response vom Gerät:** ```json { - "tag_uuid": "E2801234..." // Die UID des beschriebenen Tags + "tag_uuid": "sf:25:s5:..." // Die UID des beschriebenen Tags } ``` +### RFID Ergebnis zurückmelden +Das Device meldet das Ergebnis des Schreibvorgangs an das System zurück. + +- **Endpunkt:** `POST /api/v1/devices/rfid-result` +- **Request Body:** + ```json + { + "success": true, + "tag_uuid": "sf:25:s5:a1:00", + "spool_id": 123, + "remaining_weight_g": 850.5 + } + ``` + *Hinweis: `remaining_weight_g` ist optional und wird beim erstmaligen Beschreiben einer neuen Spule benötigt.* + +- **Felder:** + - `success` (boolean): War der Schreibvorgang erfolgreich? + - `tag_uuid` (string): Die UID des geschriebenen Tags + - `spool_id` (int, optional): DB-ID der Spule falls vorhanden + - `remaining_weight_g` (float, optional): Aktuelles Gewicht der Spule beim Schreibvorgang + +- **Response:** `{"status": "ok", "message": "Processed successfully"}` + --- ## 6. Fehlercodes diff --git a/src/api.cpp b/src/api.cpp index 60fa076..152c013 100644 --- a/src/api.cpp +++ b/src/api.cpp @@ -21,6 +21,7 @@ struct ApiRequest { float val; bool bool1; // success String str3; // error message + float remainingWeight; // remaining weight from rfid-result bool active = false; }; @@ -92,19 +93,28 @@ bool sendHeartbeat() { } bool sendWeight(int spoolId, String tagUuid, float measuredWeight) { - if (!checkFilamanRegistration() || WiFi.status() != WL_CONNECTED) return false; + Serial.printf("sendWeight: sending to API - spoolId=%d, tagUuid=%s, weight=%.1f\n", spoolId, tagUuid.c_str(), measuredWeight); + if (!checkFilamanRegistration() || WiFi.status() != WL_CONNECTED) { + Serial.println("ERROR: Not registered or WiFi not connected"); + return false; + } HTTPClient http; http.setTimeout(3000); http.begin(filamanUrl + "/api/v1/devices/scale/weight"); http.addHeader("Content-Type", "application/json"); http.addHeader("Authorization", "Device " + filamanToken); JsonDocument doc; + // Only add spool_id if it's > 0 (for NTAG tags with spool ID) + // For Bambu tags (spoolId == 0), only send tag_uuid if (spoolId > 0) doc["spool_id"] = spoolId; + // Always add tag_uuid if available (this is what we want for Bambu tags) if (tagUuid.length() > 0) doc["tag_uuid"] = tagUuid; doc["measured_weight_g"] = measuredWeight; String payload; serializeJson(doc, payload); + Serial.printf("API payload: %s\n", payload.c_str()); int httpCode = http.POST(payload); + Serial.printf("API response code: %d\n", httpCode); if (httpCode == 200) { String response = http.getString(); @@ -150,7 +160,7 @@ 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) { +bool sendRfidResult(String tagUuid, int spoolId, int locationId, bool success, String errorMessage, float remainingWeight) { if (!checkFilamanRegistration() || WiFi.status() != WL_CONNECTED) return false; HTTPClient http; http.setTimeout(5000); @@ -164,6 +174,7 @@ bool sendRfidResult(String tagUuid, int spoolId, int locationId, bool success, S if (spoolId > 0) doc["spool_id"] = spoolId; if (locationId > 0) doc["location_id"] = locationId; if (errorMessage.length() > 0) doc["error_message"] = errorMessage; + if (remainingWeight > 0) doc["remaining_weight_g"] = remainingWeight; String payload; serializeJson(doc, payload); @@ -195,7 +206,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; + case API_REQUEST_RFID_RESULT: sendRfidResult(req.str1, req.id1, req.id2, req.bool1, req.str3, req.remainingWeight); break; default: break; } filamanApiState = API_IDLE; @@ -227,7 +238,15 @@ void sendHeartbeatAsync() { } void sendWeightAsync(int spoolId, String tagUuid, float weight) { - if (!checkFilamanRegistration()) return; + Serial.printf("sendWeightAsync: spoolId=%d, tagUuid=%s, weight=%.1f\n", spoolId, tagUuid.c_str(), weight); + if (!checkFilamanRegistration()) { + Serial.println("ERROR: Not registered with FilaMan, cannot send weight"); + return; + } + if (weight <= 0) { + Serial.println("ERROR: Weight is 0 or negative, cannot send"); + return; + } if (xSemaphoreTake(queueMutex, pdMS_TO_TICKS(50)) == pdTRUE) { for(int i=0; i 3 && weightSend == 0 && nfcReaderState == NFC_READ_SUCCESS && tagProcessed == false) { - // set the current tag as processed to prevent it beeing processed again tagProcessed = true; - // Get UID from nfcJsonData or similar (nfc.cpp should set it) - // For now, use activeSpoolId if available - int sId = activeSpoolId.toInt(); - sendWeightAsync(sId, activeTagUuid, weight); + // Check if it's a Bambu tag - if so, send only UUID without spoolId + if (isBambuTag) { + sendWeightAsync(0, activeTagUuid, weight); + Serial.println("Bambu weight queued for FilaMan (UUID only)"); + } else { + // Normal NTAG: send spoolId + UUID + int sId = activeSpoolId.toInt(); + sendWeightAsync(sId, activeTagUuid, weight); + Serial.println("Weight queued for FilaMan"); + } weightSend = 1; - Serial.println("Weight queued for FilaMan"); // Feedback to user pauseMainTask = 1; diff --git a/src/nfc.cpp b/src/nfc.cpp index ada1596..b97c18e 100644 --- a/src/nfc.cpp +++ b/src/nfc.cpp @@ -22,6 +22,7 @@ String activeTagUuid = ""; String lastSpoolId = ""; String nfcJsonData = ""; bool tagProcessed = false; +bool isBambuTag = false; volatile bool nfcReadingTaskSuspendRequest = false; volatile bool nfcReadingTaskSuspendState = false; volatile bool nfcWriteInProgress = false; // Prevent any tag operations during write @@ -36,6 +37,41 @@ volatile nfcReaderStateType nfcReaderState = NFC_IDLE; // 6 = reading // ***** PN532 +// ##### Bambu Tag Helper Functions ##### +// Simplified: only read UID, no decryption needed (UID is always visible) +bool detectBambuTag(const uint8_t* uid, uint8_t uidLength) { + Serial.println("Detected Bambu Lab tag (Mifare Classic) - reading UID only"); + + // Create UID string with separators (same format as NTAG) + String uidString = ""; + for (uint8_t i = 0; i < uidLength; i++) { + uidString += String(uid[i], HEX); + if (i < uidLength - 1) { + uidString += ":"; + } + } + uidString.toUpperCase(); + + Serial.print(" UID: "); + Serial.println(uidString); + + isBambuTag = true; + activeTagUuid = uidString; + activeSpoolId = ""; // Will be resolved by FilaMan API based on tag UID + + // Create minimal JSON for compatibility + JsonDocument doc; + doc["vendor"] = "Bambu Lab"; + doc["type"] = "Bambu"; + nfcJsonData = ""; + serializeJson(doc, nfcJsonData); + + // Set normal read success state - isBambuTag flag is set for later use + nfcReaderState = NFC_READ_SUCCESS; + + return true; +} + // ##### Funktionen für RFID ##### void payloadToJson(uint8_t *data) { const char* startJson = strchr((char*)data, '{'); @@ -1590,11 +1626,11 @@ void writeJsonToTag(void *parameter) { // Wait up to 30 seconds for tag uint8_t success = 0; String uidString = ""; + uint8_t uidLength = 0; 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(); @@ -1608,7 +1644,7 @@ void writeJsonToTag(void *parameter) { uidString += ":"; // Trennzeichen hinzufügen } } - foundNfcTag(nullptr, success); + uidString.toUpperCase(); break; } @@ -1619,6 +1655,25 @@ void writeJsonToTag(void *parameter) { if (success) { + // Check if this is a Bambu tag (Mifare Classic has 4 byte UID, NTAG has 7 byte) + // If so, skip writing and just send success with weight to API + if (uidLength != 7) { + Serial.println("Bambu Lab tag detected during write - skipping write, sending result with weight"); + oledShowProgressBar(1, 1, "Write Tag", "Done!"); + + // Send success to API with tag_uuid and current weight + sendRfidResultAsync(uidString, params->spoolId, params->locationId, true, "", weight); + + vTaskDelay(pdMS_TO_TICKS(500)); + + // Clean up and exit + nfcWriteInProgress = false; + nfcReaderState = NFC_IDLE; + free(params->payload); + delete params; + vTaskDelete(NULL); + } + oledShowProgressBar(1, 3, "Write Tag", "Writing"); // Schreibe die NDEF-Message auf den Tag @@ -1710,9 +1765,9 @@ void writeJsonToTag(void *parameter) { Serial.println("========================================="); - // Send success response to API with tag_uuid (with separators) + // Send success response to API with tag_uuid and current weight Serial.println("Sending result to API via fire-and-forget..."); - sendRfidResultAsync(uidString, params->spoolId, params->locationId, true, ""); + sendRfidResultAsync(uidString, params->spoolId, params->locationId, true, "", weight); // vTaskResume(RfidReaderTask); // Don't resume as it was not suspended vTaskDelay(pdMS_TO_TICKS(500)); @@ -1740,9 +1795,6 @@ void writeJsonToTag(void *parameter) { 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(); // Reset write protection and cleanup nfcWriteInProgress = false; // Re-enable high-level tag operations @@ -2000,21 +2052,28 @@ void scanRfidTask(void * parameter) { } else { - oledShowProgressBar(1, 1, "Failure", "Tag read error"); - nfcReaderState = NFC_READ_ERROR; - // Reset activeSpoolId when tag reading fails to prevent autoSet - activeSpoolId = ""; - Serial.println("Tag read failed - activeSpoolId reset to prevent autoSet"); + // NTAG reading failed, try reading as Bambu Lab tag + Serial.println("NTAG read failed, trying Bambu Lab tag..."); + if (!detectBambuTag(uid, uidLength)) { + oledShowProgressBar(1, 1, "Failure", "Tag read error"); + nfcReaderState = NFC_READ_ERROR; + activeSpoolId = ""; + Serial.println("Tag read failed - activeSpoolId reset to prevent autoSet"); + } } } else { - //TBD: Show error here?! - oledShowProgressBar(1, 1, "Failure", "Unkown tag type"); - Serial.println("This doesn't seem to be an NTAG2xx tag (UUID length != 7 bytes)!"); - // Reset activeSpoolId when tag type is unknown to prevent autoSet - activeSpoolId = ""; - Serial.println("Unknown tag type - activeSpoolId reset to prevent autoSet"); + // UID length != 7, might be a Mifare Classic (Bambu tags) + Serial.println("Not a standard NTAG (UID length != 7), trying Bambu Lab tag..."); + if (!detectBambuTag(uid, uidLength)) { + //TBD: Show error here?! + oledShowProgressBar(1, 1, "Failure", "Unkown tag type"); + Serial.println("This doesn't seem to be an NTAG2xx tag (UUID length != 7 bytes)!"); + // Reset activeSpoolId when tag type is unknown to prevent autoSet + activeSpoolId = ""; + Serial.println("Unknown tag type - activeSpoolId reset to prevent autoSet"); + } } } @@ -2034,6 +2093,7 @@ void scanRfidTask(void * parameter) { { nfcReaderState = NFC_IDLE; tagProcessed = false; + isBambuTag = false; Serial.println("Tag nach erfolgreichem Lesen entfernt - bereit für nächsten Tag"); } diff --git a/src/nfc.h b/src/nfc.h index 29a7530..d424d40 100644 --- a/src/nfc.h +++ b/src/nfc.h @@ -11,7 +11,9 @@ typedef enum{ NFC_READ_ERROR, NFC_WRITING, NFC_WRITE_SUCCESS, - NFC_WRITE_ERROR + NFC_WRITE_ERROR, + NFC_BAMBU_DETECTED, + NFC_BAMBU_ERROR } nfcReaderStateType; struct NfcWriteParameterType { @@ -35,7 +37,6 @@ extern String lastSpoolId; extern volatile nfcReaderStateType nfcReaderState; extern volatile bool nfcWriteInProgress; extern bool tagProcessed; +extern bool isBambuTag; - - -#endif \ No newline at end of file +#endif