From 1d0b01ba6e1fe26ae2752dbe648e927b0f776f3f Mon Sep 17 00:00:00 2001 From: Manuel Weiser Date: Thu, 19 Feb 2026 10:57:40 +0100 Subject: [PATCH] Refactor API to FilaMan: Update API structure, remove Spoolman references, and implement new FilaMan functions for device registration, heartbeat, weight, and location updates. Adjust web server routes and configurations accordingly. Remove unused Bambu-related code and streamline NFC handling for FilaMan integration. --- API-DEVICES.md | 131 ++++ html/bambu_credentials.json | 1 - html/bambu_filaments.json | 70 -- html/config.html | 99 +++ html/header.html | 7 +- html/index.html | 40 +- html/own_filaments.json | 31 - html/rfid.html | 133 +--- html/rfid.js | 750 +----------------- html/rfid_bambu.html | 172 ----- html/set_spoolman.png | Bin 9444 -> 0 bytes html/spool_in.png | Bin 22495 -> 0 bytes html/spoolman.html | 234 ------ html/spoolman.js | 424 ---------- html/spoolman_url.json | 1 - html/upgrade.html | 7 +- html/waage.html | 37 +- html/wifi.html | 7 +- src/api.cpp | 1447 ++++------------------------------- src/api.h | 56 +- src/config.cpp | 4 +- src/config.h | 12 +- src/main.cpp | 56 +- src/nfc.cpp | 56 +- src/nfc.h | 1 + src/ota.cpp | 49 +- src/scale.cpp | 2 - src/website.cpp | 251 ++---- 28 files changed, 591 insertions(+), 3487 deletions(-) create mode 100644 API-DEVICES.md delete mode 100644 html/bambu_credentials.json delete mode 100644 html/bambu_filaments.json create mode 100644 html/config.html delete mode 100644 html/own_filaments.json delete mode 100644 html/rfid_bambu.html delete mode 100644 html/set_spoolman.png delete mode 100644 html/spool_in.png delete mode 100644 html/spoolman.html delete mode 100644 html/spoolman.js delete mode 100644 html/spoolman_url.json diff --git a/API-DEVICES.md b/API-DEVICES.md new file mode 100644 index 0000000..83fe73b --- /dev/null +++ b/API-DEVICES.md @@ -0,0 +1,131 @@ +# FilaMan Device API Documentation + +Diese Dokumentation beschreibt die API-Schnittstellen für die Kommunikation zwischen physischen Geräten (z.B. RFID-Waagen, Handheld-Scanner) und dem FilaMan-System. + +## 1. Authentifizierung + +Alle Anfragen eines Geräts an das System (außer der Registrierung) müssen authentifiziert werden. + +- **Header:** `Authorization` +- **Format:** `Device ` +- **Beispiel:** `Authorization: Device dev.1.abc123xyz...` + +Der Token wird während des Registrierungsprozesses generiert oder kann im Admin-Bereich rotiert werden. + +--- + +## 2. Onboarding (Registrierung) + +Wenn ein neues Gerät in Betrieb genommen wird, erhält es vom Administrator einen 6-stelligen **Device Code**. Mit diesem Code kann sich das Gerät einmalig registrieren, um einen dauerhaften API-Token zu erhalten. + +### Gerät registrieren +- **Endpunkt:** `POST /api/v1/devices/register` +- **Header:** `X-Device-Code: <6-STELLIGER-CODE>` +- **Response:** + ```json + { + "token": "dev.1.secret_key_here" + } + ``` +> **Hinweis:** Nach erfolgreicher Registrierung wird der `device_code` ungültig. Das Gerät muss den erhaltenen `token` sicher speichern. + +--- + +## 3. Lifecycle & Status + +Geräte sollten regelmäßig einen Heartbeat senden, um ihren Status auf "Online" zu halten und ihre aktuelle IP-Adresse zu melden. + +### Heartbeat senden +- **Endpunkt:** `POST /api/v1/devices/heartbeat` +- **Request Body:** + ```json + { + "ip_address": "192.168.1.100" + } + ``` +- **Response:** `{"status": "ok"}` +- **Frequenz:** Empfohlen alle 60-120 Sekunden. Ein Gerät gilt nach 180 Sekunden Inaktivität als offline. + +--- + +## 4. Kernfunktionen (Devices -> System) + +### Gewicht messen (Scale) +Übermittelt das aktuelle Gewicht einer Spule an das System. + +- **Endpunkt:** `POST /api/v1/devices/scale/weight` +- **Request Body:** + ```json + { + "spool_id": 123, // Optional: Interne ID der Spule + "tag_uuid": "E280...", // Optional: RFID Tag UID + "measured_weight_g": 850.5 // Aktuelles Gesamtgewicht in Gramm + } + ``` + *Hinweis: Mindestens `spool_id` oder `tag_uuid` muss angegeben werden.* + +- **Response:** + ```json + { + "remaining_weight_g": 750.0, + "spool_id": 123, + "filament_name": "PLA White" + } + ``` + +### Spule lokalisieren / Umstellen (Locate) +Verknüpft eine Spule mit einem Lagerort. + +- **Endpunkt:** `POST /api/v1/devices/scale/locate` +- **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 + } + ``` +- **Response:** + ```json + { + "success": true, + "spool_id": 123, + "location_id": 1, + "location_name": "Regal A" + } + ``` + +--- + +## 5. Remote-Aktionen (System -> Device) + +Wenn ein Gerät eine IP-Adresse im Heartbeat meldet, kann das System Befehle direkt an das Gerät senden (z.B. zum Beschreiben eines RFID-Tags). + +### RFID Tag schreiben +Das System sendet eine Anfrage an die IP des Geräts. +- **URL am Gerät:** `http:///api/v1/rfid/write` +- **Request vom System:** + ```json + { + "spool_id": 123, // Wenn eine Spule verknüpft werden soll + "location_id": 45 // ODER wenn ein Ort verknüpft werden soll + } + ``` +- **Erwartete Response vom Gerät:** + ```json + { + "tag_uuid": "E2801234..." // Die UID des beschriebenen Tags + } + ``` + +--- + +## 6. Fehlercodes + +Die API verwendet Standard-HTTP-Statuscodes: +- `200/201`: Erfolg +- `401`: Authentifizierung fehlgeschlagen (Token ungültig) +- `404`: Ressource (Spule, Ort, Gerät) nicht gefunden +- `422`: Validierungsfehler (falsches JSON-Format) +- `500`: Interner Serverfehler diff --git a/html/bambu_credentials.json b/html/bambu_credentials.json deleted file mode 100644 index ad0d698..0000000 --- a/html/bambu_credentials.json +++ /dev/null @@ -1 +0,0 @@ -{"bambu_ip": "192.168.1.14", "bambu_accesscode": "22772584", "bambu_serialnr": "01P00C492600230","autoSendToBambu":true,"autoSendTime": 60} \ No newline at end of file diff --git a/html/bambu_filaments.json b/html/bambu_filaments.json deleted file mode 100644 index afe2bc7..0000000 --- a/html/bambu_filaments.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "GFU99": "TPU", - "GFN99": "PA", - "GFN98": "PA-CF", - "GFL99": "PLA", - "GFL96": "PLA Silk", - "GFL98": "PLA-CF", - "GFL95": "PLA High Speed", - "GFG99": "PETG", - "GFG98": "PETG-CF", - "GFG97": "PCTG", - "GFB99": "ABS", - "GFC99": "PC", - "GFB98": "ASA", - "GFS99": "PVA", - "GFS98": "HIPS", - "GFT98": "PPS-CF", - "GFT97": "PPS", - "GFN97": "PPA-CF", - "GFN96": "PPA-GF", - "GFP99": "PE", - "GFP98": "PE-CF", - "GFP97": "PP", - "GFP96": "PP-CF", - "GFP95": "PP-GF", - "GFR99": "EVA", - "GFR98": "PHA", - "GFS97": "BVOH", - "GFA01": "Bambu PLA Matte", - "GFA00": "Bambu PLA Basic", - "GFA09": "Bambu PLA Tough", - "GFA07": "Bambu PLA Marble", - "GFA08": "Bambu PLA Sparkle", - "GFA02": "Bambu PLA Metal", - "GFA05": "Bambu PLA Silk", - "GFS00": "Bambu Support W", - "GFL03": "eSUN PLA+", - "GFL01": "PolyTerra PLA", - "GFL00": "PolyLite PLA", - "GFA50": "Bambu PLA-CF", - "GFS02": "Bambu Support For PLA", - "GFA11": "Bambu PLA Aero", - "GFL04": "Overture PLA", - "GFL05": "Overture Matte PLA", - "GFA12": "Bambu PLA Glow", - "GFA13": "Bambu PLA Dynamic", - "GFA15": "Bambu PLA Galaxy", - "GFS05": "Bambu Support For PLA/PETG", - "GFU01": "Bambu TPU 95A", - "GFU00": "Bambu TPU 95A HF", - "GFG00": "Bambu PETG Basic", - "GFT01": "Bambu PET-CF", - "GFG50": "Bambu PETG-CF", - "GFG60": "PolyLite PETG", - "GFG01": "Bambu PETG Translucent", - "GFB00": "Bambu ABS", - "GFB60": "PolyLite ABS", - "GFB50": "Bambu ABS-GF", - "GFC00": "Bambu PC", - "GFB01": "Bambu ASA", - "GFB61": "PolyLite ASA", - "GFB02": "Bambu ASA-Aero", - "GFS04": "Bambu PVA", - "GFS01": "Bambu Support G", - "GFN03": "Bambu PA-CF", - "GFN04": "Bambu PAHT-CF", - "GFS03": "Bambu Support For PA/PET", - "GFN05": "Bambu PA6-CF", - "GFN08": "Bambu PA6-GF" -} \ No newline at end of file diff --git a/html/config.html b/html/config.html new file mode 100644 index 0000000..2c8b24b --- /dev/null +++ b/html/config.html @@ -0,0 +1,99 @@ + + + + + + FilaMan - Configuration + + + + + + + +
+

Device Configuration

+ +
+
+
Registration
+

Status: {{registered}}

+
+ + +
+
+ + +
+ +
+
+
+
+ + + + diff --git a/html/header.html b/html/header.html index 0efb7cb..53eb785 100644 --- a/html/header.html +++ b/html/header.html @@ -30,16 +30,13 @@
- B -
-
- S + F
diff --git a/html/index.html b/html/index.html index 7763b7b..c79bd29 100644 --- a/html/index.html +++ b/html/index.html @@ -1,4 +1,4 @@ - + @@ -30,23 +30,18 @@
- B -
-
- S + F
- -

FilaMan

Filament Management Tool

@@ -55,25 +50,42 @@

About FilaMan

FilaMan is a tool designed to simplify filament spool management. It allows you to identify and weigh filament spools, - automatically sync data with the self-hosted Spoolman platform. + automatically syncing data with the FilaMan-System.

-

Get more information at https://www.filaman.app and https://github.com/ManuelW77/Filaman.

+

Get more information at https://www.filaman.app.

Spool Identification

-

Easily identify filament spools using NFC tags (NTag215 or larger).

+

Easily identify filament spools using NFC tags.

Automatic Syncing

-

Seamlessly update spool data with Spoolman for accurate tracking.

+

Seamlessly update spool data with the FilaMan API for accurate tracking.

-

OpenSpool Compatibility

-

Works with OpenSpool to recognize and activate spools on Bambu printers.

+

Scale Integration

+

Built-in scale support for precise remaining weight calculation.

+ + diff --git a/html/own_filaments.json b/html/own_filaments.json deleted file mode 100644 index cd3e43c..0000000 --- a/html/own_filaments.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "TPU": "GFU99", - "PA": "GFN99", - "PA-CF": "GFN98", - "PLA": "GFL99", - "PLA Silk": "GFL96", - "PLA-CF": "GFL98", - "PLA High Speed": "GFL95", - "PETG": "GFG99", - "PETG-CF": "GFG98", - "PCTG": "GFG97", - "ABS": "GFB99", - "ABS+HS": "GFB99", - "PC": "GFC99", - "PC/ABS": "GFC99", - "ASA": "GFB98", - "PVA": "GFS99", - "HIPS": "GFS98", - "PPS-CF": "GFT98", - "PPS": "GFT97", - "PPA-CF": "GFN97", - "PPA-GF": "GFN96", - "PE": "GFP99", - "PE-CF": "GFP98", - "PP": "GFP97", - "PP-CF": "GFP96", - "PP-GF": "GFP95", - "EVA": "GFR99", - "PHA": "GFR98", - "BVOH": "GFS97" -} \ No newline at end of file diff --git a/html/rfid.html b/html/rfid.html index cfffff8..89358e7 100644 --- a/html/rfid.html +++ b/html/rfid.html @@ -1,9 +1,9 @@ - + - FilaMan - Filament Management Tool + FilaMan - Status - + diff --git a/html/rfid.js b/html/rfid.js index ae9cd68..12597ac 100644 --- a/html/rfid.js +++ b/html/rfid.js @@ -1,58 +1,8 @@ -// WebSocket Variablen let socket; let isConnected = false; const RECONNECT_INTERVAL = 5000; -const HEARTBEAT_INTERVAL = 10000; -let heartbeatTimer = null; -let lastHeartbeatResponse = Date.now(); -const HEARTBEAT_TIMEOUT = 20000; -let reconnectTimer = null; -let spoolDetected = false; - -// WebSocket Funktionen -function startHeartbeat() { - if (heartbeatTimer) clearInterval(heartbeatTimer); - - heartbeatTimer = setInterval(() => { - // Prüfe ob zu lange keine Antwort kam - if (Date.now() - lastHeartbeatResponse > HEARTBEAT_TIMEOUT) { - isConnected = false; - updateConnectionStatus(); - if (socket) { - socket.close(); - socket = null; - } - return; - } - - if (!socket || socket.readyState !== WebSocket.OPEN) { - isConnected = false; - updateConnectionStatus(); - return; - } - - try { - // Sende Heartbeat - socket.send(JSON.stringify({ type: 'heartbeat' })); - } catch (error) { - isConnected = false; - updateConnectionStatus(); - if (socket) { - socket.close(); - socket = null; - } - } - }, HEARTBEAT_INTERVAL); -} function initWebSocket() { - // Clear any existing reconnect timer - if (reconnectTimer) { - clearTimeout(reconnectTimer); - reconnectTimer = null; - } - - // Wenn eine existierende Verbindung besteht, diese erst schließen if (socket) { socket.close(); socket = null; @@ -63,684 +13,68 @@ function initWebSocket() { socket.onopen = function() { isConnected = true; - updateConnectionStatus(); - startHeartbeat(); // Starte Heartbeat nach erfolgreicher Verbindung + console.log("WebSocket connected"); }; socket.onclose = function() { isConnected = false; - updateConnectionStatus(); - if (heartbeatTimer) clearInterval(heartbeatTimer); - - // Nur neue Verbindung versuchen, wenn kein Timer läuft - if (!reconnectTimer) { - reconnectTimer = setTimeout(() => { - initWebSocket(); - }, RECONNECT_INTERVAL); - } - }; - - socket.onerror = function(error) { - isConnected = false; - updateConnectionStatus(); - if (heartbeatTimer) clearInterval(heartbeatTimer); - - // Bei Fehler Verbindung schließen und neu aufbauen - if (socket) { - socket.close(); - socket = null; - } + setTimeout(initWebSocket, RECONNECT_INTERVAL); }; socket.onmessage = function(event) { - lastHeartbeatResponse = Date.now(); // Aktualisiere Zeitstempel bei jeder Server-Antwort - const data = JSON.parse(event.data); - if (data.type === 'amsData') { - displayAmsData(data.payload); - } else if (data.type === 'nfcTag') { - updateNfcStatusIndicator(data.payload); - } else if (data.type === 'nfcData') { - updateNfcData(data.payload); - } else if (data.type === 'writeNfcTag') { - handleWriteNfcTagResponse(data.success); + if (data.type === 'nfcData') { + updateNfcDisplay(data.payload); } else if (data.type === 'heartbeat') { - // Optional: Spezifische Behandlung von Heartbeat-Antworten - // Update status dots - const bambuDot = document.getElementById('bambuDot'); - const spoolmanDot = document.getElementById('spoolmanDot'); - const ramStatus = document.getElementById('ramStatus'); - - if (bambuDot) { - bambuDot.className = 'status-dot ' + (data.bambu_connected ? 'online' : 'offline'); - // Add click handler only when offline - if (!data.bambu_connected) { - bambuDot.style.cursor = 'pointer'; - bambuDot.onclick = function() { - if (socket && socket.readyState === WebSocket.OPEN) { - socket.send(JSON.stringify({ - type: 'reconnect', - payload: 'bambu' - })); - } - }; - } else { - bambuDot.style.cursor = 'default'; - bambuDot.onclick = null; - } - } - if (spoolmanDot) { - spoolmanDot.className = 'status-dot ' + (data.spoolman_connected ? 'online' : 'offline'); - // Add click handler only when offline - if (!data.spoolman_connected) { - spoolmanDot.style.cursor = 'pointer'; - spoolmanDot.onclick = function() { - if (socket && socket.readyState === WebSocket.OPEN) { - socket.send(JSON.stringify({ - type: 'reconnect', - payload: 'spoolman' - })); - } - }; - } else { - spoolmanDot.style.cursor = 'default'; - spoolmanDot.onclick = null; - } - } - if (ramStatus) { - ramStatus.textContent = `${data.freeHeap}k`; - } - } - else if (data.type === 'setSpoolmanSettings') { - if (data.payload == 'success') { - showNotification(`Spoolman Settings set successfully`, true); - } else { - showNotification(`Error setting Spoolman Settings`, false); - } + updateStatusDots(data); + } else if (data.type === 'weight') { + document.getElementById('weightDisplay').textContent = data.value + 'g'; } }; } catch (error) { isConnected = false; - updateConnectionStatus(); - - // Nur neue Verbindung versuchen, wenn kein Timer läuft - if (!reconnectTimer) { - reconnectTimer = setTimeout(() => { - initWebSocket(); - }, RECONNECT_INTERVAL); - } + setTimeout(initWebSocket, RECONNECT_INTERVAL); } } -function updateConnectionStatus() { - const statusElement = document.querySelector('.connection-status'); - if (!isConnected) { - statusElement.classList.remove('hidden'); - // Verzögerung hinzufügen, damit die CSS-Transition wirken kann - setTimeout(() => { - statusElement.classList.add('visible'); - }, 10); +function updateStatusDots(data) { + const filamanDot = document.getElementById('filamanDot'); + const ramStatus = document.getElementById('ramStatus'); + + if (filamanDot) { + filamanDot.style.backgroundColor = data.filaman_connected ? '#4caf50' : '#f44336'; + } + if (ramStatus) { + ramStatus.textContent = `${data.freeHeap}k free`; + } +} + +function updateNfcDisplay(data) { + const nfcInfo = document.getElementById('nfcInfo'); + if (data.error || data.info || !data || Object.keys(data).length === 0) { + nfcInfo.textContent = data.info || data.error || "No tag detected"; + return; + } + + let html = "Tag detected:
"; + if (data.sm_id) { + html += `Spool ID: ${data.sm_id}
`; + if (data.brand) html += `Brand: ${data.brand}
`; + if (data.type) html += `Material: ${data.type}
`; + } else if (data.location_id) { + html += `Location ID: ${data.location_id}
`; } else { - statusElement.classList.remove('visible'); - // Warte auf das Ende der Fade-out Animation bevor wir hidden setzen - setTimeout(() => { - statusElement.classList.add('hidden'); - }, 300); + html += "Unknown Tag Format"; } + nfcInfo.innerHTML = html; } -// Event Listeners document.addEventListener("DOMContentLoaded", function() { initWebSocket(); - - // Event Listener für Checkbox - document.getElementById("onlyWithoutSmId").addEventListener("change", function() { - const spoolsData = window.getSpoolData(); - window.populateVendorDropdown(spoolsData); - }); + // Heartbeat loop + setInterval(() => { + if (socket && socket.readyState === WebSocket.OPEN) { + socket.send(JSON.stringify({ type: 'heartbeat' })); + } + }, 5000); }); - -// Event Listener für Spoolman Events -document.addEventListener('spoolDataLoaded', function(event) { - window.populateVendorDropdown(event.detail); -}); - -document.addEventListener('spoolmanError', function(event) { - showNotification(`Spoolman Error: ${event.detail.message}`, false); -}); - -document.addEventListener('filamentSelected', function (event) { - updateNfcInfo(); - // Zeige Spool-Buttons wenn ein Filament ausgewählt wurde - const selectedText = document.getElementById("selected-filament").textContent; - updateSpoolButtons(selectedText !== "Please choose..."); -}); - -function updateNfcInfo() { - const selectedText = document.getElementById("selected-filament").textContent; - const nfcInfo = document.getElementById("nfcInfo"); - const writeButton = document.getElementById("writeNfcButton"); - - if (selectedText === "Please choose...") { - nfcInfo.textContent = "No Filament selected"; - nfcInfo.classList.remove("nfc-success", "nfc-error"); - writeButton.classList.add("hidden"); - return; - } - - // Finde die ausgewählte Spule in den Daten - const selectedSpool = spoolsData.find(spool => - `${spool.id} | ${spool.filament.name} (${spool.filament.material})` === selectedText - ); - - if (selectedSpool) { - writeButton.classList.remove("hidden"); - } else { - writeButton.classList.add("hidden"); - } -} - -function displayAmsData(amsData) { - const amsDataContainer = document.getElementById('amsData'); - amsDataContainer.innerHTML = ''; - - amsData.forEach((ams) => { - // Bestimme den Anzeigenamen für das AMS - const amsDisplayName = ams.ams_id === 255 ? 'External Spool' : `AMS ${ams.ams_id}`; - - const trayHTML = ams.tray.map(tray => { - // Prüfe ob überhaupt Daten vorhanden sind - const relevantFields = ['tray_type', 'tray_sub_brands', 'tray_info_idx', 'setting_id', 'cali_idx']; - const hasAnyContent = relevantFields.some(field => - tray[field] !== null && - tray[field] !== undefined && - tray[field] !== '' && - tray[field] !== 'null' - ); - - // Bestimme den Anzeigenamen für das Tray - const trayDisplayName = (ams.ams_id === 255) ? 'External' : `Tray ${tray.id}`; - - // Nur für nicht-leere Trays den Button-HTML erstellen - const buttonHtml = ` - `; - - // Nur für nicht-leere Trays den Button-HTML erstellen - const outButtonHtml = ` - `; - - const spoolmanButtonHtml = ` - `; - - if (!hasAnyContent) { - return ` -
-

