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 2ec6c22..0000000 Binary files a/html/set_spoolman.png and /dev/null differ diff --git a/html/spool_in.png b/html/spool_in.png deleted file mode 100644 index 77821a8..0000000 Binary files a/html/spool_in.png and /dev/null differ diff --git a/html/spoolman.html b/html/spoolman.html deleted file mode 100644 index 096885d..0000000 --- a/html/spoolman.html +++ /dev/null @@ -1,234 +0,0 @@ - - - - - - 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"); }