diff --git a/src/api.cpp b/src/api.cpp index 317f5e8..b023040 100644 --- a/src/api.cpp +++ b/src/api.cpp @@ -3,7 +3,7 @@ #include #include "commonFS.h" -bool spoolman_connected = false; +volatile spoolmanApiStateType spoolmanApiState = API_INIT; String spoolmanUrl = ""; bool octoEnabled = false; String octoUrl = ""; @@ -85,7 +85,8 @@ JsonDocument fetchSingleSpoolInfo(int spoolId) { } void sendToApi(void *parameter) { - SendToApiParams* params = (SendToApiParams*)parameter; + spoolmanApiState = API_TRANSMITTING; + SendToApiParams *params = (SendToApiParams *)parameter; // Extrahiere die Werte String httpType = params->httpType; @@ -120,6 +121,7 @@ void sendToApi(void *parameter) { // Speicher freigeben delete params; vTaskDelete(NULL); + spoolmanApiState = API_IDLE; } bool updateSpoolTagId(String uidString, const char* payload) { @@ -477,7 +479,8 @@ bool checkSpoolmanInstance(const String& url) { return false; } - spoolman_connected = true; + spoolmanApiState = API_IDLE; + oledShowTopRow(); return strcmp(status, "healthy") == 0; } } diff --git a/src/api.h b/src/api.h index 786ece1..ed985f5 100644 --- a/src/api.h +++ b/src/api.h @@ -6,7 +6,14 @@ #include "website.h" #include "display.h" #include +typedef enum +{ + API_INIT, + API_IDLE, + API_TRANSMITTING +} spoolmanApiStateType; +extern volatile spoolmanApiStateType spoolmanApiState; extern bool spoolman_connected; extern String spoolmanUrl; extern bool octoEnabled; diff --git a/src/config.cpp b/src/config.cpp index 8c6e814..d22fa80 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -19,6 +19,11 @@ const uint16_t SCALE_LEVEL_WEIGHT = 500; uint16_t defaultScaleCalibrationValue = 430; // ***** HX711 +// ***** TTP223 (Touch Sensor) +// TTP223 circuit wiring +const uint8_t TTP223_PIN = 25; +// ***** TTP223 + // ***** Display // Declaration for an SSD1306 display connected to I2C (SDA, SCL pins) // On an ESP32: 21(SDA), 22(SCL) diff --git a/src/config.h b/src/config.h index 822ff8d..af42897 100644 --- a/src/config.h +++ b/src/config.h @@ -10,6 +10,7 @@ extern const uint8_t LOADCELL_DOUT_PIN; extern const uint8_t LOADCELL_SCK_PIN; extern const uint8_t calVal_eepromAdress; extern const uint16_t SCALE_LEVEL_WEIGHT; +extern const uint8_t TTP223_PIN; extern const int8_t OLED_RESET; extern const uint8_t SCREEN_ADDRESS; diff --git a/src/display.cpp b/src/display.cpp index c5a623f..cad5e18 100644 --- a/src/display.cpp +++ b/src/display.cpp @@ -177,9 +177,12 @@ void oledShowTopRow() { display.drawBitmap(50, 0, bitmap_off , 16, 16, WHITE); } - if (spoolman_connected == 1) { - display.drawBitmap(80, 0, bitmap_spoolman_on , 16, 16, WHITE); - } else { + if (spoolmanApiState != API_INIT) + { + display.drawBitmap(80, 0, bitmap_spoolman_on, 16, 16, WHITE); + } + else + { display.drawBitmap(80, 0, bitmap_off , 16, 16, WHITE); } diff --git a/src/main.cpp b/src/main.cpp index 4ab3e98..cae2f81 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -15,6 +15,7 @@ bool mainTaskWasPaused = 0; uint8_t scaleTareCounter = 0; +bool touchSensorConnected = false; // ##### SETUP ##### void setup() { @@ -39,7 +40,6 @@ void setup() { setupWebserver(server); // Spoolman API - // api.cpp initSpoolman(); // Bambu MQTT @@ -48,6 +48,7 @@ void setup() { // NFC Reader startNfc(); + // Scale start_scale(); // WDT initialisieren mit 10 Sekunden Timeout @@ -56,6 +57,13 @@ void setup() { // Aktuellen Task (loopTask) zum Watchdog hinzufügen esp_task_wdt_add(NULL); + // Touch Sensor + pinMode(TTP223_PIN, INPUT_PULLUP); + if (digitalRead(TTP223_PIN) == LOW) + { + Serial.println("Touch Sensor is connected"); + touchSensorConnected = true; + } } @@ -84,13 +92,25 @@ uint8_t autoAmsCounter = 0; uint8_t weightSend = 0; int16_t lastWeight = 0; +// WIFI check variables unsigned long lastWifiCheckTime = 0; const unsigned long wifiCheckInterval = 60000; // Überprüfe alle 60 Sekunden (60000 ms) +// Button debounce variables +unsigned long lastButtonPress = 0; +const unsigned long debounceDelay = 500; // 500 ms debounce delay + // ##### PROGRAM START ##### void loop() { unsigned long currentMillis = millis(); + // Überprüfe den Status des Touch Sensors + if (touchSensorConnected && digitalRead(TTP223_PIN) == HIGH && currentMillis - lastButtonPress > debounceDelay) + { + lastButtonPress = currentMillis; + scaleTareRequest = true; + } + // Überprüfe regelmäßig die WLAN-Verbindung if (intervalElapsed(currentMillis, lastWifiCheckTime, wifiCheckInterval)) { checkWiFiConnection(); @@ -105,7 +125,7 @@ void loop() { } if (intervalElapsed(currentMillis, lastAutoSetBambuAmsTime, autoSetBambuAmsInterval)) { - if (hasReadRfidTag == 0) + if (nfcReaderState == NFC_IDLE) { lastAutoSetBambuAmsTime = currentMillis; oledShowMessage("Auto Set " + String(autoSetBambuAmsCounter - autoAmsCounter) + "s"); @@ -139,7 +159,7 @@ void loop() { // Ausgabe der Waage auf Display if(pauseMainTask == 0) { - if (mainTaskWasPaused || (weight != lastWeight && hasReadRfidTag == 0 && (!autoSendToBambu || autoSetToBambuSpoolId == 0))) + if (mainTaskWasPaused || (weight != lastWeight && nfcReaderState == NFC_IDLE && (!autoSendToBambu || autoSetToBambuSpoolId == 0))) { (weight < 2) ? ((weight < -2) ? oledShowMessage("!! -0") : oledShowWeight(0)) : oledShowWeight(weight); } @@ -152,29 +172,10 @@ void loop() { // Wenn Timer abgelaufen und nicht gerade ein RFID-Tag geschrieben wird - if (currentMillis - lastWeightReadTime >= weightReadInterval && hasReadRfidTag < 3) + if (currentMillis - lastWeightReadTime >= weightReadInterval && nfcReaderState < NFC_WRITING) { lastWeightReadTime = currentMillis; - // Prüfen ob die Waage korrekt genullt ist - if ((weight > 0 && weight < 5) || weight < -1) - { - if(scaleTareCounter < 5) - { - scaleTareCounter++; - } - else - { - scaleTareRequest = true; - scaleTareCounter = 0; - } - - } - else - { - scaleTareCounter = 0; - } - // Prüfen ob das Gewicht gleich bleibt und dann senden if (weight == lastWeight && weight > 5) { @@ -188,15 +189,17 @@ void loop() { } // reset weight counter after writing tag - if (currentMillis - lastWeightReadTime >= weightReadInterval && hasReadRfidTag > 1) + // TBD: what exactly is the logic behind this? + if (currentMillis - lastWeightReadTime >= weightReadInterval && nfcReaderState != NFC_IDLE && nfcReaderState != NFC_READ_SUCCESS) { weigthCouterToApi = 0; } - + lastWeight = weight; // Wenn ein Tag mit SM id erkannte wurde und der Waage Counter anspricht an SM Senden - if (spoolId != "" && weigthCouterToApi > 3 && weightSend == 0 && hasReadRfidTag == 1) { + if (spoolId != "" && weigthCouterToApi > 3 && weightSend == 0 && nfcReaderState == NFC_READ_SUCCESS) + { oledShowIcon("loading"); if (updateSpoolWeight(spoolId, weight)) { @@ -216,6 +219,6 @@ void loop() { vTaskDelay(2000 / portTICK_PERIOD_MS); } } - + esp_task_wdt_reset(); } diff --git a/src/nfc.cpp b/src/nfc.cpp index bd75461..97a5e32 100644 --- a/src/nfc.cpp +++ b/src/nfc.cpp @@ -32,7 +32,7 @@ String spoolId = ""; String nfcJsonData = ""; volatile bool pauseBambuMqttTask = false; -volatile uint8_t hasReadRfidTag = 0; +volatile nfcReaderStateType nfcReaderState = NFC_IDLE; // 0 = nicht gelesen // 1 = erfolgreich gelesen // 2 = fehler beim Lesen @@ -185,12 +185,12 @@ void processTag(uint8_t *uid, uint8_t uidLength, uint8_t readerNumber) { void processNfcData(uint8_t *data, String tagId) { // Process the data and send it via WebSocket if (decodeNdefAndReturnJson(data)) { - hasReadRfidTag = 1; - sendNfcData(nullptr); + nfcReaderState = NFC_READ_SUCCESS; + sendNfcData(nullptr); } else { - hasReadRfidTag = 2; - oledShowMessage("NFC-Tag unknown"); - vTaskDelay(2000 / portTICK_PERIOD_MS); + nfcReaderState = NFC_READ_ERROR; + oledShowMessage("NFC-Tag unknown"); + vTaskDelay(2000 / portTICK_PERIOD_MS); } } @@ -407,7 +407,7 @@ void writeJsonToTag(void *parameter) { Serial.println("Erstelle NDEF-Message..."); Serial.println(payload); - hasReadRfidTag = 3; + nfcReaderState = NFC_WRITING; vTaskSuspend(RfidReaderTask); vTaskDelay(50 / portTICK_PERIOD_MS); @@ -462,7 +462,7 @@ void writeJsonToTag(void *parameter) { Serial.println("NDEF-Message erfolgreich auf den Tag geschrieben"); oledShowIcon("success"); vTaskDelay(1000 / portTICK_PERIOD_MS); - hasReadRfidTag = 5; + nfcReaderState = NFC_WRITE_SUCCESS; sendNfcData(nullptr); pauseBambuMqttTask = false; @@ -481,15 +481,15 @@ void writeJsonToTag(void *parameter) { Serial.println("Fehler beim Schreiben der NDEF-Message auf den Tag"); oledShowIcon("failed"); vTaskDelay(2000 / portTICK_PERIOD_MS); - hasReadRfidTag = 4; + nfcReaderState = NFC_WRITE_ERROR; } } else { Serial.println("Fehler: Kein Tag zu schreiben gefunden."); oledShowMessage("No NFC-Tag found"); vTaskDelay(2000 / portTICK_PERIOD_MS); - hasReadRfidTag = 0; + nfcReaderState = NFC_IDLE; } - + sendWriteResult(nullptr, success); sendNfcData(nullptr); @@ -503,7 +503,7 @@ void startWriteJsonToTag(const char* payload) { char* payloadCopy = strdup(payload); // Task nicht mehrfach starten - if (hasReadRfidTag != 3) { + if (nfcReaderState != NFC_WRITING) { // Erstelle die Task xTaskCreate( writeJsonToTag, // Task-Funktion @@ -518,90 +518,108 @@ void startWriteJsonToTag(const char* payload) { void scanRfidTask(void * parameter) { Serial.println("RFID Task gestartet"); - for(;;) { - if (hasReadRfidTag != 3) { - yield(); + if (nfcReaderState != NFC_WRITING) + { + yield(); - uint8_t success = 0; - uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 }; - uint8_t uidLength; - Adafruit_PN532* activeReader = nullptr; + uint8_t success = 0; + uint8_t uid[] = {0, 0, 0, 0, 0, 0, 0}; + uint8_t uidLength; + Adafruit_PN532 *activeReader = nullptr; - // Try first reader with increased timeout - success = nfc1.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength, 150); - if (success) { - activeReader = &nfc1; - } else { - delay(50); // Small delay between readers - // Try second reader with increased timeout - success = nfc2.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength, 150); - if (success) { - activeReader = &nfc2; - } - } - - foundNfcTag(nullptr, success); - - if (success && hasReadRfidTag != 1 && activeReader != nullptr) { - Serial.println("Found an ISO14443A card"); - - hasReadRfidTag = 6; - oledShowIcon("transfer"); - vTaskDelay(500 / portTICK_PERIOD_MS); - - if (uidLength == 7) { - uint16_t tagSize = readTagSize(*activeReader); - if(tagSize > 0) { - uint8_t* data = (uint8_t*)malloc(tagSize); - memset(data, 0, tagSize); - - Serial.println("Seems to be an NTAG2xx tag (7 byte UID)"); - - uint8_t numPages = readTagSize(*activeReader)/4; - for (uint8_t i = 4; i < 4+numPages; i++) { - if (!activeReader->ntag2xx_ReadPage(i, data+(i-4) * 4)) { - break; - } - if (data[(i - 4) * 4] == 0xFE) { - break; - } - - yield(); - esp_task_wdt_reset(); - vTaskDelay(pdMS_TO_TICKS(5)); // Increased delay between page reads - } - - if (!decodeNdefAndReturnJson(data)) { - oledShowMessage("NFC-Tag unknown"); - vTaskDelay(2000 / portTICK_PERIOD_MS); - hasReadRfidTag = 2; - } else { - hasReadRfidTag = 1; - } - - free(data); - } else { - oledShowMessage("NFC-Tag read error"); - hasReadRfidTag = 2; - } - } else { - Serial.println("This doesn't seem to be an NTAG2xx tag (UUID length != 7 bytes)!"); - } - } - - if (!success && hasReadRfidTag > 0) { - hasReadRfidTag = 0; - nfcJsonData = ""; - Serial.println("Tag entfernt"); - if (!autoSendToBambu) oledShowWeight(weight); - } - - sendNfcData(nullptr); - delay(100); // Add small delay at end of loop + // Try first reader with increased timeout + success = nfc1.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength, 150); + if (success) + { + activeReader = &nfc1; + } + else + { + delay(50); // Small delay between readers + // Try second reader with increased timeout + success = nfc2.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength, 150); + if (success) + { + activeReader = &nfc2; } + } + + foundNfcTag(nullptr, success); + + if (success && nfcReaderState != NFC_READ_SUCCESS && activeReader != nullptr) + { + Serial.println("Found an ISO14443A card"); + + nfcReaderState = NFC_READING; + oledShowIcon("transfer"); + vTaskDelay(500 / portTICK_PERIOD_MS); + + if (uidLength == 7) + { + uint16_t tagSize = readTagSize(*activeReader); + if (tagSize > 0) + { + uint8_t *data = (uint8_t *)malloc(tagSize); + memset(data, 0, tagSize); + + Serial.println("Seems to be an NTAG2xx tag (7 byte UID)"); + + uint8_t numPages = readTagSize(*activeReader) / 4; + for (uint8_t i = 4; i < 4 + numPages; i++) + { + if (!activeReader->ntag2xx_ReadPage(i, data + (i - 4) * 4)) + { + break; + } + if (data[(i - 4) * 4] == 0xFE) + { + break; + } + + yield(); + esp_task_wdt_reset(); + vTaskDelay(pdMS_TO_TICKS(5)); // Increased delay between page reads + } + + if (!decodeNdefAndReturnJson(data)) + { + oledShowMessage("NFC-Tag unknown"); + vTaskDelay(2000 / portTICK_PERIOD_MS); + nfcReaderState = NFC_READ_ERROR; + } + else + { + nfcReaderState = NFC_READ_SUCCESS; + } + + free(data); + } + else + { + oledShowMessage("NFC-Tag read error"); + nfcReaderState = NFC_READ_ERROR; + } + } + else + { + Serial.println("This doesn't seem to be an NTAG2xx tag (UUID length != 7 bytes)!"); + } + } + + if (!success && nfcReaderState != NFC_IDLE) + { + nfcReaderState = NFC_IDLE; + nfcJsonData = ""; + Serial.println("Tag entfernt"); + if (!autoSendToBambu) + oledShowWeight(weight); + } + + sendNfcData(nullptr); + delay(100); // Add small delay at end of loop + } yield(); } -} void startNfc() { initNfc(); diff --git a/src/nfc.h b/src/nfc.h index 4cf79ec..1c53380 100644 --- a/src/nfc.h +++ b/src/nfc.h @@ -2,6 +2,16 @@ #include #include +typedef enum +{ + NFC_IDLE, + NFC_READING, + NFC_READ_SUCCESS, + NFC_READ_ERROR, + NFC_WRITING, + NFC_WRITE_SUCCESS, + NFC_WRITE_ERROR +} nfcReaderStateType; void startNfc(); void startWriteJsonToTag(const char* payload); @@ -14,7 +24,7 @@ bool decodeNdefAndReturnJson(const byte* encodedMessage); extern TaskHandle_t RfidReaderTask; extern String nfcJsonData; extern String spoolId; -extern volatile uint8_t hasReadRfidTag; +extern volatile nfcReaderStateType nfcReaderState; extern volatile bool pauseBambuMqttTask; // Function declarations diff --git a/src/scale.cpp b/src/scale.cpp index 62db4d1..588d27d 100644 --- a/src/scale.cpp +++ b/src/scale.cpp @@ -38,11 +38,15 @@ void scale_loop(void * parameter) { for(;;) { if (scale.is_ready()) { - // Waage nochmal Taren, wenn zu lange Abweichung - if (scaleTareRequest == true) + // Waage manuell Taren + if (scaleTareRequest == true) { Serial.println("Re-Tare scale"); + oledShowMessage("TARE Scale"); + vTaskDelay(pdMS_TO_TICKS(1000)); scale.tare(); + vTaskDelay(pdMS_TO_TICKS(1000)); + oledShowWeight(0); scaleTareRequest = false; } diff --git a/src/website.cpp b/src/website.cpp index 5f43d71..b28dce2 100644 --- a/src/website.cpp +++ b/src/website.cpp @@ -22,8 +22,7 @@ AsyncWebServer server(webserverPort); AsyncWebSocket ws("/ws"); uint8_t lastSuccess = 0; -uint8_t lastHasReadRfidTag = 0; - +nfcReaderStateType lastnfcReaderState = NFC_IDLE; void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) { if (type == WS_EVT_CONNECT) { @@ -43,6 +42,7 @@ void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventTyp String message = String((char*)data); JsonDocument doc; deserializeJson(doc, message); + bool spoolmanConnected = (spoolmanApiState != API_INIT); if (doc["type"] == "heartbeat") { // Sende Heartbeat-Antwort @@ -50,7 +50,7 @@ void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventTyp "\"type\":\"heartbeat\"," "\"freeHeap\":" + String(ESP.getFreeHeap()/1024) + "," "\"bambu_connected\":" + String(bambu_connected) + "," - "\"spoolman_connected\":" + String(spoolman_connected) + "" + "\"spoolman_connected\":" + String(spoolmanConnected) + "" "}"); } @@ -139,34 +139,33 @@ void foundNfcTag(AsyncWebSocketClient *client, uint8_t success) { } void sendNfcData(AsyncWebSocketClient *client) { - if (lastHasReadRfidTag == hasReadRfidTag) return; - if (hasReadRfidTag == 0) { + if (lastnfcReaderState == nfcReaderState) + return; + // TBD: Why is there no status for reading the tag? + switch (nfcReaderState) + { + case NFC_IDLE: ws.textAll("{\"type\":\"nfcData\", \"payload\":{}}"); - } - else if (hasReadRfidTag == 1) { + break; + case NFC_READ_SUCCESS: ws.textAll("{\"type\":\"nfcData\", \"payload\":" + nfcJsonData + "}"); - } - else if (hasReadRfidTag == 2) - { + break; + case NFC_READ_ERROR: ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"error\":\"Empty Tag or Data not readable\"}}"); - } - else if (hasReadRfidTag == 3) - { + break; + case NFC_WRITING: ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"info\":\"Schreibe Tag...\"}}"); - } - else if (hasReadRfidTag == 4) - { - ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"error\":\"Error writing to Tag\"}}"); - } - else if (hasReadRfidTag == 5) - { + break; + case NFC_WRITE_SUCCESS: ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"info\":\"Tag erfolgreich geschrieben\"}}"); - } - else - { + 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\"}}"); - } - lastHasReadRfidTag = hasReadRfidTag; + } + lastnfcReaderState = nfcReaderState; } void sendAmsData(AsyncWebSocketClient *client) {