${trayDisplayName}

-

- ${(ams.ams_id === 255 && tray.tray_type === '') ? buttonHtml : ''} - Empty -

-
-
`; - } - - // Generiere den Type mit Color-Box zusammen - const typeWithColor = tray.tray_type ? - `

Typ: ${tray.tray_type} ${tray.tray_color ? `` : ''}

` : ''; - - // Array mit restlichen Tray-Eigenschaften - const trayProperties = [ - { key: 'tray_sub_brands', label: 'Sub Brands' }, - { key: 'tray_info_idx', label: 'Filament IDX' }, - { key: 'setting_id', label: 'Setting ID' }, - { key: 'cali_idx', label: 'Calibration IDX' } - ]; - - // Nur gültige Felder anzeigen - const trayDetails = trayProperties - .filter(prop => - tray[prop.key] !== null && - tray[prop.key] !== undefined && - tray[prop.key] !== '' && - tray[prop.key] !== 'null' - ) - .map(prop => { - // Spezielle Behandlung für setting_id - if (prop.key === 'cali_idx' && tray[prop.key] === '-1') { - return `

${prop.label}: not calibrated

`; - } - return `

${prop.label}: ${tray[prop.key]}

`; - }) - .join(''); - - // Temperaturen nur anzeigen, wenn beide nicht 0 sind - const tempHTML = (tray.nozzle_temp_min > 0 && tray.nozzle_temp_max > 0) - ? `

Nozzle Temp: ${tray.nozzle_temp_min}°C - ${tray.nozzle_temp_max}°C

` - : ''; - - return ` -
-
- ${buttonHtml} -

${trayDisplayName}

- ${typeWithColor} - ${trayDetails} - ${tempHTML} - ${(ams.ams_id === 255 && tray.tray_type !== '') ? outButtonHtml : ''} - ${(tray.setting_id != "" && tray.setting_id != "null") ? spoolmanButtonHtml : ''} -
- -
`; - }).join(''); - - const amsInfo = ` -
-

${amsDisplayName}:

-
- ${trayHTML} -
-
`; - - amsDataContainer.innerHTML += amsInfo; - }); -} - -// Neue Funktion zum Anzeigen/Ausblenden der Spool-Buttons -function updateSpoolButtons(show) { - const spoolButtons = document.querySelectorAll('.spool-button'); - spoolButtons.forEach(button => { - button.style.display = show ? 'block' : 'none'; - }); -} - -function handleSpoolmanSettings(tray_info_idx, setting_id, cali_idx, nozzle_temp_min, nozzle_temp_max) { - // Hole das ausgewählte Filament - const selectedText = document.getElementById("selected-filament").textContent; - - // Finde die ausgewählte Spule in den Daten - const selectedSpool = spoolsData.find(spool => - `${spool.id} | ${spool.filament.name} (${spool.filament.material})` === selectedText - ); - - const payload = { - type: 'setSpoolmanSettings', - payload: { - filament_id: selectedSpool.filament.id, - tray_info_idx: tray_info_idx, - setting_id: setting_id, - cali_idx: cali_idx, - temp_min: nozzle_temp_min, - temp_max: nozzle_temp_max - } - }; - - try { - socket.send(JSON.stringify(payload)); - showNotification(`Setting send to Spoolman`, true); - } catch (error) { - console.error("Error while sending settings to Spoolman:", error); - showNotification("Error while sending!", false); - } -} - -function handleSpoolOut() { - // Erstelle Payload - const payload = { - type: 'setBambuSpool', - payload: { - amsId: 255, - trayId: 254, - color: "FFFFFF", - nozzle_temp_min: 0, - nozzle_temp_max: 0, - type: "", - brand: "" - } - }; - - try { - socket.send(JSON.stringify(payload)); - showNotification(`External Spool removed. Pls wait`, true); - } catch (error) { - console.error("Fehler beim Senden der WebSocket Nachricht:", error); - showNotification("Error while sending!", false); - } -} - -// Neue Funktion zum Behandeln des Spool-In-Klicks -function handleSpoolIn(amsId, trayId) { - // Prüfe WebSocket Verbindung zuerst - if (!socket || socket.readyState !== WebSocket.OPEN) { - showNotification("No active WebSocket connection!", false); - console.error("WebSocket not connected"); - return; - } - - // Hole das ausgewählte Filament - const selectedText = document.getElementById("selected-filament").textContent; - if (selectedText === "Please choose...") { - showNotification("Choose Filament first", false); - return; - } - - // Finde die ausgewählte Spule in den Daten - const selectedSpool = spoolsData.find(spool => - `${spool.id} | ${spool.filament.name} (${spool.filament.material})` === selectedText - ); - - if (!selectedSpool) { - showNotification("Selected Spool not found", false); - return; - } - - // Temperaturwerte extrahieren - let minTemp = "175"; - let maxTemp = "275"; - - if (Array.isArray(selectedSpool.filament.nozzle_temperature) && - selectedSpool.filament.nozzle_temperature.length >= 2) { - minTemp = selectedSpool.filament.nozzle_temperature[0]; - maxTemp = selectedSpool.filament.nozzle_temperature[1]; - } - - // Erstelle Payload - const payload = { - type: 'setBambuSpool', - payload: { - amsId: amsId, - trayId: trayId, - color: selectedSpool.filament.color_hex || "FFFFFF", - nozzle_temp_min: parseInt(minTemp), - nozzle_temp_max: parseInt(maxTemp), - type: selectedSpool.filament.material, - brand: selectedSpool.filament.vendor.name, - tray_info_idx: selectedSpool.filament.extra.bambu_idx?.replace(/['"]+/g, '').trim() || '', - cali_idx: "-1" // Default-Wert setzen - } - }; - - // Prüfe, ob der Key cali_idx vorhanden ist und setze ihn - if (selectedSpool.filament.extra.bambu_cali_id) { - payload.payload.cali_idx = selectedSpool.filament.extra.bambu_cali_id.replace(/['"]+/g, '').trim(); - } - - // Prüfe, ob der Key bambu_setting_id vorhanden ist - if (selectedSpool.filament.extra.bambu_setting_id) { - payload.payload.bambu_setting_id = selectedSpool.filament.extra.bambu_setting_id.replace(/['"]+/g, '').trim(); - } - - console.log("Spool-In Payload:", payload); - - try { - socket.send(JSON.stringify(payload)); - showNotification(`Spool set in AMS ${amsId} Tray ${trayId}. Pls wait`, true); - } catch (error) { - console.error("Fehler beim Senden der WebSocket Nachricht:", error); - showNotification("Error while sending", false); - } -} - -function updateNfcStatusIndicator(data) { - const indicator = document.getElementById('nfcStatusIndicator'); - - if (data.found === 0) { - // Kein NFC Tag gefunden - indicator.className = 'status-circle'; - spoolDetected = false; - } else if (data.found === 1) { - // NFC Tag erfolgreich gelesen - indicator.className = 'status-circle success'; - spoolDetected = true; - } else { - // Fehler beim Lesen - indicator.className = 'status-circle error'; - spoolDetected = true; - } -} - -function updateNfcData(data) { - // Den Container für den NFC Status finden - const nfcStatusContainer = document.querySelector('.nfc-status-display'); - - // Bestehende Daten-Anzeige entfernen falls vorhanden - const existingData = nfcStatusContainer.querySelector('.nfc-data'); - if (existingData) { - existingData.remove(); - } - - // Neues div für die Datenanzeige erstellen - const nfcDataDiv = document.createElement('div'); - nfcDataDiv.className = 'nfc-data'; - - // Wenn ein Fehler vorliegt oder keine Daten vorhanden sind - if (data.error || data.info || !data || Object.keys(data).length === 0) { - // Zeige Fehlermeldung oder leere Nachricht - if (data.error || data.info) { - if (data.error) { - nfcDataDiv.innerHTML = ` -
-

Error: ${data.error}

-
`; - } else { - nfcDataDiv.innerHTML = ` -
-

Info: ${data.info}

-
`; - } - - } else { - nfcDataDiv.innerHTML = '
'; - } - nfcStatusContainer.appendChild(nfcDataDiv); - return; - } - - // HTML für die Datenanzeige erstellen - let html = ""; - - if(data.sm_id){ - html = ` -
-

Brand: ${data.brand || 'N/A'}

-

Type: ${data.type || 'N/A'} ${data.color_hex ? `` : ''}

- `; - - // Spoolman ID anzeigen - html += `

Spoolman ID: ${data.sm_id} (Open in Spoolman)

`; - } - else if(data.location) - { - html = ` -
-

Location: ${data.location || 'N/A'}

- `; - } - else - { - html = ` -
-

Unknown tag

