#include "api.h" #include #include #include "commonFS.h" #include #include "debug.h" #include "scale.h" #include "nfc.h" #include "config.h" #include volatile filamanApiStateType filamanApiState = API_IDLE; bool filamanConnected = false; struct ApiRequest { FilamanApiRequestType type; int id1; int id2; String str1; String str2; float val; bool bool1; // success String str3; // error message float remainingWeight; // remaining weight from rfid-result 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); preferences.putString(NVS_KEY_FILAMAN_URL, filamanUrl); preferences.putString(NVS_KEY_FILAMAN_TOKEN, filamanToken); preferences.putBool(NVS_KEY_FILAMAN_REGISTERED, filamanRegistered); preferences.end(); } void loadFilamanConfig() { Preferences preferences; preferences.begin(NVS_NAMESPACE_API, true); filamanUrl = preferences.getString(NVS_KEY_FILAMAN_URL, ""); filamanToken = preferences.getString(NVS_KEY_FILAMAN_TOKEN, ""); filamanRegistered = preferences.getBool(NVS_KEY_FILAMAN_REGISTERED, false); preferences.end(); } bool checkFilamanRegistration() { return filamanRegistered && filamanToken.length() > 0; } bool registerDevice(const String& deviceCode) { if (filamanUrl.length() == 0) return false; HTTPClient http; 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("{}"); if (httpCode == 200 || httpCode == 201) { JsonDocument doc; if (!deserializeJson(doc, http.getString())) { if (doc["token"].is()) { filamanToken = doc["token"].as(); filamanRegistered = true; saveFilamanConfig(); http.end(); return true; } } } http.end(); return false; } bool sendHeartbeat() { if (!checkFilamanRegistration() || WiFi.status() != WL_CONNECTED) return false; HTTPClient http; 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); filamanConnected = (httpCode == 200); http.end(); return filamanConnected; } bool sendWeight(int spoolId, String tagUuid, float measuredWeight) { 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(); JsonDocument responseDoc; DeserializationError error = deserializeJson(responseDoc, response); if (!error && responseDoc["remaining_weight_g"].is()) { int remaining = (int)responseDoc["remaining_weight_g"].as(); pauseMainTask = 1; oledShowRemainingWeight(remaining); vTaskDelay(pdMS_TO_TICKS(3000)); pauseMainTask = 0; } http.end(); return true; } else { pauseMainTask = 1; oledShowProgressBar(1, 1, "Failure", "API Error"); vTaskDelay(pdMS_TO_TICKS(2000)); pauseMainTask = 0; } http.end(); return false; } bool sendLocation(int spoolId, String spoolTagUuid, int locationId, String locationTagUuid) { if (!checkFilamanRegistration() || WiFi.status() != WL_CONNECTED) return false; HTTPClient http; 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); http.end(); return (httpCode == 200); } 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); 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; if (remainingWeight > 0) doc["remaining_weight_g"] = remainingWeight; String payload; serializeJson(doc, payload); int httpCode = http.POST(payload); http.end(); 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