- `; - } - - - - // Nur wenn eine sm_id vorhanden ist, aktualisiere die Dropdowns - if (data.sm_id) { - const matchingSpool = spoolsData.find(spool => spool.id === parseInt(data.sm_id)); - if (matchingSpool) { - // Zuerst Hersteller-Dropdown aktualisieren - document.getElementById("vendorSelect").value = matchingSpool.filament.vendor.id; - - // Dann Filament-Dropdown aktualisieren und Spule auswählen - updateFilamentDropdown(); - setTimeout(() => { - // Warte kurz bis das Dropdown aktualisiert wurde - selectFilament(matchingSpool); - }, 100); - } - } - - html += '
'; - nfcDataDiv.innerHTML = html; - - - // Neues div zum Container hinzufügen - nfcStatusContainer.appendChild(nfcDataDiv); -} - -function writeNfcTag() { - if(!spoolDetected || confirm("Are you sure you want to overwrite the Tag?") == true){ - const selectedText = document.getElementById("selected-filament").textContent; - if (selectedText === "Please choose...") { - alert('Please select a Spool first.'); - return; - } - - const spoolsData = window.getSpoolData(); - const selectedSpool = spoolsData.find(spool => - `${spool.id} | ${spool.filament.name} (${spool.filament.material})` === selectedText - ); - - if (!selectedSpool) { - alert('Ausgewählte Spule konnte nicht gefunden werden.'); - return; - } - - // Temperaturwerte korrekt extrahieren - let minTemp = "175"; - let maxTemp = "275"; - - if (Array.isArray(selectedSpool.filament.nozzle_temperature) && - selectedSpool.filament.nozzle_temperature.length >= 2) { - minTemp = String(selectedSpool.filament.nozzle_temperature[0]); - maxTemp = String(selectedSpool.filament.nozzle_temperature[1]); - } - - // Erstelle das NFC-Datenpaket mit korrekten Datentypen - const nfcData = { - color_hex: selectedSpool.filament.color_hex || "FFFFFF", - type: selectedSpool.filament.material, - min_temp: minTemp, - max_temp: maxTemp, - brand: selectedSpool.filament.vendor.name, - sm_id: String(selectedSpool.id) // Konvertiere zu String - }; - - if (socket?.readyState === WebSocket.OPEN) { - const writeButton = document.getElementById("writeNfcButton"); - writeButton.classList.add("writing"); - writeButton.textContent = "Writing"; - socket.send(JSON.stringify({ - type: 'writeNfcTag', - tagType: 'spool', - payload: nfcData - })); - } else { - alert('Not connected to Server. Please check connection.'); - } - } -} - -function writeLocationNfcTag() { - if(!spoolDetected || confirm("Are you sure you want to overwrite the Tag?") == true){ - const selectedText = document.getElementById("locationSelect").value; - if (selectedText === "Please choose...") { - alert('Please select a location first.'); - return; - } - // Erstelle das NFC-Datenpaket mit korrekten Datentypen - const nfcData = { - location: String(selectedText) - }; - - - if (socket?.readyState === WebSocket.OPEN) { - const writeButton = document.getElementById("writeLocationNfcButton"); - writeButton.classList.add("writing"); - writeButton.textContent = "Writing"; - socket.send(JSON.stringify({ - type: 'writeNfcTag', - tagType: 'location', - payload: nfcData - })); - } else { - alert('Not connected to Server. Please check connection.'); - } - } -} - -function handleWriteNfcTagResponse(success) { - const writeButton = document.getElementById("writeNfcButton"); - const writeLocationButton = document.getElementById("writeLocationNfcButton"); - if(writeButton.classList.contains("writing")){ - writeButton.classList.remove("writing"); - writeButton.classList.add(success ? "success" : "error"); - writeButton.textContent = success ? "Write success" : "Write failed"; - - setTimeout(() => { - writeButton.classList.remove("success", "error"); - writeButton.textContent = "Write Tag"; - }, 5000); - } - - if(writeLocationButton.classList.contains("writing")){ - writeLocationButton.classList.remove("writing"); - writeLocationButton.classList.add(success ? "success" : "error"); - writeLocationButton.textContent = success ? "Write success" : "Write failed"; - - setTimeout(() => { - writeLocationButton.classList.remove("success", "error"); - writeLocationButton.textContent = "Write Location Tag"; - }, 5000); - } - - -} - -function showNotification(message, isSuccess) { - const notification = document.createElement('div'); - notification.className = `notification ${isSuccess ? 'success' : 'error'}`; - notification.textContent = message; - document.body.appendChild(notification); - - // Nach 3 Sekunden ausblenden - setTimeout(() => { - notification.classList.add('fade-out'); - setTimeout(() => { - notification.remove(); - }, 300); - }, 3000); -} \ No newline at end of file diff --git a/html/rfid_bambu.html b/html/rfid_bambu.html deleted file mode 100644 index 9fc3210..0000000 --- a/html/rfid_bambu.html +++ /dev/null @@ -1,172 +0,0 @@ - - - - - - FilaMan - Filament Management Tool - - - - - - - - - - -
-
- -
-
-
-

Statistics

- -
-
-

Spools

-
- total: - -
- without Tag: - -
-
- -
-
-

Overview

-
    -
  • - Manufacturer: - -
  • -
  • - Weight: - -
  • -
  • - Length: - -
  • -
-
-
-

Materials

-
    - -
-
-
-
-
-
-

NFC-Tag

- -
-
-
-
- - -
-
-

Spoolman Spools

- -
- - -
-
- - - -
-

Spoolman Locations

- -
- -
-

- -
-
- - -
-
-

Bambu AMS

-
-
Wait for AMS-Data...
-
-
-
-
-
- - - - - - diff --git a/html/set_spoolman.png b/html/set_spoolman.png deleted file mode 100644 index 2ec6c22f1a9c87861c9cd1493a1664693ba2abbe..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 9444 zcmaia1zc3!*7wle-6J3k14EZcgLJ3#&@jZ1BF%t+AktET5(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8C_@ngRG5|F0*hzA9gsNnMeTKmSMak)=)_LHtuE#zUVz^Jr|Bk{L zvIUjtpE3>kvIUjqz7$rPXP$Y++R@R`7>~!F3jmPobBJs`WVB9>%Us-qCsd z9v6|&9DaWpkyxB?B8isL5JI3Q5)_B$s5K0}qwDO*p;Q?GUeoot(?SgPO8J%!m$^CJ zr3H1PfBI5eVdTm^xa+*~$}8%NFTU6w3WW|N5{ZMluJ0@_FL$Kdx;$PlDP2%jUdHJ7 z#FFQbQc_V~MkEqOOC%A7fz;>G5(y?I#&x@{hXRTsc7go~i>2^x&IPmGR^P5>UDq8bj>sA}_r zic)>RYIWU&*7_SR4@tF{vW2PaWVX>eYVX>f@HsoK(KivtxwZgg;FTC)A=k)1M z-P6;P_INyD)wHC=VzEkx!>)V1#aexRT`CX=gr9rvIUV!Y>8E*bLWkQdg6ZP1KZ6VX?^8iB2}htK(@yp6*=!(uRCFc%#E2U9}lSN?lwiKe$;Ap-)YZxNJ?HcjM+0n3|yA-Ed%<=j!tR+wBm+* zIpl?P_fS}jVpg(KWm;q&D>T$9%9FKvj7TYeqU)0vgt#~eZ(_E( z-}r==7F60lt*9Yi4tZhS8`1*1F;zNQjAGs*c&J8Eez#Fo1CLuQ{z^sRoM9Mm2r<@c z8uE8oG~}87>7E$!<&YQFz31~%r3>?^vTQv(UZyBtxhmzy({Kz^Kuh_jduGU&Lta>` z$5N@X05giEMdrj5;5=qjN~gP3G33i3FRa`kGgYReSo%;gqfv@%|MZ2oe7hIqg_V1# zWT#75+;e+X4f%4&3oCa~GCtEn%6UQM$&)8fo;-Q- - - - - - FilaMan - Filament Management Tool - - - - - - - - - - - - -
-

Spoolman API URL / Bambu Credentials

- -
-
-
Set URL/IP to your Spoolman instance
- -
If you want to enable sending the spool to the Spoolman Octoprint plugin:
-

- Send to Octo-Plugin -

- - - -

-
-
- -
-
-
Bambu Lab Printer Credentials
-
-
- - -
-
- - -
-
- - -
-
- - -
-
-

If activated, FilaMan will automatically update the next filled tray with the last scanned and weighed spool.

-
- - -
-
- - -
- - - -

-
-
-
-
- - diff --git a/html/spoolman.js b/html/spoolman.js deleted file mode 100644 index aba63f0..0000000 --- a/html/spoolman.js +++ /dev/null @@ -1,424 +0,0 @@ -// Globale Variablen -let spoolmanUrl = ''; -let spoolsData = []; -let locationData = []; - -// Hilfsfunktionen für Datenmanipulation -function processSpoolData(data) { - return data.map(spool => ({ - id: spool.id, - remaining_weight: spool.remaining_weight, - remaining_length: spool.remaining_length, - filament: spool.filament, - extra: spool.extra - })); -} - -// Dropdown-Funktionen -function populateVendorDropdown(data, selectedSmId = null) { - const vendorSelect = document.getElementById("vendorSelect"); - if (!vendorSelect) { - console.error('vendorSelect Element nicht gefunden'); - return; - } - const onlyWithoutSmId = document.getElementById("onlyWithoutSmId"); - if (!onlyWithoutSmId) { - console.error('onlyWithoutSmId Element nicht gefunden'); - return; - } - - // Separate Objekte für alle Hersteller und gefilterte Hersteller - const allVendors = {}; - const filteredVendors = {}; - - vendorSelect.innerHTML = ''; - - let vendorIdToSelect = null; - let totalSpools = 0; - let spoolsWithoutTag = 0; - let totalWeight = 0; - let totalLength = 0; - // Neues Objekt für Material-Gruppierung - const materials = {}; - - data.forEach(spool => { - if (!spool.filament || !spool.filament.vendor) { - return; - } - - totalSpools++; - - // Material zählen und gruppieren - if (spool.filament.material) { - const material = spool.filament.material.toUpperCase(); // Normalisierung - materials[material] = (materials[material] || 0) + 1; - } - - // Addiere Gewicht und Länge - if (spool.remaining_weight) { - totalWeight += spool.remaining_weight; - } - if (spool.remaining_length) { - totalLength += spool.remaining_length; - } - - const vendor = spool.filament.vendor; - - const hasValidNfcId = spool.extra && - spool.extra.nfc_id && - spool.extra.nfc_id !== '""' && - spool.extra.nfc_id !== '"\\"\\"\\""'; - - if (!hasValidNfcId) { - spoolsWithoutTag++; - } - - // Alle Hersteller sammeln - if (!allVendors[vendor.id]) { - allVendors[vendor.id] = vendor.name; - } - - // Gefilterte Hersteller für Dropdown - if (!filteredVendors[vendor.id]) { - if (!onlyWithoutSmId.checked || !hasValidNfcId) { - filteredVendors[vendor.id] = vendor.name; - } - } - }); - - // Nach der Schleife: Formatierung der Gesamtlänge - const lengthInM = totalLength / 1000; // erst in m umrechnen - const formattedLength = lengthInM > 1000 - ? (lengthInM / 1000).toFixed(2) + " km" - : lengthInM.toFixed(2) + " m"; - - // Formatierung des Gesamtgewichts (von g zu kg zu t) - const weightInKg = totalWeight / 1000; // erst in kg umrechnen - const formattedWeight = weightInKg > 1000 - ? (weightInKg / 1000).toFixed(2) + " t" - : weightInKg.toFixed(2) + " kg"; - - // Dropdown mit gefilterten Herstellern befüllen - alphabetisch sortiert - Object.entries(filteredVendors) - .sort(([, nameA], [, nameB]) => nameA.localeCompare(nameB)) // Sort vendors alphabetically by name - .forEach(([id, name]) => { - const option = document.createElement("option"); - option.value = id; - option.textContent = name; - vendorSelect.appendChild(option); - }); - - document.getElementById("totalSpools").textContent = totalSpools; - document.getElementById("spoolsWithoutTag").textContent = spoolsWithoutTag; - // Zeige die Gesamtzahl aller Hersteller an - document.getElementById("totalVendors").textContent = Object.keys(allVendors).length; - - // Neue Statistiken hinzufügen - document.getElementById("totalWeight").textContent = formattedWeight; - document.getElementById("totalLength").textContent = formattedLength; - - // Material-Statistiken zum DOM hinzufügen - const materialsList = document.getElementById("materialsList"); - materialsList.innerHTML = ''; - Object.entries(materials) - .sort(([,a], [,b]) => b - a) // Sortiere nach Anzahl absteigend - .forEach(([material, count]) => { - const li = document.createElement("li"); - li.textContent = `${material}: ${count} ${count === 1 ? 'Spool' : 'Spools'}`; - materialsList.appendChild(li); - }); - - if (vendorIdToSelect) { - vendorSelect.value = vendorIdToSelect; - updateFilamentDropdown(selectedSmId); - } -} - -// Dropdown-Funktionen -function populateLocationDropdown(data) { - const locationSelect = document.getElementById("locationSelect"); - if (!locationSelect) { - console.error('locationSelect Element nicht gefunden'); - return; - } - - locationSelect.innerHTML = ''; - // Dropdown mit gefilterten Herstellern befüllen - alphabetisch sortiert - Object.entries(data) - .sort(([, nameA], [, nameB]) => nameA.localeCompare(nameB)) // Sort vendors alphabetically by name - .forEach(([id, name]) => { - const option = document.createElement("option"); - option.value = name; - option.textContent = name; - locationSelect.appendChild(option); - }); -} - -function updateFilamentDropdown(selectedSmId = null) { - const vendorId = document.getElementById("vendorSelect").value; - const dropdownContentInner = document.getElementById("filament-dropdown-content"); - const filamentSection = document.getElementById("filamentSection"); - const onlyWithoutSmId = document.getElementById("onlyWithoutSmId").checked; - const selectedText = document.getElementById("selected-filament"); - const selectedColor = document.getElementById("selected-color"); - - dropdownContentInner.innerHTML = ''; - selectedText.textContent = "Bitte wählen..."; - selectedColor.style.backgroundColor = '#FFFFFF'; - - if (vendorId) { - const filteredFilaments = spoolsData.filter(spool => { - if (!spool?.filament?.vendor?.id) { - console.log('Problem aufgetreten bei: ', spool?.filament?.vendor); - console.log('Problematische Spulen:', - spoolsData.filter(spool => !spool?.filament?.vendor?.id)); - return false; - } - - const hasValidNfcId = spool.extra && - spool.extra.nfc_id && - spool.extra.nfc_id !== '""' && - spool.extra.nfc_id !== '"\\"\\"\\""'; - - return spool.filament.vendor.id == vendorId && - (!onlyWithoutSmId || !hasValidNfcId); - }); - - filteredFilaments.forEach(spool => { - const option = document.createElement("div"); - option.className = "dropdown-option"; - option.setAttribute("data-value", spool.filament.id); - option.setAttribute("data-nfc-id", spool.extra.nfc_id || ""); - - - // Generate color representation based on filament type (single or multi color) - let colorHTML = ''; - - // Check if this is a multicolor filament - if (spool.filament.multi_color_hexes) { - // Parse multi color hexes from comma-separated string - const colors = spool.filament.multi_color_hexes.replace(/#/g, '').split(','); - - // Determine the display style based on direction - const direction = spool.filament.multi_color_direction || 'coaxial'; - - // Generate color circles for each color - colorHTML = '
'; - colors.forEach(color => { - colorHTML += `
`; - }); - colorHTML += '
'; - } else { - // Single color filament - const colorHex = spool.filament.color_hex || 'FFFFFF'; - colorHTML = `
`; - } - - option.innerHTML = ` - ${colorHTML} - ${spool.id} | ${spool.filament.name} (${spool.filament.material}) - `; - - option.onclick = () => selectFilament(spool); - dropdownContentInner.appendChild(option); - }); - - filamentSection.classList.remove("hidden"); - } else { - filamentSection.classList.add("hidden"); - } -} - -function updateLocationSelect(){ - const writeLocationNfcButton = document.getElementById('writeLocationNfcButton'); - if(writeLocationNfcButton){ - writeLocationNfcButton.classList.remove("hidden"); - } -} - -function selectFilament(spool) { - const selectedColor = document.getElementById("selected-color"); - const selectedText = document.getElementById("selected-filament"); - const dropdownContent = document.getElementById("filament-dropdown-content"); - - // Update the selected color display - if (spool.filament.multi_color_hexes) { - // Handle multicolor filament display in the selection header - const colors = spool.filament.multi_color_hexes.replace(/#/g, '').split(','); - const direction = spool.filament.multi_color_direction || 'coaxial'; - - // Replace the single color div with multiple color divs - selectedColor.innerHTML = ''; - colors.forEach(color => { - const colorDiv = document.createElement('div'); - colorDiv.className = `color-segment multi-color ${direction}`; - colorDiv.style.backgroundColor = `#${color}`; - selectedColor.appendChild(colorDiv); - }); - // Add multiple color class to the container - selectedColor.classList.add('multi-color-container'); - } else { - // Single color filament - reset to default display - selectedColor.innerHTML = ''; - selectedColor.classList.remove('multi-color-container'); - selectedColor.style.backgroundColor = `#${spool.filament.color_hex || 'FFFFFF'}`; - } - - selectedText.textContent = `${spool.id} | ${spool.filament.name} (${spool.filament.material})`; - dropdownContent.classList.remove("show"); - - document.dispatchEvent(new CustomEvent('filamentSelected', { - detail: spool - })); -} - -// Initialisierung und Event-Handler -async function initSpoolman() { - try { - const response = await fetch('/api/url'); - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } - - const data = await response.json(); - if (!data.spoolman_url) { - throw new Error('spoolman_url nicht in der Antwort gefunden'); - } - - spoolmanUrl = data.spoolman_url; - - const fetchedData = await fetchSpoolData(); - spoolsData = processSpoolData(fetchedData); - - document.dispatchEvent(new CustomEvent('spoolDataLoaded', { - detail: spoolsData - })); - - locationData = await fetchLocationData(); - - document.dispatchEvent(new CustomEvent('locationDataLoaded', { - detail: locationData - })); - - - } catch (error) { - console.error('Fehler beim Initialisieren von Spoolman:', error); - document.dispatchEvent(new CustomEvent('spoolmanError', { - detail: { message: error.message } - })); - } -} - -async function fetchSpoolData() { - try { - if (!spoolmanUrl) { - throw new Error('Spoolman URL ist nicht initialisiert'); - } - - const response = await fetch(`${spoolmanUrl}/api/v1/spool`); - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } - - const data = await response.json(); - return data; - } catch (error) { - console.error('Fehler beim Abrufen der Spulen-Daten:', error); - return []; - } -} - -async function fetchLocationData() { - try { - if (!spoolmanUrl) { - throw new Error('Spoolman URL ist nicht initialisiert'); - } - - const response = await fetch(`${spoolmanUrl}/api/v1/location`); - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } - - const data = await response.json(); - return data; - } catch (error) { - console.error('Fehler beim Abrufen der Location-Daten:', error); - return []; - } -} - -// Event Listener -document.addEventListener('DOMContentLoaded', () => { - initSpoolman(); - - const vendorSelect = document.getElementById('vendorSelect'); - if (vendorSelect) { - vendorSelect.addEventListener('change', () => updateFilamentDropdown()); - } - - const locationSelect = document.getElementById('locationSelect'); - if (locationSelect) { - locationSelect.addEventListener('change', () => updateLocationSelect()); - } - - const onlyWithoutSmId = document.getElementById('onlyWithoutSmId'); - if (onlyWithoutSmId) { - onlyWithoutSmId.addEventListener('change', () => { - populateVendorDropdown(spoolsData); - updateFilamentDropdown(); - }); - } - - document.addEventListener('spoolDataLoaded', (event) => { - populateVendorDropdown(event.detail); - }); - - document.addEventListener('locationDataLoaded', (event) => { - populateLocationDropdown(event.detail); - }); - - window.onclick = function(event) { - if (!event.target.closest('.custom-dropdown')) { - const dropdowns = document.getElementsByClassName("dropdown-content"); - for (let dropdown of dropdowns) { - dropdown.classList.remove("show"); - } - } - }; - - const refreshButton = document.getElementById('refreshSpoolman'); - if (refreshButton) { - refreshButton.addEventListener('click', async () => { - try { - refreshButton.disabled = true; - refreshButton.textContent = 'Wird aktualisiert...'; - await initSpoolman(); - refreshButton.textContent = 'Refresh Spoolman'; - } finally { - refreshButton.disabled = false; - } - }); - } -}); - -// Exportiere Funktionen -window.getSpoolData = () => spoolsData; -window.setSpoolData = (data) => { spoolsData = data; }; -window.reloadSpoolData = initSpoolman; -window.populateVendorDropdown = populateVendorDropdown; -window.populateLocationDropdown = populateLocationDropdown; -window.updateFilamentDropdown = updateFilamentDropdown; -window.toggleFilamentDropdown = () => { - const content = document.getElementById("filament-dropdown-content"); - content.classList.toggle("show"); -}; - -// Event Listener für Click außerhalb Dropdown -window.onclick = function(event) { - if (!event.target.closest('.custom-dropdown')) { - const dropdowns = document.getElementsByClassName("dropdown-content"); - for (let dropdown of dropdowns) { - dropdown.classList.remove("show"); - } - } -}; \ No newline at end of file diff --git a/html/spoolman_url.json b/html/spoolman_url.json deleted file mode 100644 index 05a8a9f..0000000 --- a/html/spoolman_url.json +++ /dev/null @@ -1 +0,0 @@ -{"url": "http://192.168.1.5:7912", "octoEnabled": true, "octoUrl": "http://192.168.1.17:5001", "octoToken": "O5zZ58mXRAyeGpVEj2ZZj-UPAPqJ2N7JgtD36mw1M4g"} \ No newline at end of file diff --git a/html/upgrade.html b/html/upgrade.html index 5bbcedf..d34d4a8 100644 --- a/html/upgrade.html +++ b/html/upgrade.html @@ -30,16 +30,13 @@
- B -
-
- S + F
diff --git a/html/waage.html b/html/waage.html index 40ffa5c..d82f435 100644 --- a/html/waage.html +++ b/html/waage.html @@ -1,9 +1,9 @@ - + - FilaMan - Filament Management Tool + FilaMan - Scale Configuration diff --git a/html/wifi.html b/html/wifi.html index c712e78..0ffef42 100644 --- a/html/wifi.html +++ b/html/wifi.html @@ -30,16 +30,13 @@
- B -
-
- S + F
diff --git a/src/api.cpp b/src/api.cpp index 3129d20..4cff372 100644 --- a/src/api.cpp +++ b/src/api.cpp @@ -6,1329 +6,166 @@ #include "debug.h" #include "scale.h" #include "nfc.h" -#include -volatile spoolmanApiStateType spoolmanApiState = API_IDLE; +#include "config.h" +#include -//bool spoolman_connected = false; -String spoolmanUrl = ""; -bool octoEnabled = false; -bool sendOctoUpdate = false; -String octoUrl = ""; -String octoToken = ""; -uint16_t remainingWeight = 0; -uint16_t createdVendorId = 0; // Store ID of newly created vendor -uint16_t foundVendorId = 0; // Store ID of found vendor -uint16_t foundFilamentId = 0; // Store ID of found filament -uint16_t createdFilamentId = 0; // Store ID of newly created filament -uint16_t createdSpoolId = 0; // Store ID of newly created spool -uint16_t updateOctoSpoolId = 0; // Store spool ID for OctoPrint update -bool spoolmanConnected = false; -bool spoolmanExtraFieldsChecked = false; -TaskHandle_t* apiTask; +volatile filamanApiStateType filamanApiState = API_IDLE; +bool filamanConnected = false; -struct SendToApiParams { - SpoolmanApiRequestType requestType; - String httpType; - String spoolsUrl; - String updatePayload; - String octoToken; - // Weight update parameters for sequential execution - bool triggerWeightUpdate; - String spoolIdForWeight; - uint16_t weightValue; -}; +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; -JsonDocument fetchSingleSpoolInfo(int spoolId) { HTTPClient http; - String spoolsUrl = spoolmanUrl + apiUrl + "/spool/" + spoolId; + String url = filamanUrl + "/api/v1/devices/register"; + + http.begin(url); + http.addHeader("Content-Type", "application/json"); + http.addHeader("X-Device-Code", deviceCode); + + int httpCode = http.POST("{}"); + bool success = false; - Serial.print("Rufe Spool-Daten von: "); - Serial.println(spoolsUrl); - - http.begin(spoolsUrl); - int httpCode = http.GET(); - - JsonDocument filteredDoc; - if (httpCode == HTTP_CODE_OK) { + if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_CREATED) { String payload = http.getString(); JsonDocument doc; DeserializationError error = deserializeJson(doc, payload); - if (error) { - Serial.print("Fehler beim Parsen der JSON-Antwort: "); - Serial.println(error.c_str()); - } else { - String filamentType = doc["filament"]["material"].as(); - String filamentBrand = doc["filament"]["vendor"]["name"].as(); - - int nozzle_temp_min = 0; - int nozzle_temp_max = 0; - if (doc["filament"]["extra"]["nozzle_temperature"].is()) { - String tempString = doc["filament"]["extra"]["nozzle_temperature"].as(); - tempString.replace("[", ""); - tempString.replace("]", ""); - int commaIndex = tempString.indexOf(','); - - if (commaIndex != -1) { - nozzle_temp_min = tempString.substring(0, commaIndex).toInt(); - nozzle_temp_max = tempString.substring(commaIndex + 1).toInt(); - } - } - - String filamentColor = doc["filament"]["color_hex"].as(); - filamentColor.toUpperCase(); - - String tray_info_idx = doc["filament"]["extra"]["bambu_idx"].as(); - tray_info_idx.replace("\"", ""); - - String cali_idx = doc["filament"]["extra"]["bambu_cali_id"].as(); // "\"153\"" - cali_idx.replace("\"", ""); - - String bambu_setting_id = doc["filament"]["extra"]["bambu_setting_id"].as(); // "\"PFUSf40e9953b40d3d\"" - bambu_setting_id.replace("\"", ""); - - doc.clear(); - - filteredDoc["color"] = filamentColor; - filteredDoc["type"] = filamentType; - filteredDoc["nozzle_temp_min"] = nozzle_temp_min; - filteredDoc["nozzle_temp_max"] = nozzle_temp_max; - filteredDoc["brand"] = filamentBrand; - filteredDoc["tray_info_idx"] = tray_info_idx; - filteredDoc["cali_idx"] = cali_idx; - filteredDoc["bambu_setting_id"] = bambu_setting_id; - } - } else { - Serial.print("Fehler beim Abrufen der Spool-Daten. HTTP-Code: "); - Serial.println(httpCode); - } - - http.end(); - return filteredDoc; -} - -void sendToApi(void *parameter) { - HEAP_DEBUG_MESSAGE("sendToApi begin"); - - // Wait until API is IDLE - while(spoolmanApiState != API_IDLE){ - vTaskDelay(100 / portTICK_PERIOD_MS); - yield(); - } - spoolmanApiState = API_TRANSMITTING; - SendToApiParams* params = (SendToApiParams*)parameter; - - // Extract values including weight update parameters - SpoolmanApiRequestType requestType = params->requestType; - String httpType = params->httpType; - String spoolsUrl = params->spoolsUrl; - String updatePayload = params->updatePayload; - String octoToken = params->octoToken; - bool triggerWeightUpdate = params->triggerWeightUpdate; - String spoolIdForWeight = params->spoolIdForWeight; - uint16_t weightValue = params->weightValue; - - // Retry mechanism with configurable parameters - const uint8_t MAX_RETRIES = 3; - const uint16_t RETRY_DELAY_MS = 1000; // 1 second between retries - const uint16_t HTTP_TIMEOUT_MS = 10000; // 10 second HTTP timeout - - bool success = false; - int httpCode = -1; - String responsePayload = ""; - - // Try request with retries - for (uint8_t attempt = 1; attempt <= MAX_RETRIES && !success; attempt++) { - Serial.printf("API Request attempt %d/%d to: %s\n", attempt, MAX_RETRIES, spoolsUrl.c_str()); - - HTTPClient http; - http.setReuse(false); - http.setTimeout(HTTP_TIMEOUT_MS); // Set HTTP timeout - - http.begin(spoolsUrl); - http.addHeader("Content-Type", "application/json"); - if (octoEnabled && octoToken != "") http.addHeader("X-Api-Key", octoToken); - - // Execute HTTP request based on type - if (httpType == "PATCH") httpCode = http.PATCH(updatePayload); - else if (httpType == "POST") httpCode = http.POST(updatePayload); - else if (httpType == "GET") httpCode = http.GET(); - else httpCode = http.PUT(updatePayload); - - // Check if request was successful - if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_CREATED) { - responsePayload = http.getString(); + if (!error && doc["token"].is()) { + filamanToken = doc["token"].as(); + filamanRegistered = true; + saveFilamanConfig(); success = true; - Serial.printf("API Request successful on attempt %d, HTTP Code: %d\n", attempt, httpCode); - } else { - Serial.printf("API Request failed on attempt %d, HTTP Code: %d (%s)\n", - attempt, httpCode, http.errorToString(httpCode).c_str()); - - // Don't retry on certain error codes (client errors) - if (httpCode >= 400 && httpCode < 500 && httpCode != 408 && httpCode != 429) { - Serial.println("Client error detected, stopping retries"); - break; - } - - // Wait before retry (except on last attempt) - if (attempt < MAX_RETRIES) { - Serial.printf("Waiting %dms before retry...\n", RETRY_DELAY_MS); - http.end(); - vTaskDelay(RETRY_DELAY_MS / portTICK_PERIOD_MS); - continue; - } - } - - http.end(); - } - - // Process successful response - if (success) { - Serial.println("Spoolman Abfrage erfolgreich"); - - // Restgewicht der Spule auslesen - JsonDocument doc; - DeserializationError error = deserializeJson(doc, responsePayload); - if (error) { - Serial.print("Fehler beim Parsen der JSON-Antwort: "); - Serial.println(error.c_str()); - } else { - switch(requestType){ - case API_REQUEST_SPOOL_WEIGHT_UPDATE: - remainingWeight = doc["remaining_weight"].as(); - Serial.print("Aktuelles Gewicht: "); - Serial.println(remainingWeight); - //oledShowMessage("Remaining: " + String(remaining_weight) + "g"); - if(!octoEnabled){ - // TBD: Do not use Strings... - //oledShowProgressBar(1, 1, "Spool Tag", ("Done: " + String(remainingWeight) + " g remain").c_str()); - oledShowMessage("Remaining: " + String(remainingWeight) + "g"); - remainingWeight = 0; - }else{ - // ocoto is enabled, trigger octo update - sendOctoUpdate = true; - } - break; - case API_REQUEST_SPOOL_LOCATION_UPDATE: - oledShowProgressBar(1, 1, "Loc. Tag", "Done!"); - break; - case API_REQUEST_SPOOL_TAG_ID_UPDATE: - oledShowProgressBar(1, 1, "Write Tag", "Done!"); - break; - case API_REQUEST_OCTO_SPOOL_UPDATE: - // TBD: Do not use Strings... - //oledShowProgressBar(5, 5, "Spool Tag", ("Done: " + String(remainingWeight) + " g remain").c_str()); - oledShowMessage("Remaining: " + String(remainingWeight) + "g"); - remainingWeight = 0; - break; - case API_REQUEST_VENDOR_CREATE: - Serial.println("Vendor successfully created!"); - createdVendorId = doc["id"].as(); - Serial.print("Created Vendor ID: "); - Serial.println(createdVendorId); - oledShowProgressBar(1, 1, "Vendor", "Created!"); - break; - case API_REQUEST_VENDOR_CHECK: - if (doc.isNull() || doc.size() == 0) { - Serial.println("Vendor not found in response"); - foundVendorId = 0; - } else { - foundVendorId = doc[0]["id"].as(); - Serial.print("Found Vendor ID: "); - Serial.println(foundVendorId); - } - break; - case API_REQUEST_FILAMENT_CHECK: - if (doc.isNull() || doc.size() == 0) { - Serial.println("Filament not found in response"); - foundFilamentId = 0; - } else { - foundFilamentId = doc[0]["id"].as(); - Serial.print("Found Filament ID: "); - Serial.println(foundFilamentId); - } - break; - case API_REQUEST_FILAMENT_CREATE: - Serial.println("Filament successfully created!"); - createdFilamentId = doc["id"].as(); - Serial.print("Created Filament ID: "); - Serial.println(createdFilamentId); - oledShowProgressBar(1, 1, "Filament", "Created!"); - break; - case API_REQUEST_SPOOL_CREATE: - Serial.println("Spool successfully created!"); - createdSpoolId = doc["id"].as(); - Serial.print("Created Spool ID: "); - Serial.println(createdSpoolId); - oledShowProgressBar(1, 1, "Spool", "Created!"); - break; - } - } - doc.clear(); - } else if (httpCode == HTTP_CODE_CREATED) { - Serial.println("Spoolman erfolgreich erstellt"); - - // Parse response for created resources - JsonDocument doc; - DeserializationError error = deserializeJson(doc, responsePayload); - if (error) { - Serial.print("Fehler beim Parsen der JSON-Antwort: "); - Serial.println(error.c_str()); - } else { - switch(requestType){ - case API_REQUEST_VENDOR_CREATE: - Serial.println("Vendor successfully created!"); - createdVendorId = doc["id"].as(); - Serial.print("Created Vendor ID: "); - Serial.println(createdVendorId); - oledShowProgressBar(1, 1, "Vendor", "Created!"); - break; - case API_REQUEST_FILAMENT_CREATE: - Serial.println("Filament successfully created!"); - createdFilamentId = doc["id"].as(); - Serial.print("Created Filament ID: "); - Serial.println(createdFilamentId); - oledShowProgressBar(1, 1, "Filament", "Created!"); - break; - case API_REQUEST_SPOOL_CREATE: - Serial.println("Spool successfully created!"); - createdSpoolId = doc["id"].as(); - Serial.print("Created Spool ID: "); - Serial.println(createdSpoolId); - oledShowProgressBar(1, 1, "Spool", "Created!"); - break; - default: - // Handle other create operations if needed - break; - } - } - doc.clear(); - - // Execute weight update if requested and tag update was successful - if (triggerWeightUpdate && requestType == API_REQUEST_SPOOL_TAG_ID_UPDATE && weightValue > 10) { - Serial.println("Executing weight update after successful tag update"); - - // Prepare weight update request - String weightUrl = spoolmanUrl + apiUrl + "/spool/" + spoolIdForWeight + "/measure"; - JsonDocument weightDoc; - weightDoc["weight"] = weightValue; - - String weightPayload; - serializeJson(weightDoc, weightPayload); - - Serial.print("Weight update URL: "); - Serial.println(weightUrl); - Serial.print("Weight update payload: "); - Serial.println(weightPayload); - - // Execute weight update - HTTPClient weightHttp; - weightHttp.setReuse(false); - weightHttp.setTimeout(HTTP_TIMEOUT_MS); - weightHttp.begin(weightUrl); - weightHttp.addHeader("Content-Type", "application/json"); - - int weightHttpCode = weightHttp.PUT(weightPayload); - - if (weightHttpCode == HTTP_CODE_OK) { - Serial.println("Weight update successful"); - String weightResponse = weightHttp.getString(); - JsonDocument weightResponseDoc; - DeserializationError weightError = deserializeJson(weightResponseDoc, weightResponse); - - if (!weightError) { - remainingWeight = weightResponseDoc["remaining_weight"].as(); - Serial.print("Updated weight: "); - Serial.println(remainingWeight); - - if (!octoEnabled) { - oledShowProgressBar(1, 1, "Spool Tag", ("Done: " + String(remainingWeight) + " g remain").c_str()); - remainingWeight = 0; - } else { - sendOctoUpdate = true; - } - } - weightResponseDoc.clear(); - } else { - Serial.print("Weight update failed with HTTP code: "); - Serial.println(weightHttpCode); - oledShowProgressBar(1, 1, "Failure!", "Weight update"); - } - - weightHttp.end(); - weightDoc.clear(); + Serial.println("Device successfully registered!"); } } else { - switch(requestType){ - case API_REQUEST_SPOOL_WEIGHT_UPDATE: - case API_REQUEST_SPOOL_LOCATION_UPDATE: - case API_REQUEST_SPOOL_TAG_ID_UPDATE: - oledShowProgressBar(1, 1, "Failure!", "Spoolman update"); - break; - case API_REQUEST_OCTO_SPOOL_UPDATE: - oledShowProgressBar(1, 1, "Failure!", "Octoprint update"); - break; - case API_REQUEST_BAMBU_UPDATE: - oledShowProgressBar(1, 1, "Failure!", "Bambu update"); - break; - case API_REQUEST_VENDOR_CHECK: - oledShowProgressBar(1, 1, "Failure!", "Vendor check"); - foundVendorId = 0; // Set to 0 to indicate error/not found - break; - case API_REQUEST_VENDOR_CREATE: - oledShowProgressBar(1, 1, "Failure!", "Vendor create"); - createdVendorId = 0; // Set to 0 to indicate error - break; - case API_REQUEST_FILAMENT_CHECK: - oledShowProgressBar(1, 1, "Failure!", "Filament check"); - foundFilamentId = 0; // Set to 0 to indicate error/not found - break; - case API_REQUEST_FILAMENT_CREATE: - oledShowProgressBar(1, 1, "Failure!", "Filament create"); - createdFilamentId = 0; // Set to 0 to indicate error - break; - case API_REQUEST_SPOOL_CREATE: - oledShowProgressBar(1, 1, "Failure!", "Spool create"); - createdSpoolId = 0; // Set to 0 to indicate error instead of hanging - break; - } - Serial.println("Fehler beim Senden an Spoolman! HTTP Code: " + String(httpCode)); - vTaskDelay(2000 / portTICK_PERIOD_MS); - nfcReaderState = NFC_IDLE; // Reset NFC state to allow retry + Serial.printf("Registration failed, HTTP code: %d\n", httpCode); } - - vTaskDelay(50 / portTICK_PERIOD_MS); - - // Speicher freigeben - delete params; - HEAP_DEBUG_MESSAGE("sendToApi end"); - spoolmanApiState = API_IDLE; - vTaskDelete(NULL); + + http.end(); + return success; } -bool updateSpoolTagId(String uidString, const char* payload) { - oledShowProgressBar(2, 3, "Write Tag", "Update Spoolman"); +bool sendHeartbeat() { + if (!checkFilamanRegistration()) return false; - JsonDocument doc; - DeserializationError error = deserializeJson(doc, payload); - - if (error) { - Serial.print("Fehler beim JSON-Parsing: "); - Serial.println(error.c_str()); - return false; - } - - // Überprüfe, ob die erforderlichen Felder vorhanden sind - if (!doc["sm_id"].is() || doc["sm_id"].as() == "") { - Serial.println("Keine Spoolman-ID gefunden."); - return false; - } - - String spoolId = doc["sm_id"].as(); - String spoolsUrl = spoolmanUrl + apiUrl + "/spool/" + spoolId; - Serial.print("Update Spule mit URL: "); - Serial.println(spoolsUrl); - - doc.clear(); - - // Update Payload erstellen - JsonDocument updateDoc; - updateDoc["extra"]["nfc_id"] = "\""+uidString+"\""; - - String updatePayload; - serializeJson(updateDoc, updatePayload); - Serial.print("Update Payload: "); - Serial.println(updatePayload); - - SendToApiParams* params = new SendToApiParams(); - if (params == nullptr) { - Serial.println("Fehler: Kann Speicher für Task-Parameter nicht allokieren."); - return false; - } - params->requestType = API_REQUEST_SPOOL_TAG_ID_UPDATE; - params->httpType = "PATCH"; - params->spoolsUrl = spoolsUrl; - params->updatePayload = updatePayload; - - // Add weight update parameters for sequential execution - params->triggerWeightUpdate = (weight > 10); - params->spoolIdForWeight = spoolId; - params->weightValue = weight; - - // Erstelle die Task mit erhöhter Stackgröße für zusätzliche HTTP-Anfrage - BaseType_t result = xTaskCreate( - sendToApi, // Task-Funktion - "SendToApiTask", // Task-Name - 8192, // Erhöhte Stackgröße für zusätzliche HTTP-Anfrage - (void*)params, // Parameter - 0, // Priorität - apiTask // Task-Handle (nicht benötigt) - ); - - updateDoc.clear(); - - // Update Spool weight now handled sequentially in sendToApi task - // to prevent parallel API access issues - - return true; -} - -uint8_t updateSpoolWeight(String spoolId, uint16_t weight) { - HEAP_DEBUG_MESSAGE("updateSpoolWeight begin"); - oledShowProgressBar(3, octoEnabled?5:4, "Spool Tag", "Spoolman update"); - String spoolsUrl = spoolmanUrl + apiUrl + "/spool/" + spoolId + "/measure"; - Serial.print("Update Spule mit URL: "); - Serial.println(spoolsUrl); - - // Update Payload erstellen - JsonDocument updateDoc; - updateDoc["weight"] = weight; - - String updatePayload; - serializeJson(updateDoc, updatePayload); - Serial.print("Update Payload: "); - Serial.println(updatePayload); - - SendToApiParams* params = new SendToApiParams(); - if (params == nullptr) { - // TBD: reset ESP instead of showing a message - Serial.println("Fehler: Kann Speicher für Task-Parameter nicht allokieren."); - return 0; - } - params->requestType = API_REQUEST_SPOOL_WEIGHT_UPDATE; - params->httpType = "PUT"; - params->spoolsUrl = spoolsUrl; - params->updatePayload = updatePayload; - - // Erstelle die Task - BaseType_t result = xTaskCreate( - sendToApi, // Task-Funktion - "SendToApiTask", // Task-Name - 6144, // Stackgröße in Bytes - (void*)params, // Parameter - 0, // Priorität - apiTask // Task-Handle (nicht benötigt) - ); - - updateDoc.clear(); - HEAP_DEBUG_MESSAGE("updateSpoolWeight end"); - - return 1; -} - -uint8_t updateSpoolLocation(String spoolId, String location){ - HEAP_DEBUG_MESSAGE("updateSpoolLocation begin"); - - oledShowProgressBar(3, octoEnabled?5:4, "Loc. Tag", "Spoolman update"); - - String spoolsUrl = spoolmanUrl + apiUrl + "/spool/" + spoolId; - Serial.print("Update Spule mit URL: "); - Serial.println(spoolsUrl); - - // Update Payload erstellen - JsonDocument updateDoc; - updateDoc["location"] = location; - - String updatePayload; - serializeJson(updateDoc, updatePayload); - Serial.print("Update Payload: "); - Serial.println(updatePayload); - - SendToApiParams* params = new SendToApiParams(); - if (params == nullptr) { - Serial.println("Fehler: Kann Speicher für Task-Parameter nicht allokieren."); - return 0; - } - params->requestType = API_REQUEST_SPOOL_LOCATION_UPDATE; - params->httpType = "PATCH"; - params->spoolsUrl = spoolsUrl; - params->updatePayload = updatePayload; - - - if(apiTask == nullptr){ - // Erstelle die Task - BaseType_t result = xTaskCreate( - sendToApi, // Task-Funktion - "SendToApiTask", // Task-Name - 6144, // Stackgröße in Bytes - (void*)params, // Parameter - 0, // Priorität - apiTask // Task-Handle - ); - }else{ - Serial.println("Not spawning new task, API still active!"); - } - - updateDoc.clear(); - - HEAP_DEBUG_MESSAGE("updateSpoolLocation end"); - return 1; -} - -bool updateSpoolOcto(int spoolId) { - oledShowProgressBar(4, octoEnabled?5:4, "Spool Tag", "Octoprint update"); - - String spoolsUrl = octoUrl + "/plugin/Spoolman/selectSpool"; - Serial.print("Update Spule in Octoprint mit URL: "); - Serial.println(spoolsUrl); - - JsonDocument updateDoc; - updateDoc["spool_id"] = spoolId; - updateDoc["tool"] = "tool0"; - - String updatePayload; - serializeJson(updateDoc, updatePayload); - Serial.print("Update Payload: "); - Serial.println(updatePayload); - - SendToApiParams* params = new SendToApiParams(); - if (params == nullptr) { - Serial.println("Fehler: Kann Speicher für Task-Parameter nicht allokieren."); - return false; - } - params->requestType = API_REQUEST_OCTO_SPOOL_UPDATE; - params->httpType = "POST"; - params->spoolsUrl = spoolsUrl; - params->updatePayload = updatePayload; - params->octoToken = octoToken; - - // Erstelle die Task - BaseType_t result = xTaskCreate( - sendToApi, // Task-Funktion - "SendToApiTask", // Task-Name - 6144, // Stackgröße in Bytes - (void*)params, // Parameter - 0, // Priorität - apiTask // Task-Handle (nicht benötigt) - ); - - updateDoc.clear(); - - return true; -} - -bool updateSpoolBambuData(String payload) { - JsonDocument doc; - DeserializationError error = deserializeJson(doc, payload); - if (error) { - Serial.print("Fehler beim JSON-Parsing: "); - Serial.println(error.c_str()); - return false; - } - - String spoolsUrl = spoolmanUrl + apiUrl + "/filament/" + doc["filament_id"].as(); - Serial.print("Update Spule mit URL: "); - Serial.println(spoolsUrl); - - JsonDocument updateDoc; - updateDoc["extra"]["bambu_setting_id"] = "\"" + doc["setting_id"].as() + "\""; - updateDoc["extra"]["bambu_cali_id"] = "\"" + doc["cali_idx"].as() + "\""; - updateDoc["extra"]["bambu_idx"] = "\"" + doc["tray_info_idx"].as() + "\""; - updateDoc["extra"]["nozzle_temperature"] = "[" + doc["temp_min"].as() + "," + doc["temp_max"].as() + "]"; - - String updatePayload; - serializeJson(updateDoc, updatePayload); - - doc.clear(); - updateDoc.clear(); - - Serial.print("Update Payload: "); - Serial.println(updatePayload); - - SendToApiParams* params = new SendToApiParams(); - if (params == nullptr) { - Serial.println("Fehler: Kann Speicher für Task-Parameter nicht allokieren."); - return false; - } - params->requestType = API_REQUEST_BAMBU_UPDATE; - params->httpType = "PATCH"; - params->spoolsUrl = spoolsUrl; - params->updatePayload = updatePayload; - - // Erstelle die Task - BaseType_t result = xTaskCreate( - sendToApi, // Task-Funktion - "SendToApiTask", // Task-Name - 6144, // Stackgröße in Bytes - (void*)params, // Parameter - 0, // Priorität - apiTask // Task-Handle (nicht benötigt) - ); - - return true; -} - -// #### Brand Filament -uint16_t createVendor(const JsonDocument& payload) { - oledShowProgressBar(2, 5, "New Brand", "Create new Vendor"); - - // Create new vendor in Spoolman database using task system - // Note: Due to async nature, the ID will be stored in createdVendorId global variable - // Note: This function assumes that the caller has already ensured API is IDLE - createdVendorId = 65535; // Reset previous value - - String spoolsUrl = spoolmanUrl + apiUrl + "/vendor"; - Serial.print("Create vendor with URL: "); - Serial.println(spoolsUrl); - - // Create JSON payload for vendor creation - JsonDocument vendorDoc; - vendorDoc["name"] = payload["b"].as(); - - // Extract domain from URL if present, otherwise use brand name - String externalId = ""; - if (payload["u"].is()) { - String url = payload["u"].as(); - // Extract domain from URL (e.g., "https://www.blubb.de/f1234/?suche=irgendwas" -> "https://www.blubb.de") - int protocolEnd = url.indexOf("://"); - if (protocolEnd != -1) { - int pathStart = url.indexOf("/", protocolEnd + 3); - externalId = (pathStart != -1) ? url.substring(0, pathStart) : url; - } else { - externalId = url; // No protocol found, use as is - } - } else { - externalId = payload["b"].as(); - } - vendorDoc["comment"] = externalId; - - String vendorPayload; - serializeJson(vendorDoc, vendorPayload); - Serial.print("Vendor Payload: "); - Serial.println(vendorPayload); - - SendToApiParams* params = new SendToApiParams(); - if (params == nullptr) { - Serial.println("Fehler: Kann Speicher für Task-Parameter nicht allokieren."); - vendorDoc.clear(); - return 0; - } - params->requestType = API_REQUEST_VENDOR_CREATE; - params->httpType = "POST"; - params->spoolsUrl = spoolsUrl; - params->updatePayload = vendorPayload; - - // Create task without additional API state check since caller ensures synchronization - BaseType_t result = xTaskCreate( - sendToApi, // Task-Funktion - "SendToApiTask", // Task-Name - 6144, // Stackgröße in Bytes - (void*)params, // Parameter - 0, // Priorität - NULL // Task-Handle (nicht benötigt) - ); - - if (result != pdPASS) { - Serial.println("Failed to create vendor task!"); - delete params; - vendorDoc.clear(); - return 0; - } - - vendorDoc.clear(); - - // Delay for Display Bar - vTaskDelay(1000 / portTICK_PERIOD_MS); - - // Wait for task completion and return the created vendor ID - // Note: createdVendorId will be set by sendToApi when response is received - while(createdVendorId == 65535) { - vTaskDelay(50 / portTICK_PERIOD_MS); - } - - return createdVendorId; -} - -uint16_t checkVendor(const JsonDocument& payload) { - oledShowProgressBar(1, 5, "New Brand", "Check Vendor"); - - // Check if vendor exists using task system - foundVendorId = 65535; // Reset to invalid value to detect when API response is received - - String vendorName = payload["b"].as(); - vendorName.trim(); - vendorName.replace(" ", "+"); - String spoolsUrl = spoolmanUrl + apiUrl + "/vendor?name=" + vendorName; - Serial.print("Check vendor with URL: "); - Serial.println(spoolsUrl); - - SendToApiParams* params = new SendToApiParams(); - if (params == nullptr) { - Serial.println("Fehler: Kann Speicher für Task-Parameter nicht allokieren."); - return 0; - } - params->requestType = API_REQUEST_VENDOR_CHECK; - params->httpType = "GET"; - params->spoolsUrl = spoolsUrl; - params->updatePayload = ""; // Empty for GET request - - // Check if API is idle before creating task - while (spoolmanApiState != API_IDLE) - { - vTaskDelay(100 / portTICK_PERIOD_MS); - } - - // Erstelle die Task - BaseType_t result = xTaskCreate( - sendToApi, // Task-Funktion - "SendToApiTask", // Task-Name - 6144, // Stackgröße in Bytes - (void*)params, // Parameter - 0, // Priorität - NULL // Task-Handle (nicht benötigt) - ); - - // Wait until foundVendorId is updated by the API response (not 65535 anymore) - while (foundVendorId == 65535) - { - vTaskDelay(50 / portTICK_PERIOD_MS); - } - - // Check if vendor was found - if (foundVendorId == 0) { - Serial.println("Vendor not found, creating new vendor..."); - uint16_t vendorId = createVendor(payload); - if (vendorId == 0) { - Serial.println("Failed to create vendor, returning 0."); - return 0; // Failed to create vendor - } else { - Serial.println("Vendor created with ID: " + String(vendorId)); - return vendorId; - } - } else { - Serial.println("Vendor found: " + payload["b"].as()); - Serial.print("Vendor ID: "); - Serial.println(foundVendorId); - return foundVendorId; - } -} - -uint16_t createFilament(uint16_t vendorId, const JsonDocument& payload) { - oledShowProgressBar(4, 5, "New Brand", "Create Filament"); - - // Create new filament in Spoolman database using task system - // Note: Due to async nature, the ID will be stored in createdFilamentId global variable - // Note: This function assumes that the caller has already ensured API is IDLE - createdFilamentId = 65535; // Reset previous value - - String spoolsUrl = spoolmanUrl + apiUrl + "/filament"; - Serial.print("Create filament with URL: "); - Serial.println(spoolsUrl); - - // Create JSON payload for filament creation - JsonDocument filamentDoc; - filamentDoc["name"] = payload["cn"].as(); - filamentDoc["vendor_id"] = String(vendorId); - filamentDoc["material"] = payload["t"].as(); - filamentDoc["density"] = (payload["de"].is() && payload["de"].as().length() > 0) ? payload["de"].as() : "1.24"; - filamentDoc["diameter"] = (payload["di"].is() && payload["di"].as().length() > 0) ? payload["di"].as() : "1.75"; - filamentDoc["weight"] = String(weight); - filamentDoc["spool_weight"] = payload["sw"].as(); - filamentDoc["article_number"] = payload["an"].as(); - filamentDoc["settings_extruder_temp"] = payload["et"].is() ? payload["et"].as() : ""; - filamentDoc["settings_bed_temp"] = payload["bt"].is() ? payload["bt"].as() : ""; - - if (payload["an"].is()) - { - filamentDoc["external_id"] = payload["an"].as(); - filamentDoc["comment"] = payload["u"].is() ? payload["u"].as() + payload["an"].as() : "automatically generated"; - } - else - { - filamentDoc["comment"] = payload["u"].is() ? payload["u"].as() : "automatically generated"; - } - - if (payload["mc"].is()) { - filamentDoc["multi_color_hexes"] = payload["mc"].as(); - filamentDoc["multi_color_direction"] = payload["mcd"].is() ? payload["mcd"].as() : ""; - } - else - { - filamentDoc["color_hex"] = (payload["c"].is() && payload["c"].as().length() >= 6) ? payload["c"].as() : "FFFFFF"; - } - - String filamentPayload; - serializeJson(filamentDoc, filamentPayload); - Serial.print("Filament Payload: "); - Serial.println(filamentPayload); - - SendToApiParams* params = new SendToApiParams(); - if (params == nullptr) { - Serial.println("Fehler: Kann Speicher für Task-Parameter nicht allokieren."); - filamentDoc.clear(); - return 0; - } - params->requestType = API_REQUEST_FILAMENT_CREATE; - params->httpType = "POST"; - params->spoolsUrl = spoolsUrl; - params->updatePayload = filamentPayload; - - // Create task without additional API state check since caller ensures synchronization - BaseType_t result = xTaskCreate( - sendToApi, // Task-Funktion - "SendToApiTask", // Task-Name - 6144, // Stackgröße in Bytes - (void*)params, // Parameter - 0, // Priorität - NULL // Task-Handle (nicht benötigt) - ); - - if (result != pdPASS) { - Serial.println("Failed to create filament task!"); - delete params; - filamentDoc.clear(); - return 0; - } - - filamentDoc.clear(); - - // Delay for Display Bar - vTaskDelay(1000 / portTICK_PERIOD_MS); - - // Wait for task completion and return the created filament ID - // Note: createdFilamentId will be set by sendToApi when response is received - while(createdFilamentId == 65535) { - vTaskDelay(50 / portTICK_PERIOD_MS); - } - - return createdFilamentId; -} - -uint16_t checkFilament(uint16_t vendorId, const JsonDocument& payload) { - oledShowProgressBar(3, 5, "New Brand", "Check Filament"); - - // Check if filament exists using task system - foundFilamentId = 65535; // Reset to invalid value to detect when API response is received - - String spoolsUrl = spoolmanUrl + apiUrl + "/filament?vendor.id=" + String(vendorId) + "&external_id=" + String(payload["artnr"].as()); - Serial.print("Check filament with URL: "); - Serial.println(spoolsUrl); - - SendToApiParams* params = new SendToApiParams(); - if (params == nullptr) { - Serial.println("Fehler: Kann Speicher für Task-Parameter nicht allokieren."); - return 0; - } - params->requestType = API_REQUEST_FILAMENT_CHECK; - params->httpType = "GET"; - params->spoolsUrl = spoolsUrl; - params->updatePayload = ""; // Empty for GET request - - // Erstelle die Task - BaseType_t result = xTaskCreate( - sendToApi, // Task-Funktion - "SendToApiTask", // Task-Name - 6144, // Stackgröße in Bytes - (void*)params, // Parameter - 0, // Priorität - NULL // Task-Handle (nicht benötigt) - ); - - // Wait until foundFilamentId is updated by the API response (not 65535 anymore) - while (foundFilamentId == 65535) { - vTaskDelay(50 / portTICK_PERIOD_MS); - } - - // Check if filament was found - if (foundFilamentId == 0) { - Serial.println("Filament not found, creating new filament..."); - uint16_t filamentId = createFilament(vendorId, payload); - if (filamentId == 0) { - Serial.println("Failed to create filament, returning 0."); - return 0; // Failed to create filament - } else { - Serial.println("Filament created with ID: " + String(filamentId)); - return filamentId; - } - } else { - Serial.println("Filament found for vendor ID: " + String(vendorId)); - Serial.print("Filament ID: "); - Serial.println(foundFilamentId); - return foundFilamentId; - } -} - -uint16_t createSpool(uint16_t vendorId, uint16_t filamentId, JsonDocument& payload, String uidString) { - oledShowProgressBar(5, 5, "New Brand", "Create new Spool"); - - // Create new spool in Spoolman database using task system - // Note: Due to async nature, the ID will be stored in createdSpoolId global variable - // Note: This function assumes that the caller has already ensured API is IDLE - createdSpoolId = 65535; // Reset to invalid value to detect when API response is received - - String spoolsUrl = spoolmanUrl + apiUrl + "/spool"; - Serial.print("Create spool with URL: "); - Serial.println(spoolsUrl); - - // Create JSON payload for spool creation - JsonDocument spoolDoc; - spoolDoc["filament_id"] = String(filamentId); - spoolDoc["initial_weight"] = weight > 10 ? String(weight - payload["sw"].as()) : "1000"; - spoolDoc["spool_weight"] = (payload["sw"].is() && payload["sw"].as().length() > 0) ? payload["sw"].as() : "180"; - spoolDoc["remaining_weight"] = spoolDoc["initial_weight"]; - spoolDoc["lot_nr"] = (payload["an"].is() && payload["an"].as().length() > 0) ? payload["an"].as() : ""; - spoolDoc["comment"] = "automatically generated"; - spoolDoc["extra"]["nfc_id"] = "\"" + uidString + "\""; - - String spoolPayload; - serializeJson(spoolDoc, spoolPayload); - Serial.print("Spool Payload: "); - Serial.println(spoolPayload); - spoolDoc.clear(); - - SendToApiParams* params = new SendToApiParams(); - if (params == nullptr) { - Serial.println("Fehler: Kann Speicher für Task-Parameter nicht allokieren."); - spoolDoc.clear(); - return 0; - } - params->requestType = API_REQUEST_SPOOL_CREATE; - params->httpType = "POST"; - params->spoolsUrl = spoolsUrl; - params->updatePayload = spoolPayload; - - // Create task without additional API state check since caller ensures synchronization - BaseType_t result = xTaskCreate( - sendToApi, // Task-Funktion - "SendToApiTask", // Task-Name - 6144, // Stackgröße in Bytes - (void*)params, // Parameter - 0, // Priorität - NULL // Task-Handle (nicht benötigt) - ); - - if (result != pdPASS) { - Serial.println("Failed to create spool task!"); - delete params; - return 0; - } - - // Wait for task completion and return the created spool ID - // Note: createdSpoolId will be set by sendToApi when response is received - while(createdSpoolId == 65535) { - vTaskDelay(50 / portTICK_PERIOD_MS); - } - - // Check if spool creation was successful - if (createdSpoolId == 0) { - Serial.println("ERROR: Spool creation failed"); - nfcReaderState = NFC_IDLE; // Reset NFC state - return 0; - } - - // Write data to tag with startWriteJsonToTag - // void startWriteJsonToTag(const bool isSpoolTag, const char* payload); - - // Create optimized JSON structure with sm_id at the beginning for fast-path detection - JsonDocument optimizedPayload; - optimizedPayload["sm_id"] = String(createdSpoolId); // Place sm_id first for fast scanning - optimizedPayload["b"] = payload["b"].as(); - optimizedPayload["cn"] = payload["an"].as(); - - String payloadString; - serializeJson(optimizedPayload, payloadString); - - Serial.println("Optimized JSON with sm_id first:"); - Serial.println(payloadString); - - optimizedPayload.clear(); - - nfcReaderState = NFC_IDLE; - - // Delay for Display Bar - vTaskDelay(1000 / portTICK_PERIOD_MS); - - startWriteJsonToTag(true, payloadString.c_str()); - - return createdSpoolId; -} - -bool createBrandFilament(JsonDocument& payload, String uidString) { - uint16_t vendorId = checkVendor(payload); - if (vendorId == 0) { - Serial.println("ERROR: Failed to create/find vendor"); - return false; - } - - uint16_t filamentId = checkFilament(vendorId, payload); - if (filamentId == 0) { - Serial.println("ERROR: Failed to create/find filament"); - return false; - } - - uint16_t spoolId = createSpool(vendorId, filamentId, payload, uidString); - if (spoolId == 0) { - Serial.println("ERROR: Failed to create spool"); - return false; - } - - Serial.println("SUCCESS: Brand filament created with Spool ID: " + String(spoolId)); - return true; -} - -// #### Spoolman init -bool checkSpoolmanExtraFields() { - // Only check extra fields if they have not been checked before - if(!spoolmanExtraFieldsChecked){ - HTTPClient http; - String checkUrls[] = { - spoolmanUrl + apiUrl + "/field/spool", - spoolmanUrl + apiUrl + "/field/filament" - }; - - String spoolExtra[] = { - "nfc_id" - }; - - String filamentExtra[] = { - "nozzle_temperature", - "price_meter", - "price_gramm", - "bambu_setting_id", - "bambu_cali_id", - "bambu_idx", - "bambu_k", - "bambu_flow_ratio", - "bambu_max_volspeed" - }; - - String spoolExtraFields[] = { - "{\"name\": \"NFC ID\"," - "\"key\": \"nfc_id\"," - "\"field_type\": \"text\"}" - }; - - String filamentExtraFields[] = { - "{\"name\": \"Nozzle Temp\"," - "\"unit\": \"°C\"," - "\"field_type\": \"integer_range\"," - "\"default_value\": \"[190,230]\"," - "\"key\": \"nozzle_temperature\"}", - - "{\"name\": \"Price/m\"," - "\"unit\": \"€\"," - "\"field_type\": \"float\"," - "\"key\": \"price_meter\"}", - - "{\"name\": \"Price/g\"," - "\"unit\": \"€\"," - "\"field_type\": \"float\"," - "\"key\": \"price_gramm\"}", - - "{\"name\": \"Bambu Setting ID\"," - "\"field_type\": \"text\"," - "\"key\": \"bambu_setting_id\"}", - - "{\"name\": \"Bambu Cali ID\"," - "\"field_type\": \"text\"," - "\"key\": \"bambu_cali_id\"}", - - "{\"name\": \"Bambu Filament IDX\"," - "\"field_type\": \"text\"," - "\"key\": \"bambu_idx\"}", - - "{\"name\": \"Bambu k\"," - "\"field_type\": \"float\"," - "\"key\": \"bambu_k\"}", - - "{\"name\": \"Bambu Flow Ratio\"," - "\"field_type\": \"float\"," - "\"key\": \"bambu_flow_ratio\"}", - - "{\"name\": \"Bambu Max Vol. Speed\"," - "\"unit\": \"mm3/s\"," - "\"field_type\": \"integer\"," - "\"default_value\": \"12\"," - "\"key\": \"bambu_max_volspeed\"}" - }; - - Serial.println("Überprüfe Extrafelder..."); - - int urlLength = sizeof(checkUrls) / sizeof(checkUrls[0]); - - for (uint8_t i = 0; i < urlLength; i++) { - Serial.println(); - Serial.println("-------- Prüfe Felder für "+checkUrls[i]+" --------"); - http.begin(checkUrls[i]); - int httpCode = http.GET(); - - if (httpCode == HTTP_CODE_OK) { - String payload = http.getString(); - JsonDocument doc; - DeserializationError error = deserializeJson(doc, payload); - if (!error) { - String* extraFields; - String* extraFieldData; - u16_t extraLength; - - if (i == 0) { - extraFields = spoolExtra; - extraFieldData = spoolExtraFields; - extraLength = sizeof(spoolExtra) / sizeof(spoolExtra[0]); - } else { - extraFields = filamentExtra; - extraFieldData = filamentExtraFields; - extraLength = sizeof(filamentExtra) / sizeof(filamentExtra[0]); - } - - for (uint8_t s = 0; s < extraLength; s++) { - bool found = false; - for (JsonObject field : doc.as()) { - if (field["key"].is() && field["key"] == extraFields[s]) { - Serial.println("Feld gefunden: " + extraFields[s]); - found = true; - break; - } - } - if (!found) { - Serial.println("Feld nicht gefunden: " + extraFields[s]); - - // Extrafeld hinzufügen - http.begin(checkUrls[i] + "/" + extraFields[s]); - http.addHeader("Content-Type", "application/json"); - int httpCode = http.POST(extraFieldData[s]); - - if (httpCode > 0) { - // Antwortscode und -nachricht abrufen - String response = http.getString(); - //Serial.println("HTTP-Code: " + String(httpCode)); - //Serial.println("Antwort: " + response); - if (httpCode != HTTP_CODE_OK) { - - return false; - } - } else { - // Fehler beim Senden der Anfrage - Serial.println("Fehler beim Senden der Anfrage: " + String(http.errorToString(httpCode))); - return false; - } - //http.end(); - } - yield(); - vTaskDelay(100 / portTICK_PERIOD_MS); - } - } - doc.clear(); - } - } - - Serial.println("-------- ENDE Prüfe Felder --------"); - Serial.println(); - - http.end(); - - spoolmanExtraFieldsChecked = true; - return true; - }else{ - return true; - } -} - -bool checkSpoolmanInstance() { HTTPClient http; - bool returnValue = false; - - // Only do the spoolman instance check if there is no active API request going on - if(spoolmanApiState == API_IDLE){ - spoolmanApiState = API_TRANSMITTING; - String healthUrl = spoolmanUrl + apiUrl + "/health"; - - Serial.print("Checking spoolman instance: "); - Serial.println(healthUrl); - - http.begin(healthUrl); - int httpCode = http.GET(); - - if (httpCode > 0) { - if (httpCode == HTTP_CODE_OK) { - String payload = http.getString(); - JsonDocument doc; - DeserializationError error = deserializeJson(doc, payload); - if (!error && doc["status"].is()) { - const char* status = doc["status"]; - http.end(); - - if (!checkSpoolmanExtraFields()) { - Serial.println("Fehler beim Überprüfen der Extrafelder."); - - // TBD - oledShowMessage("Spoolman Error creating Extrafields"); - vTaskDelay(2000 / portTICK_PERIOD_MS); - - return false; - } - - spoolmanApiState = API_IDLE; - oledShowTopRow(); - spoolmanConnected = true; - returnValue = strcmp(status, "healthy") == 0; - }else{ - spoolmanConnected = false; - } - - doc.clear(); - }else{ - spoolmanConnected = false; - } - } else { - spoolmanConnected = false; - Serial.println("Error contacting spoolman instance! HTTP Code: " + String(httpCode)); - } - http.end(); - spoolmanApiState = API_IDLE; - } - else - { - // If the check is skipped, return the previous status - Serial.println("Skipping spoolman healthcheck, API is active."); - returnValue = spoolmanConnected; - } - Serial.println("Healthcheck completed!"); - return returnValue; -} - -bool saveSpoolmanUrl(const String& url, bool octoOn, const String& octo_url, const String& octoTk) { - Preferences preferences; - preferences.begin(NVS_NAMESPACE_API, false); // false = readwrite - preferences.putString(NVS_KEY_SPOOLMAN_URL, url); - preferences.putBool(NVS_KEY_OCTOPRINT_ENABLED, octoOn); - preferences.putString(NVS_KEY_OCTOPRINT_URL, octo_url); - preferences.putString(NVS_KEY_OCTOPRINT_TOKEN, octoTk); - preferences.end(); - - //TBD: This could be handled nicer in the future - spoolmanExtraFieldsChecked = false; - spoolmanUrl = url; - octoEnabled = octoOn; - octoUrl = octo_url; - octoToken = octoTk; - - return checkSpoolmanInstance(); -} - -String loadSpoolmanUrl() { - Preferences preferences; - preferences.begin(NVS_NAMESPACE_API, true); - String spoolmanUrl = preferences.getString(NVS_KEY_SPOOLMAN_URL, ""); - octoEnabled = preferences.getBool(NVS_KEY_OCTOPRINT_ENABLED, false); - if(octoEnabled) - { - octoUrl = preferences.getString(NVS_KEY_OCTOPRINT_URL, ""); - octoToken = preferences.getString(NVS_KEY_OCTOPRINT_TOKEN, ""); - } - preferences.end(); - return spoolmanUrl; -} - -bool initSpoolman() { - oledShowProgressBar(3, 7, DISPLAY_BOOT_TEXT, "Spoolman init"); - spoolmanUrl = loadSpoolmanUrl(); + String url = filamanUrl + "/api/v1/devices/heartbeat"; - bool success = checkSpoolmanInstance(); - if (!success) { - Serial.println("Spoolman not available"); - return false; + http.begin(url); + 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); + bool success = (httpCode == HTTP_CODE_OK); + + if (success) { + filamanConnected = true; + } else { + Serial.printf("Heartbeat failed, HTTP code: %d\n", httpCode); + if (httpCode == 401) { + filamanRegistered = false; // Token might be invalid + saveFilamanConfig(); + } + filamanConnected = false; } + + http.end(); + return success; +} +bool sendWeight(int spoolId, String tagUuid, float measuredWeight) { + if (!checkFilamanRegistration()) return false; + + HTTPClient http; + String url = filamanUrl + "/api/v1/devices/scale/weight"; + + http.begin(url); + http.addHeader("Content-Type", "application/json"); + http.addHeader("Authorization", "Device " + filamanToken); + + JsonDocument doc; + if (spoolId > 0) doc["spool_id"] = spoolId; + if (tagUuid.length() > 0) doc["tag_uuid"] = tagUuid; + doc["measured_weight_g"] = measuredWeight; + + String payload; + serializeJson(doc, payload); + + int httpCode = http.POST(payload); + bool success = (httpCode == HTTP_CODE_OK); + + if (!success) { + Serial.printf("Weight update failed, HTTP code: %d\n", httpCode); + } + + http.end(); + return success; +} + +bool sendLocation(int spoolId, String spoolTagUuid, int locationId, String locationTagUuid) { + if (!checkFilamanRegistration()) return false; + + HTTPClient http; + String url = filamanUrl + "/api/v1/devices/scale/locate"; + + http.begin(url); + 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); + bool success = (httpCode == HTTP_CODE_OK); + + if (!success) { + Serial.printf("Location update failed, HTTP code: %d\n", httpCode); + } + + http.end(); + return success; +} + +bool initFilaman() { + oledShowProgressBar(3, 7, DISPLAY_BOOT_TEXT, "FilaMan init"); + loadFilamanConfig(); + + if (checkFilamanRegistration()) { + sendHeartbeat(); + } + oledShowTopRow(); return true; -} \ No newline at end of file +} diff --git a/src/api.h b/src/api.h index a8aac63..7add678 100644 --- a/src/api.h +++ b/src/api.h @@ -2,50 +2,36 @@ #define API_H #include -#include // Include for AsyncWebServerRequest +#include #include "website.h" #include "display.h" #include + typedef enum { - API_INIT, API_IDLE, API_TRANSMITTING -} spoolmanApiStateType; +} filamanApiStateType; typedef enum { - API_REQUEST_OCTO_SPOOL_UPDATE, - API_REQUEST_BAMBU_UPDATE, - API_REQUEST_SPOOL_TAG_ID_UPDATE, - API_REQUEST_SPOOL_WEIGHT_UPDATE, - API_REQUEST_SPOOL_LOCATION_UPDATE, - API_REQUEST_VENDOR_CREATE, - API_REQUEST_VENDOR_CHECK, - API_REQUEST_FILAMENT_CHECK, - API_REQUEST_FILAMENT_CREATE, - API_REQUEST_SPOOL_CREATE -} SpoolmanApiRequestType; + API_REQUEST_REGISTER, + API_REQUEST_HEARTBEAT, + API_REQUEST_WEIGHT, + API_REQUEST_LOCATE +} FilamanApiRequestType; -extern volatile spoolmanApiStateType spoolmanApiState; -extern bool spoolman_connected; -extern String spoolmanUrl; -extern bool octoEnabled; -extern bool sendOctoUpdate; -extern String octoUrl; -extern String octoToken; -extern bool spoolmanConnected; -extern uint16_t updateOctoSpoolId; +extern volatile filamanApiStateType filamanApiState; +extern bool filamanConnected; -bool checkSpoolmanInstance(); -bool saveSpoolmanUrl(const String& url, bool octoOn, const String& octoWh, const String& octoTk); -String loadSpoolmanUrl(); // Neue Funktion zum Laden der URL -bool checkSpoolmanExtraFields(); // Neue Funktion zum Überprüfen der Extrafelder -JsonDocument fetchSingleSpoolInfo(int spoolId); // API-Funktion für die Webseite -bool updateSpoolTagId(String uidString, const char* payload); // Neue Funktion zum Aktualisieren eines Spools -uint8_t updateSpoolWeight(String spoolId, uint16_t weight); // Neue Funktion zum Aktualisieren des Gewichts -uint8_t updateSpoolLocation(String spoolId, String location); -bool initSpoolman(); // Neue Funktion zum Initialisieren von Spoolman -bool updateSpoolBambuData(String payload); // Neue Funktion zum Aktualisieren der Bambu-Daten -bool updateSpoolOcto(int spoolId); // Neue Funktion zum Aktualisieren der Octo-Daten -bool createBrandFilament(JsonDocument& payload, String uidString); +// FilaMan API functions +bool initFilaman(); +bool registerDevice(const String& deviceCode); +bool sendHeartbeat(); +bool sendWeight(int spoolId, String tagUuid, float weight); +bool sendLocation(int spoolId, String spoolTagUuid, int locationId, String locationTagUuid); + +// Helper functions +void saveFilamanConfig(); +void loadFilamanConfig(); +bool checkFilamanRegistration(); #endif diff --git a/src/config.cpp b/src/config.cpp index bd5cdb4..34cd7b5 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -37,7 +37,9 @@ const uint8_t webserverPort = 80; // ***** Webserver // ***** API -const char* apiUrl = "/api/v1"; +String filamanUrl = ""; +String filamanToken = ""; +bool filamanRegistered = false; // ***** API // ***** Bambu Auto Set Spool diff --git a/src/config.h b/src/config.h index 5902712..61e6b05 100644 --- a/src/config.h +++ b/src/config.h @@ -3,19 +3,16 @@ #include -#define BAMBU_DEFAULT_AUTOSEND_TIME 60 - #define NVS_NAMESPACE_API "api" #define NVS_KEY_FILAMAN_URL "filamanUrl" #define NVS_KEY_FILAMAN_TOKEN "filamanToken" +#define NVS_KEY_FILAMAN_REGISTERED "registered" #define NVS_NAMESPACE_SCALE "scale" #define NVS_KEY_CALIBRATION "cal_value" #define NVS_KEY_AUTOTARE "auto_tare" #define SCALE_DEFAULT_CALIBRATION_VALUE 430.0f; -#define BAMBU_USERNAME "bblp" - #define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin) #define SCREEN_ADDRESS 0x3CU // See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32 #define SCREEN_WIDTH 128U @@ -26,7 +23,7 @@ #define WIFI_CHECK_INTERVAL 60000U #define DISPLAY_UPDATE_INTERVAL 1000U -#define SPOOLMAN_HEALTHCHECK_INTERVAL 60000U +#define FILAMAN_HEARTBEAT_INTERVAL 60000U extern const uint8_t PN532_IRQ; extern const uint8_t PN532_RESET; @@ -43,7 +40,10 @@ extern const uint8_t OLED_TOP_END; extern const uint8_t OLED_DATA_START; extern const uint8_t OLED_DATA_END; -extern const char* apiUrl; +extern String filamanUrl; +extern String filamanToken; +extern bool filamanRegistered; + extern const uint8_t webserverPort; diff --git a/src/main.cpp b/src/main.cpp index 1880ea3..10e3f82 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -39,8 +39,8 @@ void setup() { // Webserver setupWebserver(server); - // Spoolman API - initSpoolman(); + // FilaMan API + initFilaman(); // NFC Reader startNfc(); @@ -85,17 +85,7 @@ bool intervalElapsed(unsigned long currentTime, unsigned long &lastTime, unsigne unsigned long lastWeightReadTime = 0; const unsigned long weightReadInterval = 1000; // 1 second -unsigned long lastAutoSetBambuAmsTime = 0; -const unsigned long autoSetBambuAmsInterval = 1000; // 1 second -uint8_t autoAmsCounter = 0; - -uint8_t weightSend = 0; -int16_t lastWeight = 0; - -// WIFI check variables -unsigned long lastWifiCheckTime = 0; -unsigned long lastTopRowUpdateTime = 0; -unsigned long lastSpoolmanHealcheckTime = 0; +unsigned long lastFilamanHeartbeatTime = 0; // Button debounce variables unsigned long lastButtonPress = 0; @@ -124,10 +114,10 @@ void loop() { oledShowTopRow(); } - // Periodic spoolman health check - if (intervalElapsed(currentMillis, lastSpoolmanHealcheckTime, SPOOLMAN_HEALTHCHECK_INTERVAL)) + // Periodic FilaMan heartbeat + if (intervalElapsed(currentMillis, lastFilamanHeartbeatTime, FILAMAN_HEARTBEAT_INTERVAL)) { - checkSpoolmanInstance(); + sendHeartbeat(); } // If scale is not calibrated, only show a warning @@ -147,7 +137,7 @@ void loop() { { // Use filtered weight for smooth display, but still check API weight for significant changes int16_t displayWeight = getFilteredDisplayWeight(); - if (mainTaskWasPaused || (weight != lastWeight && nfcReaderState == NFC_IDLE && (!bambuCredentials.autosend_enable || autoSetToBambuSpoolId == 0))) + if (mainTaskWasPaused || (weight != lastWeight && nfcReaderState == NFC_IDLE)) { (displayWeight < 2) ? ((displayWeight < -2) ? oledShowMessage("!! -0") : oledShowWeight(0)) : oledShowWeight(displayWeight); } @@ -184,29 +174,29 @@ void loop() { lastWeight = weight; - // Wenn ein Tag mit SM id erkannte wurde und der Waage Counter anspricht an SM Senden - if (activeSpoolId != "" && weightCounterToApi > 3 && weightSend == 0 && nfcReaderState == NFC_READ_SUCCESS && tagProcessed == false && spoolmanApiState == API_IDLE) + // Wenn ein Tag erkannt wurde und das Gewicht stabil ist, an FilaMan senden + if (weightCounterToApi > 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(); + if (sendWeight(sId, activeTagUuid, weight)) { + weightSend = 1; + Serial.println("Weight sent to FilaMan"); + } } - // Handle successful tag write: Send weight to Spoolman but NEVER auto-send to Bambu - if (activeSpoolId != "" && weightCounterToApi > 3 && weightSend == 0 && nfcReaderState == NFC_WRITE_SUCCESS && tagProcessed == false && spoolmanApiState == API_IDLE) + // Handle successful tag write + if (nfcReaderState == NFC_WRITE_SUCCESS && tagProcessed == false) { - // set the current tag as processed to prevent it beeing processed again tagProcessed = true; - - if (updateSpoolWeight(activeSpoolId, weight)) - { - weightSend = 1; - Serial.println("Tag written: Weight sent to Spoolman, but NO auto-send to Bambu"); - // INTENTIONALLY do NOT set autoSetToBambuSpoolId here to prevent Bambu auto-send - } - else - { - oledShowIcon("failed"); - vTaskDelay(2000 / portTICK_PERIOD_MS); + int sId = activeSpoolId.toInt(); + if (sendWeight(sId, activeTagUuid, weight)) { + weightSend = 1; + Serial.println("Weight sent to FilaMan after tag write"); } } } diff --git a/src/nfc.cpp b/src/nfc.cpp index d16c3dd..7c931c0 100644 --- a/src/nfc.cpp +++ b/src/nfc.cpp @@ -16,10 +16,10 @@ TaskHandle_t RfidReaderTask; JsonDocument rfidData; String activeSpoolId = ""; +String activeTagUuid = ""; String lastSpoolId = ""; String nfcJsonData = ""; bool tagProcessed = false; -volatile bool pauseBambuMqttTask = false; volatile bool nfcReadingTaskSuspendRequest = false; volatile bool nfcReadingTaskSuspendState = false; volatile bool nfcWriteInProgress = false; // Prevent any tag operations during write @@ -1241,55 +1241,33 @@ bool decodeNdefAndReturnJson(const byte* encodedMessage, String uidString) { { nfcJsonData = ""; Serial.println("Fehler beim Verarbeiten des JSON-Dokuments"); - Serial.print("deserializeJson() failed: "); - Serial.println(error.f_str()); return false; } else { - // If spoolman is unavailable, there is no point in continuing - if(spoolmanConnected){ - // Sende die aktualisierten AMS-Daten an alle WebSocket-Clients + if(filamanConnected){ Serial.println("JSON-Dokument erfolgreich verarbeitet"); - Serial.println(doc.as()); if (doc["sm_id"].is() && doc["sm_id"] != "" && doc["sm_id"] != "0") { - oledShowProgressBar(2, octoEnabled?5:4, "Spool Tag", "Weighing"); - Serial.println("SPOOL-ID gefunden: " + doc["sm_id"].as()); + oledShowProgressBar(2, 4, "Spool Tag", "Weighing"); activeSpoolId = doc["sm_id"].as(); lastSpoolId = activeSpoolId; } - else if(doc["location"].is() && doc["location"] != "") + else if(doc["location_id"].is()) { Serial.println("Location Tag found!"); - String location = doc["location"].as(); - if(lastSpoolId != ""){ - updateSpoolLocation(lastSpoolId, location); - } - else - { - Serial.println("Location update tag scanned without scanning spool before!"); - oledShowProgressBar(1, 1, "Failure", "Scan spool first"); - } - } - // Brand Filament not registered to Spoolman - else if ((!doc["sm_id"].is() || (doc["sm_id"].is() && (doc["sm_id"] == "0" || doc["sm_id"] == ""))) - && doc["b"].is() && doc["an"].is()) - { - doc["sm_id"] = "0"; // Ensure sm_id is set to 0 - // If no sm_id is present but the brand is Brand Filament then - // create a new spool, maybe brand too, in Spoolman - Serial.println("New Brand Filament Tag found!"); - createBrandFilament(doc, uidString); + int locId = doc["location_id"].as(); + int sId = lastSpoolId.toInt(); + sendLocation(sId, "", locId, ""); } else { - Serial.println("Keine SPOOL-ID gefunden."); + Serial.println("Unbekannter Tag-Inhalt."); activeSpoolId = ""; - oledShowProgressBar(1, 1, "Failure", "Unkown tag"); + oledShowProgressBar(1, 1, "Failure", "Unknown tag"); } - }else{ - oledShowProgressBar(octoEnabled?5:4, octoEnabled?5:4, "Failure!", "Spoolman unavailable"); + } else { + oledShowProgressBar(4, 4, "Failure!", "API offline"); } } @@ -1498,7 +1476,7 @@ bool quickSpoolIdCheck(String uidString) { Serial.println("⚠ FAST-PATH: Could not read complete JSON, web interface may show limited data"); } - oledShowProgressBar(2, octoEnabled?5:4, "Known Spool", "Quick mode"); + oledShowProgressBar(2, 4, "Known Spool", "Quick mode"); Serial.println("✓ FAST-PATH SUCCESS: Known spool processed quickly"); return true; } else { @@ -1553,7 +1531,7 @@ bool quickSpoolIdCheck(String uidString) { Serial.println("⚠ FAST-PATH: Could not read complete JSON, web interface may show limited data"); } - oledShowProgressBar(2, octoEnabled?5:4, "Known Spool", "Quick mode"); + oledShowProgressBar(2, 4, "Known Spool", "Quick mode"); Serial.println("✓ FAST-PATH SUCCESS: Known spool processed quickly"); return true; } else { @@ -1777,7 +1755,6 @@ void writeJsonToTag(void *parameter) { // Only reset the write protection flag - reading task was never suspended nfcWriteInProgress = false; // Re-enable high-level tag operations - pauseBambuMqttTask = false; free(params->payload); delete params; @@ -1911,9 +1888,10 @@ void scanRfidTask(void * parameter) { foundNfcTag(nullptr, success); - // Reset activeSpoolId immediately when no tag is detected to prevent stale autoSet + // Reset activeSpoolId and activeTagUuid immediately when no tag is detected if (!success) { activeSpoolId = ""; + activeTagUuid = ""; } // As long as there is still a tag on the reader, do not try to read it again @@ -1927,7 +1905,7 @@ void scanRfidTask(void * parameter) { nfcReaderState = NFC_READING; - oledShowProgressBar(0, octoEnabled?5:4, "Reading", "Detecting tag"); + oledShowProgressBar(0, 4, "Reading", "Detecting tag"); // Reduced stabilization time for better responsiveness Serial.println("Tag detected, minimal stabilization..."); @@ -1945,6 +1923,7 @@ void scanRfidTask(void * parameter) { if (uidLength == 7) { + activeTagUuid = uidString; // Try fast-path detection first for known spools if (quickSpoolIdCheck(uidString)) { Serial.println("✓ FAST-PATH: Tag processed quickly, skipping full read"); @@ -2077,6 +2056,7 @@ void scanRfidTask(void * parameter) { void startNfc() { oledShowProgressBar(5, 7, DISPLAY_BOOT_TEXT, "NFC init"); nfc.begin(); // Beginne Kommunikation mit RFID Leser + delay(1000); unsigned long versiondata = nfc.getFirmwareVersion(); // Lese Versionsnummer der Firmware aus if (! versiondata) { // Wenn keine Antwort kommt diff --git a/src/nfc.h b/src/nfc.h index 6cdf8ce..f496a51 100644 --- a/src/nfc.h +++ b/src/nfc.h @@ -22,6 +22,7 @@ bool readCompleteJsonForFastPath(); // Read complete JSON data for fast-path web extern TaskHandle_t RfidReaderTask; extern String nfcJsonData; extern String activeSpoolId; +extern String activeTagUuid; extern String lastSpoolId; extern volatile nfcReaderStateType nfcReaderState; extern volatile bool nfcWriteInProgress; diff --git a/src/ota.cpp b/src/ota.cpp index a98b949..630974e 100644 --- a/src/ota.cpp +++ b/src/ota.cpp @@ -2,7 +2,6 @@ #include #include #include "scale.h" -#include "bambu.h" #include "nfc.h" @@ -48,49 +47,11 @@ bool isVersionLessThan(const String& version1, const String& version2) { } void backupJsonConfigs() { - // Bambu Credentials backup - if (LittleFS.exists("/bambu_credentials.json")) { - File file = LittleFS.open("/bambu_credentials.json", "r"); - if (file) { - bambuCredentialsBackup = file.readString(); - file.close(); - Serial.println("Bambu credentials backed up"); - } - } - - // Spoolman URL backup - if (LittleFS.exists("/spoolman_url.json")) { - File file = LittleFS.open("/spoolman_url.json", "r"); - if (file) { - spoolmanUrlBackup = file.readString(); - file.close(); - Serial.println("Spoolman URL backed up"); - } - } + // No more JSON configs to backup, using NVS } void restoreJsonConfigs() { - // Restore Bambu credentials - if (bambuCredentialsBackup.length() > 0) { - File file = LittleFS.open("/bambu_credentials.json", "w"); - if (file) { - file.print(bambuCredentialsBackup); - file.close(); - Serial.println("Bambu credentials restored"); - } - bambuCredentialsBackup = ""; // Clear backup - } - - // Restore Spoolman URL - if (spoolmanUrlBackup.length() > 0) { - File file = LittleFS.open("/spoolman_url.json", "w"); - if (file) { - file.print(spoolmanUrlBackup); - file.close(); - Serial.println("Spoolman URL restored"); - } - spoolmanUrlBackup = ""; // Clear backup - } + // No more JSON configs to restore, using NVS } void espRestart() { @@ -157,12 +118,6 @@ void handleUpdate(AsyncWebServer &server) { size_t index, uint8_t *data, size_t len, bool final) { // Disable all Tasks - if (BambuMqttTask != NULL) - { - Serial.println("Delete BambuMqttTask"); - vTaskDelete(BambuMqttTask); - BambuMqttTask = NULL; - } if (ScaleTask) { Serial.println("Delete ScaleTask"); vTaskDelete(ScaleTask); diff --git a/src/scale.cpp b/src/scale.cpp index 699df9d..e47d8e1 100644 --- a/src/scale.cpp +++ b/src/scale.cpp @@ -288,7 +288,6 @@ uint8_t calibrate_scale() { if (RfidReaderTask != NULL) vTaskSuspend(RfidReaderTask); if (ScaleTask != NULL) vTaskSuspend(ScaleTask); - pauseBambuMqttTask = true; pauseMainTask = 1; if (scale.wait_ready_timeout(1000)) @@ -395,7 +394,6 @@ uint8_t calibrate_scale() { if (RfidReaderTask != NULL) vTaskResume(RfidReaderTask); if (ScaleTask != NULL) vTaskResume(ScaleTask); - pauseBambuMqttTask = false; pauseMainTask = 0; scaleCalibrationActive = false; diff --git a/src/website.cpp b/src/website.cpp index 4daf7c8..7504c80 100644 --- a/src/website.cpp +++ b/src/website.cpp @@ -3,7 +3,6 @@ #include "api.h" #include #include -#include "bambu.h" #include "nfc.h" #include "scale.h" #include "esp_task_wdt.h" @@ -13,9 +12,8 @@ #include "config.h" #include "debug.h" - #ifndef VERSION - #define VERSION "1.1.0" + #define VERSION "1.2.0" #endif // Cache-Control Header definieren @@ -32,8 +30,6 @@ void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventTyp HEAP_DEBUG_MESSAGE("onWsEvent begin"); if (type == WS_EVT_CONNECT) { Serial.println("Neuer Client verbunden!"); - // Sende die AMS-Daten an den neuen Client - if (!bambuDisabled) sendAmsData(client); sendNfcData(); foundNfcTag(client, 0); sendWriteResult(client, 3); @@ -50,8 +46,6 @@ void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventTyp } else if (type == WS_EVT_DATA) { JsonDocument doc; DeserializationError error = deserializeJson(doc, (char*)data, len); - //String message = String((char*)data); - //deserializeJson(doc, message); if (error) { Serial.println("JSON deserialization failed: " + String(error.c_str())); @@ -63,17 +57,15 @@ void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventTyp ws.text(client->id(), "{" "\"type\":\"heartbeat\"," "\"freeHeap\":" + String(ESP.getFreeHeap()/1024) + "," - "\"bambu_connected\":" + String(bambu_connected) + "," - "\"spoolman_connected\":" + String(spoolmanConnected) + "" + "\"filaman_connected\":" + String(filamanConnected) + "," + "\"registered\":" + String(filamanRegistered) + "" "}"); } else if (doc["type"] == "writeNfcTag") { if (doc["payload"].is()) { - // Versuche NFC-Daten zu schreiben String payloadString; serializeJson(doc["payload"], payloadString); - startWriteJsonToTag((doc["tagType"] == "spool") ? true : false, payloadString.c_str()); } } @@ -83,7 +75,6 @@ void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventTyp if (doc["payload"] == "tare") { scaleTareRequest = true; success = 1; - //success = tareScale(); } if (doc["payload"] == "calibrate") { @@ -102,26 +93,8 @@ void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventTyp } else if (doc["type"] == "reconnect") { - if (doc["payload"] == "bambu") { - bambu_restart(); - } - - if (doc["payload"] == "spoolman") { - initSpoolman(); - } - } - - else if (doc["type"] == "setBambuSpool") { - Serial.println(doc["payload"].as()); - setBambuSpool(doc["payload"]); - } - - else if (doc["type"] == "setSpoolmanSettings") { - Serial.println(doc["payload"].as()); - if (updateSpoolBambuData(doc["payload"].as())) { - ws.textAll("{\"type\":\"setSpoolmanSettings\",\"payload\":\"success\"}"); - } else { - ws.textAll("{\"type\":\"setSpoolmanSettings\",\"payload\":\"error\"}"); + if (doc["payload"] == "filaman") { + sendHeartbeat(); } } @@ -133,7 +106,6 @@ void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventTyp HEAP_DEBUG_MESSAGE("onWsEvent end"); } -// Funktion zum Laden und Ersetzen des Headers in einer HTML-Datei String loadHtmlWithHeader(const char* filename) { Serial.println("Lade HTML-Datei: " + String(filename)); if (!LittleFS.exists(filename)) { @@ -149,7 +121,6 @@ String loadHtmlWithHeader(const char* filename) { } void sendWriteResult(AsyncWebSocketClient *client, uint8_t success) { - // Sende Erfolg/Misserfolg an alle Clients String response = "{\"type\":\"writeNfcTag\",\"success\":" + String(success ? "1" : "0") + "}"; ws.textAll(response); } @@ -163,7 +134,6 @@ void foundNfcTag(AsyncWebSocketClient *client, uint8_t success) { void sendNfcData() { if (lastnfcReaderState == nfcReaderState) return; - // TBD: Why is there no status for reading the tag? switch(nfcReaderState){ case NFC_IDLE: ws.textAll("{\"type\":\"nfcData\", \"payload\":{}}"); @@ -189,36 +159,20 @@ void sendNfcData() { lastnfcReaderState = nfcReaderState; } -void sendAmsData(AsyncWebSocketClient *client) { - if (ams_count > 0) { - ws.textAll("{\"type\":\"amsData\",\"payload\":" + amsJsonData + "}"); - } -} - void setupWebserver(AsyncWebServer &server) { oledShowProgressBar(2, 7, DISPLAY_BOOT_TEXT, "Webserver init"); - // Deaktiviere alle Debug-Ausgaben Serial.setDebugOutput(false); - // WebSocket-Optimierungen ws.onEvent(onWsEvent); ws.enable(true); - // Konfiguriere Server für große Uploads server.onRequestBody([](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total){}); server.onFileUpload([](AsyncWebServerRequest *request, const String& filename, size_t index, uint8_t *data, size_t len, bool final){}); - // Lade die Spoolman-URL beim Booten - spoolmanUrl = loadSpoolmanUrl(); - Serial.print("Geladene Spoolman-URL: "); - Serial.println(spoolmanUrl); - - // Load Bamb credentials: - loadBambuCredentials(); + loadFilamanConfig(); // Route für about server.on("/about", HTTP_GET, [](AsyncWebServerRequest *request){ - Serial.println("Anfrage für /about erhalten"); AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/index.html.gz", "text/html"); response->addHeader("Content-Encoding", "gzip"); response->addHeader("Cache-Control", CACHE_CONTROL); @@ -227,208 +181,97 @@ void setupWebserver(AsyncWebServer &server) { // Route für Waage server.on("/waage", HTTP_GET, [](AsyncWebServerRequest *request){ - Serial.println("Anfrage für /waage erhalten"); - //AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/waage.html.gz", "text/html"); - //response->addHeader("Content-Encoding", "gzip"); - //response->addHeader("Cache-Control", CACHE_CONTROL); - String html = loadHtmlWithHeader("/waage.html"); html.replace("{{autoTare}}", (autoTare) ? "checked" : ""); - request->send(200, "text/html", html); }); // Route für RFID server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ - Serial.println("Anfrage für /rfid erhalten"); - - String page = (bambuDisabled) ? "/rfid.html.gz" : "/rfid_bambu.html.gz"; - AsyncWebServerResponse *response = request->beginResponse(LittleFS, page, "text/html"); - + AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/rfid.html.gz", "text/html"); response->addHeader("Content-Encoding", "gzip"); response->addHeader("Cache-Control", CACHE_CONTROL); request->send(response); - Serial.println("RFID-Seite gesendet"); }); - server.on("/api/url", HTTP_GET, [](AsyncWebServerRequest *request){ - Serial.println("API-Aufruf: /api/url"); - String jsonResponse = "{\"spoolman_url\": \"" + String(spoolmanUrl) + "\"}"; - request->send(200, "application/json", jsonResponse); + // Route für Config & Registration + server.on("/config", HTTP_GET, [](AsyncWebServerRequest *request){ + String html = loadHtmlWithHeader("/config.html"); + html.replace("{{filamanUrl}}", filamanUrl); + html.replace("{{registered}}", filamanRegistered ? "Yes" : "No"); + request->send(200, "text/html", html); + }); + + server.on("/api/register", HTTP_POST, [](AsyncWebServerRequest *request){}, NULL, [](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total){ + JsonDocument doc; + deserializeJson(doc, (const char*)data); + + if (doc["url"].is()) filamanUrl = doc["url"].as(); + String code = doc["code"].as(); + + saveFilamanConfig(); + + if (registerDevice(code)) { + request->send(200, "application/json", "{\"success\": true}"); + } else { + request->send(400, "application/json", "{\"success\": false}"); + } + }); + + // API for Backend to trigger Tag write + server.on("/api/v1/rfid/write", HTTP_POST, [](AsyncWebServerRequest *request){}, NULL, [](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total){ + // Check Authorization? (TBD) + JsonDocument doc; + deserializeJson(doc, (const char*)data); + + String payloadString; + serializeJson(doc, payloadString); + + bool isSpool = doc.containsKey("spool_id"); + startWriteJsonToTag(isSpool, payloadString.c_str()); + + request->send(200, "application/json", "{\"status\": \"writing\"}"); }); // Route für WiFi server.on("/wifi", HTTP_GET, [](AsyncWebServerRequest *request){ - Serial.println("Anfrage für /wifi erhalten"); AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/wifi.html.gz", "text/html"); response->addHeader("Content-Encoding", "gzip"); response->addHeader("Cache-Control", CACHE_CONTROL); request->send(response); }); - // Route für Spoolman Setting - server.on("/spoolman", HTTP_GET, [](AsyncWebServerRequest *request){ - Serial.println("Anfrage für /spoolman erhalten"); - String html = loadHtmlWithHeader("/spoolman.html"); - html.replace("{{spoolmanUrl}}", (spoolmanUrl != "") ? spoolmanUrl : ""); - html.replace("{{spoolmanOctoEnabled}}", octoEnabled ? "checked" : ""); - html.replace("{{spoolmanOctoUrl}}", (octoUrl != "") ? octoUrl : ""); - html.replace("{{spoolmanOctoToken}}", (octoToken != "") ? octoToken : ""); - - html.replace("{{bambuIp}}", bambuCredentials.ip); - html.replace("{{bambuSerial}}", bambuCredentials.serial); - html.replace("{{bambuCode}}", bambuCredentials.accesscode ? bambuCredentials.accesscode : ""); - html.replace("{{autoSendToBambu}}", bambuCredentials.autosend_enable ? "checked" : ""); - html.replace("{{autoSendTime}}", (bambuCredentials.autosend_time != 0) ? String(bambuCredentials.autosend_time) : String(BAMBU_DEFAULT_AUTOSEND_TIME)); - html.replace("{{printerModel}}", String(printerModelToString(bambuCredentials.printer_model))); - - request->send(200, "text/html", html); - }); - - // Route für das Überprüfen der Spoolman-Instanz - server.on("/api/checkSpoolman", HTTP_GET, [](AsyncWebServerRequest *request){ - if (!request->hasParam("url")) { - request->send(400, "application/json", "{\"success\": false, \"error\": \"Missing URL parameter\"}"); - return; - } - - if (request->getParam("octoEnabled")->value() == "true" && (!request->hasParam("octoUrl") || !request->hasParam("octoToken"))) { - request->send(400, "application/json", "{\"success\": false, \"error\": \"Missing OctoPrint URL or Token parameter\"}"); - return; - } - - String url = request->getParam("url")->value(); - if (url.indexOf("http://") == -1 && url.indexOf("https://") == -1) { - url = "http://" + url; - } - // Remove trailing slash if exists - if (url.length() > 0 && url.charAt(url.length()-1) == '/') { - url = url.substring(0, url.length()-1); - } - - bool octoEnabled = (request->getParam("octoEnabled")->value() == "true") ? true : false; - String octoUrl = request->getParam("octoUrl")->value(); - String octoToken = (request->getParam("octoToken")->value() != "") ? request->getParam("octoToken")->value() : ""; - - url.trim(); - octoUrl.trim(); - octoToken.trim(); - - bool healthy = saveSpoolmanUrl(url, octoEnabled, octoUrl, octoToken); - String jsonResponse = "{\"healthy\": " + String(healthy ? "true" : "false") + "}"; - - request->send(200, "application/json", jsonResponse); - }); - - // Route für das Überprüfen der Bambu-Instanz - server.on("/api/bambu", HTTP_GET, [](AsyncWebServerRequest *request){ - if (request->hasParam("remove")) { - if (removeBambuCredentials()) { - request->send(200, "application/json", "{\"success\": true}"); - } else { - request->send(500, "application/json", "{\"success\": false, \"error\": \"Fehler beim Löschen der Bambu-Credentials\"}"); - } - return; - } - - if (!request->hasParam("bambu_ip") || !request->hasParam("bambu_serialnr") || !request->hasParam("bambu_accesscode") || !request->hasParam("printerModel")) { - request->send(400, "application/json", "{\"success\": false, \"error\": \"Missing parameter\"}"); - return; - } - - String bambu_ip = request->getParam("bambu_ip")->value(); - String bambu_serialnr = request->getParam("bambu_serialnr")->value(); - String bambu_accesscode = request->getParam("bambu_accesscode")->value(); - bool autoSend = (request->getParam("autoSend")->value() == "true") ? true : false; - String autoSendTime = request->getParam("autoSendTime")->value(); - String printerModel = request->getParam("printerModel")->value(); - - bambu_ip.trim(); - bambu_serialnr.trim(); - bambu_accesscode.trim(); - autoSendTime.trim(); - printerModel.trim(); - - if (bambu_ip.length() == 0 || bambu_serialnr.length() == 0 || bambu_accesscode.length() == 0) { - request->send(400, "application/json", "{\"success\": false, \"error\": \"Empty parameter\"}"); - return; - } - - bool success = saveBambuCredentials(bambu_ip, bambu_serialnr, bambu_accesscode, autoSend, autoSendTime, printerModel); - - request->send(200, "application/json", "{\"healthy\": " + String(success ? "true" : "false") + "}"); - }); - - // Route für das Überprüfen der Spoolman-Instanz server.on("/reboot", HTTP_GET, [](AsyncWebServerRequest *request){ ESP.restart(); }); - // Route für das Laden der CSS-Datei server.on("/style.css", HTTP_GET, [](AsyncWebServerRequest *request){ - Serial.println("Lade style.css"); AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/style.css.gz", "text/css"); response->addHeader("Content-Encoding", "gzip"); response->addHeader("Cache-Control", CACHE_CONTROL); request->send(response); - Serial.println("style.css gesendet"); }); - // Route für das Logo server.on("/logo.png", HTTP_GET, [](AsyncWebServerRequest *request){ AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/logo.png.gz", "image/png"); response->addHeader("Content-Encoding", "gzip"); response->addHeader("Cache-Control", CACHE_CONTROL); request->send(response); - Serial.println("logo.png gesendet"); }); - // Route für Favicon server.on("/favicon.ico", HTTP_GET, [](AsyncWebServerRequest *request){ AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/favicon.ico", "image/x-icon"); response->addHeader("Cache-Control", CACHE_CONTROL); request->send(response); - Serial.println("favicon.ico gesendet"); - }); - - // Route für spool_in.png - server.on("/spool_in.png", HTTP_GET, [](AsyncWebServerRequest *request){ - AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/spool_in.png.gz", "image/png"); - response->addHeader("Content-Encoding", "gzip"); - response->addHeader("Cache-Control", CACHE_CONTROL); - request->send(response); - Serial.println("spool_in.png gesendet"); - }); - - // Route für set_spoolman.png - server.on("/set_spoolman.png", HTTP_GET, [](AsyncWebServerRequest *request){ - AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/set_spoolman.png.gz", "image/png"); - response->addHeader("Content-Encoding", "gzip"); - response->addHeader("Cache-Control", CACHE_CONTROL); - request->send(response); - Serial.println("set_spoolman.png gesendet"); - }); - - // Route für JavaScript Dateien - server.on("/spoolman.js", HTTP_GET, [](AsyncWebServerRequest *request){ - Serial.println("Anfrage für /spoolman.js erhalten"); - AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/spoolman.js.gz", "text/javascript"); - response->addHeader("Content-Encoding", "gzip"); - response->addHeader("Cache-Control", CACHE_CONTROL); - request->send(response); - Serial.println("Spoolman.js gesendet"); }); server.on("/rfid.js", HTTP_GET, [](AsyncWebServerRequest *request){ - Serial.println("Anfrage für /rfid.js erhalten"); AsyncWebServerResponse *response = request->beginResponse(LittleFS,"/rfid.js.gz", "text/javascript"); response->addHeader("Content-Encoding", "gzip"); response->addHeader("Cache-Control", CACHE_CONTROL); request->send(response); - Serial.println("RFID.js gesendet"); }); - // Vereinfachter Update-Handler server.on("/upgrade", HTTP_GET, [](AsyncWebServerRequest *request) { AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/upgrade.html.gz", "text/html"); response->addHeader("Content-Encoding", "gzip"); @@ -436,7 +279,6 @@ void setupWebserver(AsyncWebServer &server) { request->send(response); }); - // Update-Handler registrieren handleUpdate(server); server.on("/api/version", HTTP_GET, [](AsyncWebServerRequest *request){ @@ -445,19 +287,14 @@ void setupWebserver(AsyncWebServer &server) { request->send(200, "application/json", jsonResponse); }); - // Fehlerbehandlung für nicht gefundene Seiten server.onNotFound([](AsyncWebServerRequest *request){ - Serial.print("404 - Nicht gefunden: "); - Serial.println(request->url()); request->send(404, "text/plain", "Seite nicht gefunden"); }); - // WebSocket-Route ws.onEvent(onWsEvent); server.addHandler(&ws); ws.enable(true); - // Starte den Webserver server.begin(); Serial.println("Webserver gestartet"); }