Compare commits

..

No commits in common. "main" and "v1.3.98" have entirely different histories.

52 changed files with 280 additions and 49429 deletions

View File

@ -41,16 +41,16 @@ jobs:
run: |
VERSION=$(grep '^version = ' platformio.ini | cut -d'"' -f2)
# Build firmware and LittleFS
echo "Building firmware and LittleFS..."
# Build firmware and SPIFFS
echo "Building firmware and SPIFFS..."
pio run -e esp32dev
pio run -t buildfs
# Copy firmware binary
cp .pio/build/esp32dev/firmware.bin .pio/build/esp32dev/upgrade_filaman_firmware_v${VERSION}.bin
# Create LittleFS binary - direct copy without header
cp .pio/build/esp32dev/littlefs.bin .pio/build/esp32dev/upgrade_filaman_website_v${VERSION}.bin
# Create SPIFFS binary - direct copy without header
cp .pio/build/esp32dev/spiffs.bin .pio/build/esp32dev/upgrade_filaman_website_v${VERSION}.bin
# Create full binary
(cd .pio/build/esp32dev &&
@ -63,7 +63,7 @@ jobs:
0x1000 bootloader.bin \
0x8000 partitions.bin \
0x10000 firmware.bin \
0x3D0000 littlefs.bin)
0x3D0000 spiffs.bin)
# Verify file sizes
echo "File sizes:"

View File

@ -39,16 +39,16 @@ jobs:
run: |
VERSION=$(grep '^version = ' platformio.ini | cut -d'"' -f2)
# Always build firmware and LittleFS
echo "Building firmware and LittleFS..."
# Always build firmware and SPIFFS
echo "Building firmware and SPIFFS..."
pio run -e esp32dev
pio run -t buildfs
# Copy firmware binary
cp .pio/build/esp32dev/firmware.bin .pio/build/esp32dev/upgrade_filaman_firmware_v${VERSION}.bin
# Create LittleFS binary - direct copy without header
cp .pio/build/esp32dev/littlefs.bin .pio/build/esp32dev/upgrade_filaman_website_v${VERSION}.bin
# Create SPIFFS binary - direct copy without header
cp .pio/build/esp32dev/spiffs.bin .pio/build/esp32dev/upgrade_filaman_website_v${VERSION}.bin
# Create full binary (always)
(cd .pio/build/esp32dev &&
@ -61,7 +61,7 @@ jobs:
0x1000 bootloader.bin \
0x8000 partitions.bin \
0x10000 firmware.bin \
0x3D0000 littlefs.bin)
0x3D0000 spiffs.bin)
# Verify file sizes
echo "File sizes:"
@ -131,7 +131,7 @@ jobs:
FILES_TO_UPLOAD="$FILES_TO_UPLOAD upgrade_filaman_firmware_v${VERSION}.bin"
fi
# Add LittleFS and full binary only if they exist
# Add SPIFFS and full binary only if they exist
if [ -f "upgrade_filaman_website_v${VERSION}.bin" ]; then
FILES_TO_UPLOAD="$FILES_TO_UPLOAD upgrade_filaman_website_v${VERSION}.bin"
fi

View File

@ -1,223 +1,5 @@
# Changelog
## [1.5.1] - 2025-03-30
### Changed
- update version to 1.5.1 and improve OTA update handling with task management
## [1.4.14] - 2025-03-30
### Added
- add auto-tare functionality and update scale handling based on touch sensor connection
### Changed
- update platformio.ini for version v1.4.14
## [1.4.13] - 2025-03-30
### Changed
- update platformio.ini for version v1.4.13
### Fixed
- update touch sensor connection logic to correctly identify connection status
## [1.4.12] - 2025-03-30
### Added
- add touch sensor connection check and update logic
### Changed
- update platformio.ini for version v1.4.12
- update README files to clarify PN532 DIP switch settings
## [1.4.11] - 2025-03-30
### Added
- Renamed states of NFC state machine and introduced new state machine for spoolman API
### Changed
- update platformio.ini for version v1.4.11
- Merge branch 'main' of github.com:ManuelW77/Filaman
- Merge pull request #31 from janecker/nfc_rework
- Introducing enum for handling the NFC state to improve code readability
## [1.4.10] - 2025-03-30
### Added
- add manual tare functionality for scale
- add debounce handling for TTP223 touch sensor
- add TTP223 touch sensor support and wiring configuration
### Changed
- update platformio.ini for version v1.4.10
### Fixed
- update TTP223 pin configuration and adjust touch sensor logic
## [1.4.9] - 2025-03-29
### Changed
- update platformio.ini for version v1.4.9
### Fixed
- enhance HTTP method handling in sendToApi function
## [1.4.8] - 2025-03-29
### Changed
- update platformio.ini for version v1.4.8
- Merge pull request #30 from janecker/main
- Merge branch 'testing' into main
### Fixed
- improve HTTP client configuration and clear update documents after API calls
- Fixes memory leak in HTTPClient by disabling connection reuse
- update reload logic after removing and saving Bambu credentials for better cache handling
## [1.4.7] - 2025-03-27
### Added
- add forced cache refresh after removing and saving Bambu credentials
- add functionality to remove Bambu credentials and update API handling
- add rfid_bambu.html and update bambu connection handling
### Changed
- update platformio.ini for version v1.4.7
- Merge branch 'testing'
- update remove button for Bambu credentials with red background
- Merge pull request #28 from tugsi/main
### Fixed
- handle Bambu connection state by introducing bambuDisabled flag
- Fix rfid.js-Failure with X1-Series, if you wanna send a Spool to AMS: - Uncaught TypeError: Cannot read properties of undefined (reading 'replace') at handleSpoolIn (rfid.js:493:67) at HTMLButtonElement.onclick ((Index):1:1) handleSpoolIn @ rfid.js:493 onclick @ (Index):1
## [1.4.6] - 2025-03-26
### Changed
- update platformio.ini for version v1.4.6
### Fixed
- handle potential undefined value for tray_info_idx in handleSpoolIn function, by @tugsi
## [1.4.5] - 2025-03-25
### Changed
- update platformio.ini for version v1.4.5
- Merge branch 'testing'
- remove unused request_topic subscription and reduce MQTT task stack size
- Merge pull request #26 from tugsi/main
- rename report_topic to topic and update MQTT subscription logic, switched publish topic to request
### Fixed
- increase MQTT buffer size and adjust task stack size
- Fix BufferSize for larger JSONs from X-Series
## [1.4.4] - 2025-03-23
### Added
- add error handling for missing vendor IDs in filament data
### Changed
- update platformio.ini for version v1.4.4
### Fixed
- adjust weight threshold for tare check to allow negative values
## [1.4.3] - 2025-03-23
### Changed
- update platformio.ini for version v1.4.3
## [1.4.2] - 2025-03-23
### Added
- add WiFi connection check and restart Bambu if not connected
### Changed
- update platformio.ini for version v1.4.2
- increase stack size for BambuMqtt task
- update Discord Link
- update Discord Link
- remove commented-out subscription topic in MQTT setup
### Fixed
- use unique client ID for MQTT connection to avoid conflicts
- reload page after firmware update completion
- increase WiFi connection timeout from 5 to 10 seconds
- ensure valid URL format and remove trailing slash in setupWebserver
## [1.4.1] - 2025-03-10
### Added
- added new .step, now with correct individual parts
- added changelog
- Add files via upload
- added .stp files of modifications
- added merged picture
- added pictures of components bought from AliE
- Add files via upload
- added pictures for heat insert location
- added pictures showing heat insert location
- remove unnecessary delay in MQTT setup and add delay before restart
- add new 3D print file for Filaman scale
- added Discord Server
### Changed
- update platformio.ini for version v1.4.1
- refactor length calculation to convert total length to meters before formatting
- Merge pull request #16 from spitzbirne32/main
- improved housing to show display better
- removed CAD, as they were all duplicates
- typo in AliE link
- Delete usermod/spitzbirne32/STL/README.md
- Update README.md
- moved pictures of parts into dedicated folders
- Update README.md
- Update README.md
- Update README.md
- Delete usermod/spitzbirne32/STL/ScaleTop_Heatinsert_Location_usermod_spitzbirne32_.png
- Delete usermod/spitzbirne32/STL/Housing_Heatinsert_Location_usermod_spitzbirne32_.png
- created folders
- Update README.md
- Update README.md
- Create README.md
- Update README.md
- Update README.md
- Create README.md
- Merge pull request #15 from ManuelW77/main
- Merge pull request #14 from janecker/scale-calibration-rework
- Reworks the scale calibration handling
- remove redundant scale calibration checks and enhance task management
- enhance AMS data handling and streamline spool auto-setting logic
- adjust stack size and improve scale calibration logic
- update labels and input types for better clarity and functionality
- update documentation for clarity and accuracy
### Fixed
- correct typo in console log for total length
## [1.4.0] - 2025-03-01
### Added
- add support for Spoolman Octoprint Plugin in README files
- add OctoPrint integration with configurable fields and update functionality
- add version comparison function and check for outdated versions before updates
- remove unused version and protocol fields from JSON output; add error message for insufficient memory
### Changed
- update NFC tag references to include NTAG213 and clarify storage capacity
- bump version to 1.4.0
- remove unused version and protocol fields from NFC data packet
- sort vendors alphabetically in the dropdown list
- Merge pull request #10 from janecker/nfc-improvements
- Improves NFC Tag handling
## [1.3.99] - 2025-02-28
### Changed
- update platformio.ini for version v1.3.99
- update workflows to build firmware with LittleFS instead of SPIFFS
## [1.3.98] - 2025-02-28
### Changed
- update platformio.ini for version v1.3.98

View File

@ -8,8 +8,7 @@ Das System integriert sich nahtlos mit der [Spoolman](https://github.com/Donkie/
Weitere Bilder finden Sie im [img Ordner](/img/)
oder auf meiner Website: [FilaMan Website](https://www.filaman.app)
Deutsches Erklärvideo: [Youtube](https://youtu.be/uNDe2wh9SS8?si=b-jYx4I1w62zaOHU)
Discord Server: [https://discord.gg/my7Gvaxj2v](https://discord.gg/my7Gvaxj2v)
Deutsches Erklärvideo: [Youtube](https://youtu.be/uNDe2wh9SS8?si=b-jYx4I1w62zaOHU)
### Es gibt jetzt auch ein Wiki, dort sind nochmal alle Funktionen beschrieben: [Wiki](https://github.com/ManuelW77/Filaman/wiki)
@ -19,7 +18,7 @@ Discord Server: [https://discord.gg/my7Gvaxj2v](https://discord.gg/my7Gvaxj2v)
- **OLED-Display:** Zeigt aktuelles Gewicht, Verbindungsstatus (WiFi, Bambu Lab, Spoolman).
- **WLAN-Konnektivität:** WiFiManager für einfache Netzwerkkonfiguration.
- **MQTT-Integration:** Verbindet sich mit Bambu Lab Drucker für AMS-Steuerung.
- **NFC-Tag NTAG213 NTAG215:** Verwendung von NTAG213, besser NTAG215 wegen ausreichendem Speicherplatz auf dem Tag
- **NFC-Tag NTAG215:** Verwendung von NTAG215 wegen ausreichendem Speicherplatz auf dem Tag
### Weboberflächen-Funktionen
- **Echtzeit-Updates:** WebSocket-Verbindung für Live-Daten-Updates.
@ -36,7 +35,6 @@ Discord Server: [https://discord.gg/my7Gvaxj2v](https://discord.gg/my7Gvaxj2v)
- Filtern und Auswählen von Filamenten.
- Automatische Aktualisierung der Spulengewichte.
- Verfolgung von NFC-Tag-Zuweisungen.
- Unterstützt das Spoolman Octoprint Plugin
### Wenn Sie meine Arbeit unterstützen möchten, freue ich mich über einen Kaffee
<a href="https://www.buymeacoffee.com/manuelw" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 30px !important;width: 108px !important;" ></a>
@ -55,22 +53,19 @@ Discord Server: [https://discord.gg/my7Gvaxj2v](https://discord.gg/my7Gvaxj2v)
## Hardware-Anforderungen
### Komponenten
- **ESP32 Development Board:** Any ESP32 variant.
[Amazon Link](https://amzn.to/3FHea6D)
- **HX711 5kg Load Cell Amplifier:** For weight measurement.
[Amazon Link](https://amzn.to/4ja1KTe)
- **OLED 0.96 Zoll I2C white/yellow Display:** 128x64 SSD1306.
[Amazon Link](https://amzn.to/445aaa9)
- **PN532 NFC NXP RFID-Modul V3:** For NFC tag operations.
[Amazon Link](https://amzn.to/4iO6CO4)
- **NFC Tags NTAG213 NTAG215:** RFID Tag
[Amazon Link](https://amzn.to/3E071xO)
- **TTP223 Touch Sensor (optional):** For reTARE per Button/Touch
[Amazon Link](https://amzn.to/4hTChMK)
- **ESP32 Entwicklungsboard:** Jede ESP32-Variante.
[Amazon Link](https://amzn.eu/d/aXThslf)
- **HX711 5kg Wägezellen-Verstärker:** Für Gewichtsmessung.
[Amazon Link](https://amzn.eu/d/06A0DLb)
- **OLED 0.96 Zoll I2C weiß/gelb Display:** 128x64 SSD1306.
[Amazon Link](https://amzn.eu/d/0AuBp2c)
- **PN532 NFC NXP RFID-Modul V3:** Für NFC-Tag-Operationen.
[Amazon Link](https://amzn.eu/d/jfIuQXb)
- **NFC Tags Ntag215:** RFID Tag
[Amazon Link](https://amzn.eu/d/9Z6mXc1)
### Pin Konfiguration
| Component | ESP32 Pin |
### Pin-Konfiguration
| Komponente | ESP32 Pin |
|-------------------|-----------|
| HX711 DOUT | 16 |
| HX711 SCK | 17 |
@ -80,10 +75,8 @@ Discord Server: [https://discord.gg/my7Gvaxj2v](https://discord.gg/my7Gvaxj2v)
| PN532 RESET | 33 |
| PN532 SDA | 21 |
| PN532 SCL | 22 |
| TTP223 I/O | 25 |
**!! Achte darauf, dass am PN532 die DIP-Schalter auf I2C gestellt sind**
**Nutze den 3V Pin vom ESP für den Touch Sensor**
**Achte darauf, dass am PN532 die DIP-Schalter auf I2C gestellt sind**
![Wiring](./img/Schaltplan.png)

View File

@ -6,14 +6,12 @@ FilaMan is a filament management system for 3D printing. It uses ESP32 hardware
Users can manage filament spools, monitor the status of the Automatic Material System (AMS) and make settings via a web interface.
The system integrates seamlessly with [Bambulab](https://bambulab.com/en-us) 3D printers and [Spoolman](https://github.com/Donkie/Spoolman) filament management as well as the [Openspool](https://github.com/spuder/OpenSpool) NFC-TAG format.
![Scale](./img/scale_trans.png)
More Images can be found in the [img Folder](/img/)
or my website: [FilaMan Website](https://www.filaman.app)
german explanatory video: [Youtube](https://youtu.be/uNDe2wh9SS8?si=b-jYx4I1w62zaOHU)
Discord Server: [https://discord.gg/my7Gvaxj2v](https://discord.gg/my7Gvaxj2v)
or my website:[FilaMan Website](https://www.filaman.app)
german explanatory video: [Youtube](https://youtu.be/uNDe2wh9SS8?si=b-jYx4I1w62zaOHU)
### Now more detailed informations about the usage: [Wiki](https://github.com/ManuelW77/Filaman/wiki)
@ -23,7 +21,7 @@ Discord Server: [https://discord.gg/my7Gvaxj2v](https://discord.gg/my7Gvaxj2v)
- **OLED Display:** Shows current weight, connection status (WiFi, Bambu Lab, Spoolman).
- **WiFi Connectivity:** WiFiManager for easy network configuration.
- **MQTT Integration:** Connects to Bambu Lab printer for AMS control.
- **NFC-Tag NTAG213 NTAG215:** Use NTAG213, better NTAG215 because of enaught space on the Tag
- **NFC-Tag NTAG215:** Use NTAG215 because of enaught space on the Tag
### Web Interface Features
- **Real-time Updates:** WebSocket connection for live data updates.
@ -40,7 +38,6 @@ Discord Server: [https://discord.gg/my7Gvaxj2v](https://discord.gg/my7Gvaxj2v)
- Filter and select filaments.
- Update spool weights automatically.
- Track NFC tag assignments.
- Supports Spoolman Octoprint Plugin
### If you want to support my work, i would be happy to get a coffe
<a href="https://www.buymeacoffee.com/manuelw" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 30px !important;width: 108px !important;" ></a>
@ -60,17 +57,15 @@ Discord Server: [https://discord.gg/my7Gvaxj2v](https://discord.gg/my7Gvaxj2v)
### Components
- **ESP32 Development Board:** Any ESP32 variant.
[Amazon Link](https://amzn.to/3FHea6D)
[Amazon Link](https://amzn.eu/d/aXThslf)
- **HX711 5kg Load Cell Amplifier:** For weight measurement.
[Amazon Link](https://amzn.to/4ja1KTe)
[Amazon Link](https://amzn.eu/d/06A0DLb)
- **OLED 0.96 Zoll I2C white/yellow Display:** 128x64 SSD1306.
[Amazon Link](https://amzn.to/445aaa9)
[Amazon Link](https://amzn.eu/d/0AuBp2c)
- **PN532 NFC NXP RFID-Modul V3:** For NFC tag operations.
[Amazon Link](https://amzn.to/4iO6CO4)
- **NFC Tags NTAG213 NTAG215:** RFID Tag
[Amazon Link](https://amzn.to/3E071xO)
- **TTP223 Touch Sensor (optional):** For reTARE per Button/Touch
[Amazon Link](https://amzn.to/4hTChMK)
[Amazon Link](https://amzn.eu/d/jfIuQXb)
- **NFC Tags Ntag215:** RFID Tag
[Amazon Link](https://amzn.eu/d/9Z6mXc1)
### Pin Configuration
@ -84,10 +79,8 @@ Discord Server: [https://discord.gg/my7Gvaxj2v](https://discord.gg/my7Gvaxj2v)
| PN532 RESET | 33 |
| PN532 SDA | 21 |
| PN532 SCL | 22 |
| TTP223 I/O | 25 |
**!! Make sure that the DIP switches on the PN532 are set to I2C**
**Use the 3V pin from the ESP for the touch sensor**
**Make sure that the DIP switches on the PN532 are set to I2C**
![Wiring](./img/Schaltplan.png)

File diff suppressed because it is too large Load Diff

Binary file not shown.

View File

@ -141,6 +141,15 @@
</div>
</div>
<!-- Rechte Spalte -->
<div class="column">
<div class="feature-box">
<h2>Bambu AMS</h2>
<div id="amsDataContainer">
<div class="amsData" id="amsData">Wait for AMS-Data...</div>
</div>
</div>
</div>
</div>
</div>

View File

@ -11,7 +11,7 @@ let reconnectTimer = null;
// WebSocket Funktionen
function startHeartbeat() {
if (heartbeatTimer) clearInterval(heartbeatTimer);
heartbeatTimer = setInterval(() => {
// Prüfe ob zu lange keine Antwort kam
if (Date.now() - lastHeartbeatResponse > HEARTBEAT_TIMEOUT) {
@ -29,7 +29,7 @@ function startHeartbeat() {
updateConnectionStatus();
return;
}
try {
// Sende Heartbeat
socket.send(JSON.stringify({ type: 'heartbeat' }));
@ -83,7 +83,7 @@ function initWebSocket() {
isConnected = false;
updateConnectionStatus();
if (heartbeatTimer) clearInterval(heartbeatTimer);
// Bei Fehler Verbindung schließen und neu aufbauen
if (socket) {
socket.close();
@ -109,7 +109,7 @@ function initWebSocket() {
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
@ -208,7 +208,7 @@ document.addEventListener('spoolmanError', function(event) {
showNotification(`Spoolman Error: ${event.detail.message}`, false);
});
document.addEventListener('filamentSelected', function (event) {
document.addEventListener('filamentSelected', function(event) {
updateNfcInfo();
// Zeige Spool-Buttons wenn ein Filament ausgewählt wurde
const selectedText = document.getElementById("selected-filament").textContent;
@ -490,7 +490,7 @@ function handleSpoolIn(amsId, trayId) {
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() || '',
tray_info_idx: selectedSpool.filament.extra.bambu_idx.replace(/['"]+/g, '').trim(),
cali_idx: "-1" // Default-Wert setzen
}
};
@ -640,6 +640,8 @@ function writeNfcTag() {
// Erstelle das NFC-Datenpaket mit korrekten Datentypen
const nfcData = {
version: "2.0",
protocol: "openspool",
color_hex: selectedSpool.filament.color_hex || "FFFFFF",
type: selectedSpool.filament.material,
min_temp: minTemp,
@ -686,4 +688,4 @@ function showNotification(message, isSuccess) {
notification.remove();
}, 300);
}, 3000);
}
}

View File

@ -1,160 +0,0 @@
<!-- head --><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FilaMan - Filament Management Tool</title>
<link rel="icon" type="image/png" href="/favicon.ico">
<link rel="stylesheet" href="style.css">
<script>
fetch('/api/version')
.then(response => response.json())
.then(data => {
const versionSpan = document.querySelector('.version');
if (versionSpan) {
versionSpan.textContent = 'v' + data.version;
}
})
.catch(error => console.error('Error fetching version:', error));
</script>
</head>
<body>
<div class="navbar">
<div style="display: flex; align-items: center; gap: 2rem;">
<img src="/logo.png" alt="FilaMan Logo" class="logo">
<div class="logo-text">
<h1>FilaMan<span class="version"></span></h1>
<h4>Filament Management Tool</h4>
</div>
</div>
<nav style="display: flex; gap: 1rem;">
<a href="/">Start</a>
<a href="/waage">Scale</a>
<a href="/spoolman">Spoolman/Bambu</a>
<a href="/about">About</a>
<a href="/upgrade">Upgrade</a>
</nav>
<div class="status-container">
<div class="status-item">
<span class="status-dot" id="bambuDot"></span>B
</div>
<div class="status-item">
<span class="status-dot" id="spoolmanDot"></span>S
</div>
<div class="ram-status" id="ramStatus"></div>
</div>
</div>
<!-- head -->
<div class="connection-status hidden">
<div class="spinner"></div>
<span>Connection lost. Trying to reconnect...</span>
</div>
<div class="content">
<div class="three-column-layout">
<!-- Linke Spalte -->
<div class="column">
<div class="feature-box">
<div class="statistics-header">
<h2>Statistics</h2>
<button id="refreshSpoolman" class="refresh-button">
<span>Refresh Spoolman</span>
</button>
</div>
<div class="statistics-column">
<h3>Spools</h3>
<div class="spool-stat" style="display: flex; justify-content: center; align-items: center;">
<span class="stat-label">total:</span>
<span class="stat-value" id="totalSpools"></span>
<div style="width: auto;"></div>
<span class="stat-label">without Tag:</span>
<span class="stat-value" id="spoolsWithoutTag"></span>
</div>
</div>
<div class="statistics-grid">
<div class="statistics-column">
<h3>Overview</h3>
<ul class="statistics-list">
<li>
<span class="stat-label">Manufacturer:</span>
<span class="stat-value" id="totalVendors"></span>
</li>
<li>
<span class="stat-label">Weight:</span>
<span class="stat-value"><span id="totalWeight"></span></span>
</li>
<li>
<span class="stat-label">Length:</span>
<span class="stat-value"><span id="totalLength"></span></span>
</li>
</ul>
</div>
<div class="statistics-column">
<h3>Materials</h3>
<ul class="statistics-list" id="materialsList">
<!-- Wird dynamisch befüllt -->
</ul>
</div>
</div>
</div>
<div class="feature-box">
<div class="nfc-header">
<h2>NFC-Tag</h2>
<span id="nfcStatusIndicator" class="status-circle"></span>
</div>
<div class="nfc-status-display"></div>
</div>
</div>
<!-- Mittlere Spalte -->
<div class="column">
<div class="feature-box">
<h2>Spoolman Spools</h2>
<label for="vendorSelect">Manufacturer:</label>
<div style="display: flex; justify-content: space-between; align-items: center;">
<select id="vendorSelect" class="styled-select">
<option value="">Please choose...</option>
</select>
<label style="margin-left: 10px;">
<input type="checkbox" id="onlyWithoutSmId" checked onchange="updateFilamentDropdown()">
Only Spools without SM ID
</label>
</div>
</div>
<div id="filamentSection" class="feature-box hidden">
<label>Spool / Filament:</label>
<div class="custom-dropdown">
<div class="dropdown-button" onclick="toggleFilamentDropdown()">
<div class="selected-color" id="selected-color"></div>
<span id="selected-filament">Please choose...</span>
<span class="dropdown-arrow"></span>
</div>
<div class="dropdown-content" id="filament-dropdown-content">
<!-- Optionen werden dynamisch hinzugefügt -->
</div>
</div>
<p id="nfcInfo" class="nfc-status"></p>
<button id="writeNfcButton" class="btn btn-primary hidden" onclick="writeNfcTag()">Write Tag</button>
</div>
</div>
<!-- Rechte Spalte -->
<div class="column">
<div class="feature-box">
<h2>Bambu AMS</h2>
<div id="amsDataContainer">
<div class="amsData" id="amsData">Wait for AMS-Data...</div>
</div>
</div>
</div>
</div>
</div>
<script src="spoolman.js"></script>
<script src="rfid.js"></script>
</body>
</html>

View File

@ -52,43 +52,11 @@
if (spoolmanUrl && spoolmanUrl.trim() !== "") {
document.getElementById('spoolmanUrl').value = spoolmanUrl;
}
// Initialize OctoPrint fields visibility
toggleOctoFields();
};
function removeBambuCredentials() {
fetch('/api/bambu?remove=true')
.then(response => response.json())
.then(data => {
if (data.success) {
document.getElementById('bambuIp').value = '';
document.getElementById('bambuSerial').value = '';
document.getElementById('bambuCode').value = '';
document.getElementById('autoSend').checked = false;
document.getElementById('autoSendTime').value = '';
document.getElementById('bambuStatusMessage').innerText = 'Bambu Credentials removed!';
// Reload with forced cache refresh after short delay
setTimeout(() => {
window.location.reload(true);
window.location.href = '/';
}, 1500);
} else {
document.getElementById('bambuStatusMessage').innerText = 'Error while removing Bambu Credentials.';
}
})
.catch(error => {
document.getElementById('bambuStatusMessage').innerText = 'Error while removing: ' + error.message;
});
}
function checkSpoolmanInstance() {
const url = document.getElementById('spoolmanUrl').value;
const spoolmanOctoEnabled = document.getElementById('spoolmanOctoEnabled').checked;
const spoolmanOctoUrl = document.getElementById('spoolmanOctoUrl').value;
const spoolmanOctoToken = document.getElementById('spoolmanOctoToken').value;
fetch(`/api/checkSpoolman?url=${encodeURIComponent(url)}&octoEnabled=${spoolmanOctoEnabled}&octoUrl=${spoolmanOctoUrl}&octoToken=${spoolmanOctoToken}`)
fetch(`/api/checkSpoolman?url=${encodeURIComponent(url)}`)
.then(response => response.json())
.then(data => {
if (data.healthy) {
@ -114,11 +82,6 @@
.then(data => {
if (data.healthy) {
document.getElementById('bambuStatusMessage').innerText = 'Bambu Credentials saved!';
// Reload with forced cache refresh after short delay
setTimeout(() => {
window.location.reload(true);
window.location.href = '/';
}, 1500);
} else {
document.getElementById('bambuStatusMessage').innerText = 'Error while saving Bambu Credentials.';
}
@ -127,15 +90,6 @@
document.getElementById('bambuStatusMessage').innerText = 'Error while saving: ' + error.message;
});
}
/**
* Controls visibility of OctoPrint configuration fields based on checkbox state
* Called on page load and when checkbox changes
*/
function toggleOctoFields() {
const octoEnabled = document.getElementById('spoolmanOctoEnabled').checked;
document.getElementById('octoFields').style.display = octoEnabled ? 'block' : 'none';
}
</script>
<script>
var spoolmanUrl = "{{spoolmanUrl}}";
@ -148,17 +102,6 @@
<div class="card-body">
<h5 class="card-title">Set URL/IP to your Spoolman-Instanz</h5>
<input type="text" id="spoolmanUrl" placeholder="http://ip-or-url-of-your-spoolman-instanz:port">
<h5 class="card-title">If you want to enable sending Spool to Spoolman Octoprint Plugin:</h5>
<p>
<input type="checkbox" id="spoolmanOctoEnabled" {{spoolmanOctoEnabled}} onchange="toggleOctoFields()"> Send to Octo-Plugin
</p>
<div id="octoFields" style="display: none;">
<p>
<input type="text" id="spoolmanOctoUrl" placeholder="http://ip-or-url-of-your-octoprint-instanz:port" value="{{spoolmanOctoUrl}}">
<input type="text" id="spoolmanOctoToken" placeholder="Your Octoprint Token" value="{{spoolmanOctoToken}}">
</p>
</div>
<button onclick="checkSpoolmanInstance()">Save Spoolman URL</button>
<p id="statusMessage"></p>
</div>
@ -184,15 +127,14 @@
<p>If activated, FilaMan will automatically update the next filled tray with the last scanned and weighed spool.</p>
<div class="input-group" style="display: flex; margin-bottom: 0;">
<label for="autoSend" style="width: 250px; margin-right: 5px;">Auto Send to Bambu:</label>
<label for="autoSendTime" style="width: 250px; margin-right: 5px;">Wait for Spool in Sec:</label>
<label for="autoSendTime" style="width: 250px; margin-right: 5px;">Wait time in Seconds:</label>
</div>
<div class="input-group" style="display: flex;">
<input type="checkbox" id="autoSend" {{autoSendToBambu}} style="width: 190px; margin-right: 10px;">
<input type="number" min="60" id="autoSendTime" placeholder="Time to wait" value="{{autoSendTime}}" style="width: 100px;">
<input type="text" id="autoSendTime" placeholder="Time to wait for new Spool" value="{{autoSendTime}}" style="width: 100px;">
</div>
<button style="margin: 0;" onclick="saveBambuCredentials()">Save Bambu Credentials</button>
<button style="margin: 0; background-color: red;" onclick="removeBambuCredentials()">Remove Credentials</button>
<p id="bambuStatusMessage"></p>
</div>
</div>

View File

@ -86,10 +86,10 @@ function populateVendorDropdown(data, selectedSmId = null) {
});
// 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";
console.log("Total Lenght: ", totalLength);
const formattedLength = totalLength > 1000
? (totalLength / 1000).toFixed(2) + " km"
: totalLength.toFixed(2) + " m";
// Formatierung des Gesamtgewichts (von g zu kg zu t)
const weightInKg = totalWeight / 1000; // erst in kg umrechnen
@ -97,15 +97,13 @@ function populateVendorDropdown(data, selectedSmId = null) {
? (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);
});
// Dropdown mit gefilterten Herstellern befüllen
Object.entries(filteredVendors).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;
@ -147,13 +145,6 @@ function updateFilamentDropdown(selectedSmId = null) {
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 !== '""' &&
@ -247,6 +238,18 @@ async function fetchSpoolData() {
}
}
/*
// Exportiere Funktionen
window.getSpoolData = () => spoolsData;
window.reloadSpoolData = initSpoolman;
window.populateVendorDropdown = populateVendorDropdown;
window.updateFilamentDropdown = updateFilamentDropdown;
window.toggleFilamentDropdown = () => {
const content = document.getElementById("filament-dropdown-content");
content.classList.toggle("show");
};
*/
// Event Listener
document.addEventListener('DOMContentLoaded', () => {
initSpoolman();

View File

@ -188,18 +188,14 @@ label {
font-weight: bold;
}
input[type="text"], input[type="submit"], input[type="number"] {
input[type="text"], input[type="submit"] {
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 16px;
}
input[type="number"] {
width: 108px !important;
}
input[type="text"]:focus, input[type="number"]:focus {
input[type="text"]:focus {
border-color: #007bff;
outline: none;
}

View File

@ -129,7 +129,6 @@
if (data.status === 'success' || lastReceivedProgress >= 98) {
clearTimeout(wsReconnectTimer);
setTimeout(() => {
window.location.reload(true);
window.location.href = '/';
}, 30000);
}
@ -149,7 +148,6 @@
status.style.display = 'block';
clearTimeout(wsReconnectTimer);
setTimeout(() => {
window.location.reload(true);
window.location.href = '/';
}, 30000);
} else {

View File

@ -55,7 +55,6 @@
<h5 class="card-title">Sacle Calibration</h5>
<button id="calibrateBtn" class="btn btn-primary">Calibrate Scale</button>
<button id="tareBtn" class="btn btn-secondary">Tare Scale</button>
&nbsp;&nbsp;&nbsp;Enable Auto-TARE <input type="checkbox" id="autoTareCheckbox" onchange="setAutoTare(this.checked);" {{autoTare}}>
<div id="statusMessage" class="mt-3"></div>
</div>
</div>
@ -141,15 +140,6 @@
}));
});
// Add auto-tare function
function setAutoTare(enabled) {
ws.send(JSON.stringify({
type: 'scale',
payload: 'setAutoTare',
enabled: enabled
}));
}
// WebSocket-Verbindung beim Laden der Seite initiieren
connectWebSocket();
</script>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

View File

@ -9,9 +9,7 @@
; https://docs.platformio.org/page/projectconf.html
[common]
version = "1.5.1"
to_old_version = "1.5.0"
version = "1.3.98"
##
[env:esp32dev]
platform = espressif32
@ -50,7 +48,6 @@ build_flags =
#-DNDEBUG
-mtext-section-literals
-DVERSION=\"${common.version}\"
-DTOOLDVERSION=\"${common.to_old_version}\"
-DASYNCWEBSERVER_REGEX
#-DCORE_DEBUG_LEVEL=3
-DCONFIG_ARDUHAL_LOG_COLORS=1

View File

@ -14,7 +14,7 @@ def copy_file(input_file, output_file):
def should_compress(file):
# Skip compression for spoolman.html
if file == 'spoolman.html' or file == 'waage.html':
if file == 'spoolman.html':
return False
# Komprimiere nur bestimmte Dateitypen
return file.endswith(('.js', '.png', '.css', '.html'))

View File

@ -3,18 +3,13 @@
#include <ArduinoJson.h>
#include "commonFS.h"
volatile spoolmanApiStateType spoolmanApiState = API_INIT;
//bool spoolman_connected = false;
bool spoolman_connected = false;
String spoolmanUrl = "";
bool octoEnabled = false;
String octoUrl = "";
String octoToken = "";
struct SendToApiParams {
String httpType;
String spoolsUrl;
String updatePayload;
String octoToken;
};
JsonDocument fetchSingleSpoolInfo(int spoolId) {
@ -86,26 +81,20 @@ JsonDocument fetchSingleSpoolInfo(int spoolId) {
}
void sendToApi(void *parameter) {
spoolmanApiState = API_TRANSMITTING;
SendToApiParams* params = (SendToApiParams*)parameter;
// Extrahiere die Werte
String httpType = params->httpType;
String spoolsUrl = params->spoolsUrl;
String updatePayload = params->updatePayload;
String octoToken = params->octoToken;
HTTPClient http;
http.setReuse(false);
http.begin(spoolsUrl);
http.addHeader("Content-Type", "application/json");
if (octoEnabled && octoToken != "") http.addHeader("X-Api-Key", octoToken);
int httpCode;
int httpCode = http.PUT(updatePayload);
if (httpType == "PATCH") httpCode = http.PATCH(updatePayload);
else if (httpType == "POST") httpCode = http.POST(updatePayload);
else httpCode = http.PUT(updatePayload);
if (httpCode == HTTP_CODE_OK) {
Serial.println("Spoolman erfolgreich aktualisiert");
@ -116,12 +105,10 @@ void sendToApi(void *parameter) {
}
http.end();
vTaskDelay(50 / portTICK_PERIOD_MS);
// Speicher freigeben
delete params;
vTaskDelete(NULL);
spoolmanApiState = API_IDLE;
}
bool updateSpoolTagId(String uidString, const char* payload) {
@ -166,14 +153,12 @@ bool updateSpoolTagId(String uidString, const char* payload) {
BaseType_t result = xTaskCreate(
sendToApi, // Task-Funktion
"SendToApiTask", // Task-Name
6144, // Stackgröße in Bytes
4096, // Stackgröße in Bytes
(void*)params, // Parameter
0, // Priorität
NULL // Task-Handle (nicht benötigt)
);
updateDoc.clear();
return true;
}
@ -204,56 +189,15 @@ uint8_t updateSpoolWeight(String spoolId, uint16_t weight) {
BaseType_t result = xTaskCreate(
sendToApi, // Task-Funktion
"SendToApiTask", // Task-Name
6144, // Stackgröße in Bytes
4096, // Stackgröße in Bytes
(void*)params, // Parameter
0, // Priorität
NULL // Task-Handle (nicht benötigt)
);
updateDoc.clear();
return 1;
}
bool updateSpoolOcto(int spoolId) {
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->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
NULL // Task-Handle (nicht benötigt)
);
updateDoc.clear();
return true;
}
bool updateSpoolBambuData(String payload) {
JsonDocument doc;
DeserializationError error = deserializeJson(doc, payload);
@ -291,7 +235,7 @@ bool updateSpoolBambuData(String payload) {
BaseType_t result = xTaskCreate(
sendToApi, // Task-Funktion
"SendToApiTask", // Task-Name
6144, // Stackgröße in Bytes
4096, // Stackgröße in Bytes
(void*)params, // Parameter
0, // Priorität
NULL // Task-Handle (nicht benötigt)
@ -482,8 +426,7 @@ bool checkSpoolmanInstance(const String& url) {
return false;
}
spoolmanApiState = API_IDLE;
oledShowTopRow();
spoolman_connected = true;
return strcmp(status, "healthy") == 0;
}
}
@ -492,24 +435,17 @@ bool checkSpoolmanInstance(const String& url) {
return false;
}
bool saveSpoolmanUrl(const String& url, bool octoOn, const String& octoWh, const String& octoTk) {
bool saveSpoolmanUrl(const String& url) {
if (!checkSpoolmanInstance(url)) return false;
JsonDocument doc;
doc["url"] = url;
doc["octoEnabled"] = octoOn;
doc["octoUrl"] = octoWh;
doc["octoToken"] = octoTk;
Serial.print("Speichere Spoolman Data in Datei: ");
Serial.println(doc.as<String>());
Serial.print("Speichere URL in Datei: ");
Serial.println(url);
if (!saveJsonValue("/spoolman_url.json", doc)) {
Serial.println("Fehler beim Speichern der Spoolman-URL.");
return false;
}
spoolmanUrl = url;
octoEnabled = octoOn;
octoUrl = octoWh;
octoToken = octoTk;
return true;
}
@ -517,13 +453,6 @@ bool saveSpoolmanUrl(const String& url, bool octoOn, const String& octoWh, const
String loadSpoolmanUrl() {
JsonDocument doc;
if (loadJsonValue("/spoolman_url.json", doc) && doc["url"].is<String>()) {
octoEnabled = (doc["octoEnabled"].is<bool>()) ? doc["octoEnabled"].as<bool>() : false;
if (octoEnabled && doc["octoToken"].is<String>() && doc["octoUrl"].is<String>())
{
octoUrl = doc["octoUrl"].as<String>();
octoToken = doc["octoToken"].as<String>();
}
return doc["url"].as<String>();
}
Serial.println("Keine gültige Spoolman-URL gefunden.");

View File

@ -6,21 +6,12 @@
#include "website.h"
#include "display.h"
#include <ArduinoJson.h>
typedef enum {
API_INIT,
API_IDLE,
API_TRANSMITTING
} spoolmanApiStateType;
extern volatile spoolmanApiStateType spoolmanApiState;
extern bool spoolman_connected;
extern String spoolmanUrl;
extern bool octoEnabled;
extern String octoUrl;
extern String octoToken;
bool checkSpoolmanInstance(const String& url);
bool saveSpoolmanUrl(const String& url, bool octoOn, const String& octoWh, const String& octoTk);
bool saveSpoolmanUrl(const String& url);
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
@ -28,6 +19,5 @@ bool updateSpoolTagId(String uidString, const char* payload); // Neue Funktion z
uint8_t updateSpoolWeight(String spoolId, uint16_t weight); // Neue Funktion zum Aktualisieren des Gewichts
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
#endif

View File

@ -17,7 +17,7 @@ PubSubClient client(sslClient);
TaskHandle_t BambuMqttTask;
String topic = "";
String report_topic = "";
//String request_topic = "";
const char* bambu_username = "bblp";
const char* bambu_ip = nullptr;
@ -27,7 +27,6 @@ const char* bambu_serialnr = nullptr;
String g_bambu_ip = "";
String g_bambu_accesscode = "";
String g_bambu_serialnr = "";
bool bambuDisabled = false;
bool bambu_connected = false;
bool autoSendToBambu = false;
@ -38,32 +37,6 @@ int ams_count = 0;
String amsJsonData; // Speichert das fertige JSON für WebSocket-Clients
AMSData ams_data[MAX_AMS]; // Definition des Arrays;
bool removeBambuCredentials() {
if (BambuMqttTask) {
vTaskDelete(BambuMqttTask);
}
if (!removeJsonValue("/bambu_credentials.json")) {
Serial.println("Fehler beim Löschen der Bambu-Credentials.");
return false;
}
// Löschen der globalen Variablen
g_bambu_ip = "";
g_bambu_accesscode = "";
g_bambu_serialnr = "";
bambu_ip = nullptr;
bambu_accesscode = nullptr;
bambu_serialnr = nullptr;
autoSendToBambu = false;
autoSetToBambuSpoolId = 0;
ams_count = 0;
amsJsonData = "";
bambuDisabled = true;
return true;
}
bool saveBambuCredentials(const String& ip, const String& serialnr, const String& accesscode, bool autoSend, const String& autoSendTime) {
if (BambuMqttTask) {
vTaskDelete(BambuMqttTask);
@ -118,7 +91,7 @@ bool loadBambuCredentials() {
bambu_accesscode = g_bambu_accesscode.c_str();
bambu_serialnr = g_bambu_serialnr.c_str();
topic = "device/" + String(bambu_serialnr);
report_topic = "device/" + String(bambu_serialnr) + "/report";
//request_topic = "device/" + String(bambu_serialnr) + "/request";
return true;
}
@ -226,7 +199,7 @@ FilamentResult findFilamentIdx(String brand, String type) {
bool sendMqttMessage(const String& payload) {
Serial.println("Sending MQTT message");
Serial.println(payload);
if (client.publish((String(topic) + "/request").c_str(), payload.c_str()))
if (client.publish(report_topic.c_str(), payload.c_str()))
{
return true;
}
@ -368,7 +341,7 @@ void updateAmsWsData(JsonDocument& doc, JsonArray& amsArray, int& ams_count, Jso
ams_data[i].trays[j].tray_color = trayObj["tray_color"].as<String>();
ams_data[i].trays[j].nozzle_temp_min = trayObj["nozzle_temp_min"].as<int>();
ams_data[i].trays[j].nozzle_temp_max = trayObj["nozzle_temp_max"].as<int>();
if (trayObj["tray_type"].as<String>() == "") ams_data[i].trays[j].setting_id = "";
//ams_data[i].trays[j].setting_id = trayObj["setting_id"].as<String>();
ams_data[i].trays[j].cali_idx = trayObj["cali_idx"].as<String>();
}
}
@ -452,8 +425,16 @@ void mqtt_callback(char* topic, byte* payload, unsigned int length) {
return;
}
// Wenn bambu auto set spool aktiv und eine spule erkannt und mqtt meldung das neue spule im ams
if (autoSendToBambu && autoSetToBambuSpoolId > 0 &&
doc["print"]["command"].as<String>() == "push_status" && doc["print"]["ams"]["tray_pre"].as<uint8_t>()
&& !doc["print"]["ams"]["ams"].as<JsonArray>())
{
autoSetSpool(autoSetToBambuSpoolId, doc["print"]["ams"]["tray_pre"].as<uint8_t>());
}
// Prüfen, ob "print->upgrade_state" und "print.ams.ams" existieren
if (doc["print"]["upgrade_state"].is<JsonObject>() || (doc["print"]["command"].is<String>() && doc["print"]["command"] == "push_status"))
if (doc["print"]["upgrade_state"].is<JsonObject>())
{
// Prüfen ob AMS-Daten vorhanden sind
if (!doc["print"]["ams"].is<JsonObject>() || !doc["print"]["ams"]["ams"].is<JsonArray>())
@ -462,7 +443,7 @@ void mqtt_callback(char* topic, byte* payload, unsigned int length) {
}
JsonArray amsArray = doc["print"]["ams"]["ams"].as<JsonArray>();
// Prüfe ob sich die AMS-Daten geändert haben
bool hasChanges = false;
@ -498,12 +479,6 @@ void mqtt_callback(char* topic, byte* payload, unsigned int length) {
(trayObj["setting_id"].as<String>() != "" && trayObj["setting_id"].as<String>() != ams_data[storedIndex].trays[j].setting_id) ||
trayObj["cali_idx"].as<String>() != ams_data[storedIndex].trays[j].cali_idx) {
hasChanges = true;
if (autoSendToBambu && autoSetToBambuSpoolId > 0 && hasChanges)
{
autoSetSpool(autoSetToBambuSpoolId, ams_data[storedIndex].trays[j].id);
}
break;
}
}
@ -522,11 +497,6 @@ void mqtt_callback(char* topic, byte* payload, unsigned int length) {
(vtTray["setting_id"].as<String>() != "" && vtTray["setting_id"].as<String>() != ams_data[i].trays[0].setting_id) ||
(vtTray["tray_type"].as<String>() != "" && vtTray["cali_idx"].as<String>() != ams_data[i].trays[0].cali_idx)) {
hasChanges = true;
if (autoSendToBambu && autoSetToBambuSpoolId > 0 && hasChanges)
{
autoSetSpool(autoSetToBambuSpoolId, 254);
}
}
break;
}
@ -580,11 +550,10 @@ void reconnect() {
oledShowTopRow();
// Attempt to connect
String clientId = String(bambu_serialnr) + "_" + String(random(0, 100));
if (client.connect(clientId.c_str(), bambu_username, bambu_accesscode)) {
if (client.connect(bambu_serialnr, bambu_username, bambu_accesscode)) {
Serial.println("MQTT re/connected");
client.subscribe((String(topic) + "/report").c_str());
client.subscribe(report_topic.c_str());
bambu_connected = true;
oledShowTopRow();
} else {
@ -631,27 +600,30 @@ void mqtt_loop(void * parameter) {
bool setupMqtt() {
// Wenn Bambu Daten vorhanden
bool success = loadBambuCredentials();
vTaskDelay(100 / portTICK_PERIOD_MS);
if (!success) {
bambuDisabled = true;
Serial.println("Failed to load Bambu credentials");
oledShowMessage("Bambu Credentials Missing");
vTaskDelay(2000 / portTICK_PERIOD_MS);
return false;
}
if (success && bambu_ip != "" && bambu_accesscode != "" && bambu_serialnr != "")
{
bambuDisabled = false;
sslClient.setCACert(root_ca);
sslClient.setInsecure();
client.setServer(bambu_ip, 8883);
// Verbinden mit dem MQTT-Server
bool connected = true;
String clientId = String(bambu_serialnr) + "_" + String(random(0, 100));
if (client.connect(clientId.c_str(), bambu_username, bambu_accesscode))
if (client.connect(bambu_serialnr, bambu_username, bambu_accesscode))
{
client.setCallback(mqtt_callback);
client.setBufferSize(15488);
client.subscribe((String(topic) + "/report").c_str());
client.setBufferSize(5120);
// Optional: Topic abonnieren
client.subscribe(report_topic.c_str());
//client.subscribe(request_topic.c_str());
Serial.println("MQTT-Client initialisiert");
oledShowMessage("Bambu Connected");
@ -680,7 +652,10 @@ bool setupMqtt() {
}
else
{
bambuDisabled = true;
Serial.println("Fehler: Keine MQTT-Daten vorhanden");
oledShowMessage("Bambu Credentials Missing");
oledShowTopRow();
vTaskDelay(2000 / portTICK_PERIOD_MS);
return false;
}
return true;
@ -689,7 +664,6 @@ bool setupMqtt() {
void bambu_restart() {
if (BambuMqttTask) {
vTaskDelete(BambuMqttTask);
delay(10);
}
setupMqtt();
}

View File

@ -30,9 +30,7 @@ extern int ams_count;
extern AMSData ams_data[MAX_AMS];
extern bool autoSendToBambu;
extern int autoSetToBambuSpoolId;
extern bool bambuDisabled;
bool removeBambuCredentials();
bool loadBambuCredentials();
bool saveBambuCredentials(const String& bambu_ip, const String& bambu_serialnr, const String& bambu_accesscode, const bool autoSend, const String& autoSendTime);
bool setupMqtt();

View File

@ -1,20 +1,6 @@
#include "commonFS.h"
#include <LittleFS.h>
bool removeJsonValue(const char* filename) {
File file = LittleFS.open(filename, "r");
if (!file) {
return true;
}
file.close();
if (!LittleFS.remove(filename)) {
Serial.print("Fehler beim Löschen der Datei: ");
Serial.println(filename);
return false;
}
return true;
}
bool saveJsonValue(const char* filename, const JsonDocument& doc) {
File file = LittleFS.open(filename, "w");
if (!file) {

View File

@ -5,7 +5,6 @@
#include <ArduinoJson.h>
#include <LittleFS.h>
bool removeJsonValue(const char* filename);
bool saveJsonValue(const char* filename, const JsonDocument& doc);
bool loadJsonValue(const char* filename, JsonDocument& doc);
void initializeFileSystem();

View File

@ -19,12 +19,6 @@ const uint16_t SCALE_LEVEL_WEIGHT = 500;
uint16_t defaultScaleCalibrationValue = 430;
// ***** HX711
// ***** TTP223 (Touch Sensor)
// TTP223 circuit wiring
const uint8_t TTP223_PIN = 25;
// ***** TTP223
// ***** Display
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
// On an ESP32: 21(SDA), 22(SCL)

View File

@ -11,8 +11,6 @@ extern const uint8_t LOADCELL_SCK_PIN;
extern const uint8_t calVal_eepromAdress;
extern const uint16_t SCALE_LEVEL_WEIGHT;
extern const uint8_t TTP223_PIN;
extern const int8_t OLED_RESET;
extern const uint8_t SCREEN_ADDRESS;
extern const uint8_t SCREEN_WIDTH;

View File

@ -177,7 +177,7 @@ void oledShowTopRow() {
display.drawBitmap(50, 0, bitmap_off , 16, 16, WHITE);
}
if (spoolmanApiState != API_INIT) {
if (spoolman_connected == 1) {
display.drawBitmap(80, 0, bitmap_spoolman_on , 16, 16, WHITE);
} else {
display.drawBitmap(80, 0, bitmap_off , 16, 16, WHITE);

View File

@ -13,10 +13,6 @@
#include "esp_task_wdt.h"
#include "commonFS.h"
bool mainTaskWasPaused = 0;
uint8_t scaleTareCounter = 0;
bool touchSensorConnected = false;
// ##### SETUP #####
void setup() {
Serial.begin(115200);
@ -40,6 +36,7 @@ void setup() {
setupWebserver(server);
// Spoolman API
// api.cpp
initSpoolman();
// Bambu MQTT
@ -48,23 +45,32 @@ void setup() {
// NFC Reader
startNfc();
// Touch Sensor
pinMode(TTP223_PIN, INPUT_PULLUP);
if (digitalRead(TTP223_PIN) == LOW)
{
Serial.println("Touch Sensor is connected");
touchSensorConnected = true;
uint8_t scaleCalibrated = start_scale();
if (scaleCalibrated == 3) {
oledShowMessage("Scale not calibrated!");
for (uint16_t i = 0; i < 50000; i++) {
yield();
vTaskDelay(pdMS_TO_TICKS(1));
esp_task_wdt_reset();
}
} else if (scaleCalibrated == 0) {
oledShowMessage("HX711 not found");
for (uint16_t i = 0; i < 50000; i++) {
yield();
vTaskDelay(pdMS_TO_TICKS(1));
esp_task_wdt_reset();
}
}
// Scale
start_scale(touchSensorConnected);
// WDT initialisieren mit 10 Sekunden Timeout
bool panic = true; // Wenn true, löst ein WDT-Timeout einen System-Panik aus
esp_task_wdt_init(10, panic);
esp_task_wdt_init(10, panic);
// Aktuellen Task (loopTask) zum Watchdog hinzufügen
esp_task_wdt_add(NULL);
// Optional: Andere Tasks zum Watchdog hinzufügen, falls nötig
// esp_task_wdt_add(task_handle);
}
@ -93,42 +99,23 @@ uint8_t autoAmsCounter = 0;
uint8_t weightSend = 0;
int16_t lastWeight = 0;
// WIFI check variables
unsigned long lastWifiCheckTime = 0;
const unsigned long wifiCheckInterval = 60000; // Überprüfe alle 60 Sekunden (60000 ms)
// Button debounce variables
unsigned long lastButtonPress = 0;
const unsigned long debounceDelay = 500; // 500 ms debounce delay
// ##### PROGRAM START #####
void loop() {
unsigned long currentMillis = millis();
// Überprüfe den Status des Touch Sensors
if (touchSensorConnected && digitalRead(TTP223_PIN) == HIGH && currentMillis - lastButtonPress > debounceDelay)
{
lastButtonPress = currentMillis;
scaleTareRequest = true;
}
// Überprüfe regelmäßig die WLAN-Verbindung
if (intervalElapsed(currentMillis, lastWifiCheckTime, wifiCheckInterval))
{
if (intervalElapsed(currentMillis, lastWifiCheckTime, wifiCheckInterval)) {
checkWiFiConnection();
}
// Wenn Bambu auto set Spool aktiv
if (autoSendToBambu && autoSetToBambuSpoolId > 0)
{
if (!bambuDisabled && !bambu_connected)
{
bambu_restart();
}
if (autoSendToBambu && autoSetToBambuSpoolId > 0) {
if (intervalElapsed(currentMillis, lastAutoSetBambuAmsTime, autoSetBambuAmsInterval))
{
if (nfcReaderState == NFC_IDLE)
if (hasReadRfidTag == 0)
{
lastAutoSetBambuAmsTime = currentMillis;
oledShowMessage("Auto Set " + String(autoSetBambuAmsCounter - autoAmsCounter) + "s");
@ -160,28 +147,19 @@ void loop() {
}
// Ausgabe der Waage auf Display
if(pauseMainTask == 0)
if (pauseMainTask == 0 && weight != lastWeight && hasReadRfidTag == 0 && (!autoSendToBambu || autoSetToBambuSpoolId == 0))
{
if (mainTaskWasPaused || (weight != lastWeight && nfcReaderState == NFC_IDLE && (!autoSendToBambu || autoSetToBambuSpoolId == 0)))
{
(weight < 2) ? ((weight < -2) ? oledShowMessage("!! -0") : oledShowWeight(0)) : oledShowWeight(weight);
}
mainTaskWasPaused = false;
}
else
{
mainTaskWasPaused = true;
(weight < 2) ? ((weight < -2) ? oledShowMessage("!! -0") : oledShowWeight(0)) : oledShowWeight(weight);
}
// Wenn Timer abgelaufen und nicht gerade ein RFID-Tag geschrieben wird
if (currentMillis - lastWeightReadTime >= weightReadInterval && nfcReaderState < NFC_WRITING)
if (currentMillis - lastWeightReadTime >= weightReadInterval && hasReadRfidTag < 3)
{
lastWeightReadTime = currentMillis;
// Prüfen ob die Waage korrekt genullt ist
// Abweichung von 2g ignorieren
if (autoTare && (weight > 2 && weight < 7) || weight < -2)
if ((weight > 0 && weight < 5) || weight < 0)
{
scale_tare_counter++;
}
@ -191,7 +169,7 @@ void loop() {
}
// Prüfen ob das Gewicht gleich bleibt und dann senden
if (abs(weight - lastWeight) <= 2 && weight > 5)
if (weight == lastWeight && weight > 5)
{
weigthCouterToApi++;
}
@ -203,8 +181,7 @@ void loop() {
}
// reset weight counter after writing tag
// TBD: what exactly is the logic behind this?
if (currentMillis - lastWeightReadTime >= weightReadInterval && nfcReaderState != NFC_IDLE && nfcReaderState != NFC_READ_SUCCESS)
if (currentMillis - lastWeightReadTime >= weightReadInterval && hasReadRfidTag > 1)
{
weigthCouterToApi = 0;
}
@ -212,7 +189,7 @@ void loop() {
lastWeight = weight;
// Wenn ein Tag mit SM id erkannte wurde und der Waage Counter anspricht an SM Senden
if (spoolId != "" && weigthCouterToApi > 3 && weightSend == 0 && nfcReaderState == NFC_READ_SUCCESS) {
if (spoolId != "" && weigthCouterToApi > 3 && weightSend == 0 && hasReadRfidTag == 1) {
oledShowIcon("loading");
if (updateSpoolWeight(spoolId, weight))
{
@ -220,11 +197,6 @@ void loop() {
vTaskDelay(2000 / portTICK_PERIOD_MS);
weightSend = 1;
autoSetToBambuSpoolId = spoolId.toInt();
if (octoEnabled)
{
updateSpoolOcto(autoSetToBambuSpoolId);
}
}
else
{
@ -232,6 +204,7 @@ void loop() {
vTaskDelay(2000 / portTICK_PERIOD_MS);
}
}
yield();
esp_task_wdt_reset();
}

View File

@ -18,7 +18,7 @@ String spoolId = "";
String nfcJsonData = "";
volatile bool pauseBambuMqttTask = false;
volatile nfcReaderStateType nfcReaderState = NFC_IDLE;
volatile uint8_t hasReadRfidTag = 0;
// 0 = nicht gelesen
// 1 = erfolgreich gelesen
// 2 = fehler beim Lesen
@ -44,6 +44,8 @@ void payloadToJson(uint8_t *data) {
DeserializationError error = deserializeJson(doc, jsonString);
if (!error) {
const char* version = doc["version"];
const char* protocol = doc["protocol"];
const char* color_hex = doc["color_hex"];
const char* type = doc["type"];
int min_temp = doc["min_temp"];
@ -53,6 +55,8 @@ void payloadToJson(uint8_t *data) {
Serial.println();
Serial.println("-----------------");
Serial.println("JSON-Parsed Data:");
Serial.println(version);
Serial.println(protocol);
Serial.println(color_hex);
Serial.println(type);
Serial.println(min_temp);
@ -89,16 +93,8 @@ bool formatNdefTag() {
return success;
}
uint16_t readTagSize()
{
uint8_t buffer[4];
memset(buffer, 0, 4);
nfc.ntag2xx_ReadPage(3, buffer);
return buffer[2]*8;
}
uint8_t ntag2xx_WriteNDEF(const char *payload) {
uint16_t tagSize = readTagSize();
uint8_t tagSize = 240; // 144 bytes is maximum for NTAG213
Serial.print("Tag Size: ");Serial.println(tagSize);
uint8_t pageBuffer[4] = {0, 0, 0, 0};
@ -140,8 +136,6 @@ uint8_t ntag2xx_WriteNDEF(const char *payload) {
if (combinedData == NULL)
{
Serial.println("Fehler: Nicht genug Speicher vorhanden.");
oledShowMessage("Tag too small");
vTaskDelay(2000 / portTICK_PERIOD_MS);
return 0;
}
@ -242,7 +236,7 @@ void writeJsonToTag(void *parameter) {
Serial.println("Erstelle NDEF-Message...");
Serial.println(payload);
nfcReaderState = NFC_WRITING;
hasReadRfidTag = 3;
vTaskSuspend(RfidReaderTask);
vTaskDelay(50 / portTICK_PERIOD_MS);
@ -288,7 +282,7 @@ void writeJsonToTag(void *parameter) {
//oledShowMessage("NFC-Tag written");
oledShowIcon("success");
vTaskDelay(1000 / portTICK_PERIOD_MS);
nfcReaderState = NFC_WRITE_SUCCESS;
hasReadRfidTag = 5;
// aktualisieren der Website wenn sich der Status ändert
sendNfcData(nullptr);
pauseBambuMqttTask = false;
@ -310,7 +304,7 @@ void writeJsonToTag(void *parameter) {
Serial.println("Fehler beim Schreiben der NDEF-Message auf den Tag");
oledShowIcon("failed");
vTaskDelay(2000 / portTICK_PERIOD_MS);
nfcReaderState = NFC_WRITE_ERROR;
hasReadRfidTag = 4;
}
}
else
@ -318,7 +312,7 @@ void writeJsonToTag(void *parameter) {
Serial.println("Fehler: Kein Tag zu schreiben gefunden.");
oledShowMessage("No NFC-Tag found");
vTaskDelay(2000 / portTICK_PERIOD_MS);
nfcReaderState = NFC_IDLE;
hasReadRfidTag = 0;
}
sendWriteResult(nullptr, success);
@ -334,7 +328,7 @@ void startWriteJsonToTag(const char* payload) {
char* payloadCopy = strdup(payload);
// Task nicht mehrfach starten
if (nfcReaderState != NFC_WRITING) {
if (hasReadRfidTag != 3) {
// Erstelle die Task
xTaskCreate(
writeJsonToTag, // Task-Funktion
@ -351,7 +345,7 @@ void scanRfidTask(void * parameter) {
Serial.println("RFID Task gestartet");
for(;;) {
// Wenn geschrieben wird Schleife aussetzen
if (nfcReaderState != NFC_WRITING)
if (hasReadRfidTag != 3)
{
yield();
@ -363,63 +357,58 @@ void scanRfidTask(void * parameter) {
foundNfcTag(nullptr, success);
if (success && nfcReaderState != NFC_READ_SUCCESS)
if (success && hasReadRfidTag != 1)
{
// Display some basic information about the card
Serial.println("Found an ISO14443A card");
nfcReaderState = NFC_READING;
hasReadRfidTag = 6;
oledShowIcon("transfer");
vTaskDelay(500 / portTICK_PERIOD_MS);
if (uidLength == 7)
{
uint16_t tagSize = readTagSize();
if(tagSize > 0)
{
// Create a buffer depending on the size of the tag
uint8_t* data = (uint8_t*)malloc(tagSize);
memset(data, 0, tagSize);
uint8_t data[256];
// We probably have an NTAG2xx card (though it could be Ultralight as well)
Serial.println("Seems to be an NTAG2xx tag (7 byte UID)");
uint8_t numPages = readTagSize()/4;
for (uint8_t i = 4; i < 4+numPages; i++) {
if (!nfc.ntag2xx_ReadPage(i, data+(i-4) * 4))
{
break; // Stop if reading fails
// We probably have an NTAG2xx card (though it could be Ultralight as well)
Serial.println("Seems to be an NTAG2xx tag (7 byte UID)");
for (uint8_t i = 0; i < 45; i++) {
/*
if (i < uidLength) {
uidString += String(uid[i], HEX);
if (i < uidLength - 1) {
uidString += ":"; // Optional: Trennzeichen hinzufügen
}
// Check for NDEF message end
if (data[(i - 4) * 4] == 0xFE)
{
break; // End of NDEF message
}
yield();
esp_task_wdt_reset();
vTaskDelay(pdMS_TO_TICKS(1));
}
if (!decodeNdefAndReturnJson(data))
*/
if (!nfc.mifareclassic_ReadDataBlock(i, data + (i - 4) * 4))
{
oledShowMessage("NFC-Tag unknown");
vTaskDelay(2000 / portTICK_PERIOD_MS);
nfcReaderState = NFC_READ_ERROR;
break; // Stop if reading fails
}
else
// Check for NDEF message end
if (data[(i - 4) * 4] == 0xFE)
{
nfcReaderState = NFC_READ_SUCCESS;
break; // End of NDEF message
}
free(data);
yield();
esp_task_wdt_reset();
vTaskDelay(pdMS_TO_TICKS(1));
}
else
if (!decodeNdefAndReturnJson(data))
{
oledShowMessage("NFC-Tag read error");
nfcReaderState = NFC_READ_ERROR;
oledShowMessage("NFC-Tag unknown");
vTaskDelay(2000 / portTICK_PERIOD_MS);
hasReadRfidTag = 2;
}
else
{
hasReadRfidTag = 1;
}
}
else
{
@ -427,9 +416,9 @@ void scanRfidTask(void * parameter) {
}
}
if (!success && nfcReaderState != NFC_IDLE)
if (!success && hasReadRfidTag > 0)
{
nfcReaderState = NFC_IDLE;
hasReadRfidTag = 0;
//uidString = "";
nfcJsonData = "";
Serial.println("Tag entfernt");

View File

@ -3,16 +3,6 @@
#include <Arduino.h>
typedef enum{
NFC_IDLE,
NFC_READING,
NFC_READ_SUCCESS,
NFC_READ_ERROR,
NFC_WRITING,
NFC_WRITE_SUCCESS,
NFC_WRITE_ERROR
} nfcReaderStateType;
void startNfc();
void scanRfidTask(void * parameter);
void startWriteJsonToTag(const char* payload);
@ -20,9 +10,7 @@ void startWriteJsonToTag(const char* payload);
extern TaskHandle_t RfidReaderTask;
extern String nfcJsonData;
extern String spoolId;
extern volatile nfcReaderStateType nfcReaderState;
extern volatile uint8_t hasReadRfidTag;
extern volatile bool pauseBambuMqttTask;
#endif

View File

@ -1,10 +1,6 @@
#include <Arduino.h>
#include <website.h>
#include <commonFS.h>
#include "scale.h"
#include "bambu.h"
#include "nfc.h"
// Globale Variablen für Config Backups hinzufügen
String bambuCredentialsBackup;
@ -18,34 +14,6 @@ static size_t updateTotalSize = 0;
static size_t updateWritten = 0;
static bool isSpiffsUpdate = false;
/**
* Compares two version strings and determines if version1 is less than version2
*
* @param version1 First version string (format: x.y.z)
* @param version2 Second version string (format: x.y.z)
* @return true if version1 is less than version2
*/
bool isVersionLessThan(const String& version1, const String& version2) {
int major1 = 0, minor1 = 0, patch1 = 0;
int major2 = 0, minor2 = 0, patch2 = 0;
// Parse version1
sscanf(version1.c_str(), "%d.%d.%d", &major1, &minor1, &patch1);
// Parse version2
sscanf(version2.c_str(), "%d.%d.%d", &major2, &minor2, &patch2);
// Compare major version
if (major1 < major2) return true;
if (major1 > major2) return false;
// Major versions equal, compare minor
if (minor1 < minor2) return true;
if (minor1 > minor2) return false;
// Minor versions equal, compare patch
return patch1 < patch2;
}
void backupJsonConfigs() {
// Bambu Credentials backup
@ -143,37 +111,8 @@ void handleUpdate(AsyncWebServer &server) {
updateHandler->setUri("/update");
updateHandler->setMethod(HTTP_POST);
// Check if current version is less than defined TOOLVERSION before proceeding with update
if (isVersionLessThan(VERSION, TOOLDVERSION)) {
updateHandler->onRequest([](AsyncWebServerRequest *request) {
request->send(400, "application/json",
"{\"success\":false,\"message\":\"Your current version is too old. Please perform a full upgrade.\"}");
});
server.addHandler(updateHandler);
return;
}
updateHandler->onUpload([](AsyncWebServerRequest *request, String filename,
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);
ScaleTask = NULL;
}
if (RfidReaderTask) {
Serial.println("Delete RfidReaderTask");
vTaskDelete(RfidReaderTask);
RfidReaderTask = NULL;
}
if (!index) {
updateTotalSize = request->contentLength();
updateWritten = 0;
@ -182,9 +121,9 @@ void handleUpdate(AsyncWebServer &server) {
if (isSpiffsUpdate) {
// Backup vor dem Update
sendUpdateProgress(0, "backup", "Backing up configurations...");
vTaskDelay(200 / portTICK_PERIOD_MS);
delay(200);
backupJsonConfigs();
vTaskDelay(200 / portTICK_PERIOD_MS);
delay(200);
const esp_partition_t *partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_SPIFFS, NULL);
if (!partition || !Update.begin(partition->size, U_SPIFFS)) {
@ -192,14 +131,14 @@ void handleUpdate(AsyncWebServer &server) {
return;
}
sendUpdateProgress(5, "starting", "Starting SPIFFS update...");
vTaskDelay(200 / portTICK_PERIOD_MS);
delay(200);
} else {
if (!Update.begin(updateTotalSize)) {
request->send(400, "application/json", "{\"success\":false,\"message\":\"Update initialization failed\"}");
return;
}
sendUpdateProgress(0, "starting", "Starting firmware update...");
vTaskDelay(200 / portTICK_PERIOD_MS);
delay(200);
}
}
@ -225,7 +164,7 @@ void handleUpdate(AsyncWebServer &server) {
if (currentProgress != lastProgress && (currentProgress % 10 == 0 || final)) {
sendUpdateProgress(currentProgress, "uploading");
oledShowMessage("Update: " + String(currentProgress) + "%");
vTaskDelay(50 / portTICK_PERIOD_MS);
delay(50);
lastProgress = currentProgress;
}
}

View File

@ -15,30 +15,14 @@ int16_t weight = 0;
uint8_t weigthCouterToApi = 0;
uint8_t scale_tare_counter = 0;
bool scaleTareRequest = false;
uint8_t pauseMainTask = 0;
uint8_t scaleCalibrated = 1;
Preferences preferences;
const char* NVS_NAMESPACE = "scale";
const char* NVS_KEY_CALIBRATION = "cal_value";
const char* NVS_KEY_AUTOTARE = "auto_tare";
bool autoTare = true;
// ##### Funktionen für Waage #####
uint8_t setAutoTare(bool autoTareValue) {
Serial.print("Set AutoTare to ");
Serial.println(autoTareValue);
autoTare = autoTareValue;
// Speichern mit NVS
preferences.begin(NVS_NAMESPACE, false); // false = readwrite
preferences.putBool(NVS_KEY_AUTOTARE, autoTare);
preferences.end();
return 1;
}
uint8_t tareScale() {
Serial.println("Tare scale");
scale.tare();
@ -50,51 +34,30 @@ void scale_loop(void * parameter) {
Serial.println("++++++++++++++++++++++++++++++");
Serial.println("Scale Loop started");
Serial.println("++++++++++++++++++++++++++++++");
for(;;) {
if (scale.is_ready())
{
// Waage automatisch Taren, wenn zu lange Abweichung
if (autoTare && scale_tare_counter >= 5)
// Waage nochmal Taren, wenn zu lange Abweichung
if (scale_tare_counter >= 5)
{
Serial.println("Auto Tare scale");
scale.tare();
scale_tare_counter = 0;
}
// Waage manuell Taren
if (scaleTareRequest == true)
{
Serial.println("Re-Tare scale");
oledShowMessage("TARE Scale");
vTaskDelay(pdMS_TO_TICKS(1000));
scale.tare();
vTaskDelay(pdMS_TO_TICKS(1000));
oledShowWeight(0);
scaleTareRequest = false;
}
weight = round(scale.get_units());
}
vTaskDelay(pdMS_TO_TICKS(100));
vTaskDelay(pdMS_TO_TICKS(100)); // Verzögerung, um die CPU nicht zu überlasten
}
}
void start_scale(bool touchSensorConnected) {
uint8_t start_scale() {
Serial.println("Prüfe Calibration Value");
float calibrationValue;
long calibrationValue;
// NVS lesen
preferences.begin(NVS_NAMESPACE, true); // true = readonly
calibrationValue = preferences.getFloat(NVS_KEY_CALIBRATION, defaultScaleCalibrationValue);
// auto Tare
// Wenn Touch Sensor verbunden, dann autoTare auf false setzen
// Danach prüfen was in NVS gespeichert ist
autoTare = (touchSensorConnected) ? false : true;
autoTare = preferences.getBool(NVS_KEY_AUTOTARE, autoTare);
calibrationValue = preferences.getLong(NVS_KEY_CALIBRATION, defaultScaleCalibrationValue);
preferences.end();
Serial.print("Read Scale Calibration Value ");
@ -105,13 +68,6 @@ void start_scale(bool touchSensorConnected) {
if (isnan(calibrationValue) || calibrationValue < 1) {
calibrationValue = defaultScaleCalibrationValue;
scaleCalibrated = 0;
oledShowMessage("Scale not calibrated!");
for (uint16_t i = 0; i < 50000; i++) {
yield();
vTaskDelay(pdMS_TO_TICKS(1));
esp_task_wdt_reset();
}
}
oledShowMessage("Scale Tare Please remove all");
@ -134,7 +90,7 @@ void start_scale(bool touchSensorConnected) {
BaseType_t result = xTaskCreatePinnedToCore(
scale_loop, /* Function to implement the task */
"ScaleLoop", /* Name of the task */
2048, /* Stack size in words */
10000, /* Stack size in words */
NULL, /* Task input parameter */
scaleTaskPrio, /* Priority of the task */
&ScaleTask, /* Task handle. */
@ -145,21 +101,20 @@ void start_scale(bool touchSensorConnected) {
} else {
Serial.println("ScaleLoop-Task erfolgreich erstellt");
}
return (scaleCalibrated == 1) ? 1 : 3;
}
uint8_t calibrate_scale() {
uint8_t returnState = 0;
float newCalibrationValue;
vTaskSuspend(RfidReaderTask);
vTaskSuspend(ScaleTask);
long newCalibrationValue;
//vTaskSuspend(RfidReaderTask);
vTaskDelete(RfidReaderTask);
pauseBambuMqttTask = true;
pauseMainTask = 1;
if (scale.wait_ready_timeout(1000))
{
scale.set_scale();
oledShowMessage("Step 1 empty Scale");
@ -181,7 +136,7 @@ uint8_t calibrate_scale() {
esp_task_wdt_reset();
}
float newCalibrationValue = scale.get_units(10);
long newCalibrationValue = scale.get_units(10);
Serial.print("Result: ");
Serial.println(newCalibrationValue);
@ -194,33 +149,28 @@ uint8_t calibrate_scale() {
// Speichern mit NVS
preferences.begin(NVS_NAMESPACE, false); // false = readwrite
preferences.putFloat(NVS_KEY_CALIBRATION, newCalibrationValue);
preferences.putLong(NVS_KEY_CALIBRATION, newCalibrationValue);
preferences.end();
// Verifizieren
preferences.begin(NVS_NAMESPACE, true);
float verifyValue = preferences.getFloat(NVS_KEY_CALIBRATION, 0);
long verifyValue = preferences.getLong(NVS_KEY_CALIBRATION, 0);
preferences.end();
Serial.print("Verified stored value: ");
Serial.println(verifyValue);
Serial.println("End calibration, remove weight");
Serial.println("End calibration, revome weight");
oledShowMessage("Remove weight");
scale.set_scale(newCalibrationValue);
for (uint16_t i = 0; i < 2000; i++) {
yield();
vTaskDelay(pdMS_TO_TICKS(1));
esp_task_wdt_reset();
}
oledShowMessage("Scale calibrated");
// For some reason it is not possible to re-tare the scale here, it will result in a wdt timeout. Instead let the scale loop do the taring
//scale.tare();
scaleTareRequest = true;
oledShowMessage("Calibration done");
for (uint16_t i = 0; i < 2000; i++) {
yield();
@ -228,9 +178,8 @@ uint8_t calibrate_scale() {
esp_task_wdt_reset();
}
returnState = 1;
//ESP.restart();
}
else
{
{
@ -243,10 +192,10 @@ uint8_t calibrate_scale() {
vTaskDelay(pdMS_TO_TICKS(1));
esp_task_wdt_reset();
}
returnState = 0;
return 0;
}
}
}
}
}
else
{
Serial.println("HX711 not found.");
@ -258,13 +207,17 @@ uint8_t calibrate_scale() {
vTaskDelay(pdMS_TO_TICKS(1));
esp_task_wdt_reset();
}
returnState = 0;
return 0;
}
vTaskResume(RfidReaderTask);
vTaskResume(ScaleTask);
oledShowMessage("Scale Ready");
Serial.println("starte Scale Task");
start_scale();
pauseBambuMqttTask = false;
pauseMainTask = 0;
return returnState;
return 1;
}

View File

@ -4,8 +4,8 @@
#include <Arduino.h>
#include "HX711.h"
uint8_t setAutoTare(bool autoTareValue);
uint8_t start_scale(bool touchSensorConnected);
uint8_t start_scale();
uint8_t calibrate_scale();
uint8_t tareScale();
@ -13,10 +13,8 @@ extern HX711 scale;
extern int16_t weight;
extern uint8_t weigthCouterToApi;
extern uint8_t scale_tare_counter;
extern uint8_t scaleTareRequest;
extern uint8_t pauseMainTask;
extern uint8_t scaleCalibrated;
extern bool autoTare;
extern TaskHandle_t ScaleTask;

View File

@ -22,14 +22,14 @@ AsyncWebServer server(webserverPort);
AsyncWebSocket ws("/ws");
uint8_t lastSuccess = 0;
nfcReaderStateType lastnfcReaderState = NFC_IDLE;
uint8_t lastHasReadRfidTag = 0;
void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) {
if (type == WS_EVT_CONNECT) {
Serial.println("Neuer Client verbunden!");
// Sende die AMS-Daten an den neuen Client
if (!bambuDisabled) sendAmsData(client);
sendAmsData(client);
sendNfcData(client);
foundNfcTag(client, 0);
sendWriteResult(client, 3);
@ -44,15 +44,13 @@ void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventTyp
JsonDocument doc;
deserializeJson(doc, message);
bool spoolmanConnected = (spoolmanApiState != API_INIT);
if (doc["type"] == "heartbeat") {
// Sende Heartbeat-Antwort
ws.text(client->id(), "{"
"\"type\":\"heartbeat\","
"\"freeHeap\":" + String(ESP.getFreeHeap()/1024) + ","
"\"bambu_connected\":" + String(bambu_connected) + ","
"\"spoolman_connected\":" + String(spoolmanConnected) + ""
"\"spoolman_connected\":" + String(spoolman_connected) + ""
"}");
}
@ -75,10 +73,6 @@ void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventTyp
success = calibrate_scale();
}
if (doc["payload"] == "setAutoTare") {
success = setAutoTare(doc["enabled"].as<bool>());
}
if (success) {
ws.textAll("{\"type\":\"scale\",\"payload\":\"success\"}");
} else {
@ -145,31 +139,34 @@ void foundNfcTag(AsyncWebSocketClient *client, uint8_t success) {
}
void sendNfcData(AsyncWebSocketClient *client) {
if (lastnfcReaderState == nfcReaderState) return;
// TBD: Why is there no status for reading the tag?
switch(nfcReaderState){
case NFC_IDLE:
ws.textAll("{\"type\":\"nfcData\", \"payload\":{}}");
break;
case NFC_READ_SUCCESS:
ws.textAll("{\"type\":\"nfcData\", \"payload\":" + nfcJsonData + "}");
break;
case NFC_READ_ERROR:
ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"error\":\"Empty Tag or Data not readable\"}}");
break;
case NFC_WRITING:
ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"info\":\"Schreibe Tag...\"}}");
break;
case NFC_WRITE_SUCCESS:
ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"info\":\"Tag erfolgreich geschrieben\"}}");
break;
case NFC_WRITE_ERROR:
ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"error\":\"Error writing to Tag\"}}");
break;
case DEFAULT:
ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"error\":\"Something went wrong\"}}");
if (lastHasReadRfidTag == hasReadRfidTag) return;
if (hasReadRfidTag == 0) {
ws.textAll("{\"type\":\"nfcData\", \"payload\":{}}");
}
lastnfcReaderState = nfcReaderState;
else if (hasReadRfidTag == 1) {
ws.textAll("{\"type\":\"nfcData\", \"payload\":" + nfcJsonData + "}");
}
else if (hasReadRfidTag == 2)
{
ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"error\":\"Empty Tag or Data not readable\"}}");
}
else if (hasReadRfidTag == 3)
{
ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"info\":\"Schreibe Tag...\"}}");
}
else if (hasReadRfidTag == 4)
{
ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"error\":\"Error writing to Tag\"}}");
}
else if (hasReadRfidTag == 5)
{
ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"info\":\"Tag erfolgreich geschrieben\"}}");
}
else
{
ws.textAll("{\"type\":\"nfcData\", \"payload\":{\"error\":\"Something went wrong\"}}");
}
lastHasReadRfidTag = hasReadRfidTag;
}
void sendAmsData(AsyncWebSocketClient *client) {
@ -207,23 +204,16 @@ 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);
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/waage.html.gz", "text/html");
response->addHeader("Content-Encoding", "gzip");
response->addHeader("Cache-Control", CACHE_CONTROL);
request->send(response);
});
// 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);
@ -249,10 +239,7 @@ void setupWebserver(AsyncWebServer &server) {
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("{{spoolmanUrl}}", spoolmanUrl);
JsonDocument doc;
if (loadJsonValue("/bambu_credentials.json", doc) && doc["bambu_ip"].is<String>())
@ -290,45 +277,17 @@ void setupWebserver(AsyncWebServer &server) {
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);
bool healthy = saveSpoolmanUrl(url);
String jsonResponse = "{\"healthy\": " + String(healthy ? "true" : "false") + "}";
request->send(200, "application/json", jsonResponse);
});
// Route für das Überprüfen der Bambu-Instanz
// Route für das Überprüfen der Spoolman-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->send(400, "application/json", "{\"success\": false, \"error\": \"Missing parameter\"}");
return;

View File

@ -59,7 +59,7 @@ void initWiFi() {
if(wm_nonblocking) wm.setConfigPortalBlocking(false);
//wm.setConfigPortalTimeout(320); // Portal nach 5min schließen
wm.setWiFiAutoReconnect(true);
wm.setConnectTimeout(10);
wm.setConnectTimeout(5);
oledShowTopRow();
oledShowMessage("WiFi Setup");

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 540 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 525 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 183 KiB

View File

@ -1,12 +0,0 @@
## **Heat insert location**
Housing:
- every hole is made to fit a heat insert
![](./Housing_Heatinsert_Location_usermod_spitzbirne32_.png)
---
Scale top:
- two heat inserts for the NFC Reader
![](./ScaleTop_Heatinsert_Location_usermod_spitzbirne32_.png)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 491 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 834 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 MiB

View File

@ -1,69 +0,0 @@
## Modifications
To reduce costs, components were sourced from AliExpress instead of Amazon. However, differences in dimensions and mounting hole spacing necessitated adjustments to the 3D-printed parts. Additionally M3 heat inserts were used to limit M4 screws to a minimum.
![](./Images/Showcase_usermod_spitzbirne32.gif)
---
List of parts that were used:
- Display: https://aliexpress.com/item/1005007389730469.html
- Scale(5KG with HX711): https://aliexpress.com/item/1005006827930173.html
- NFC Reader: https://aliexpress.com/item/1005005973913526.html
- NFC Chips: https://aliexpress.com/item/1005006332360160.html
- [VORON](https://vorondesign.com/) Heat Inserts M3 OD5mm L4mm: https://aliexpress.com/item/1005003582355741.html - make sure to select the correct size
---
- **Parts are designed to be printed in ABS/ASA.** Shrinking compensation not needed.
- **Display and Scale Adjustments:** The AliExpress-sourced display and scale had different dimensions and hole spacings compared to the Amazon versions. The 3D models were modified to accommodate these differences, ensuring proper fit and functionality.
- measurement of my Display & Scale to check if your parts will fit can be found in the images folder
- **Screw Size and Heat Inserts:** All holes originally designed for M4 screws were resized to fit M3 screws. Standard VORON heat inserts were incorporated to provide durable threading. This change standardizes the hardware and simplifies assembly.
- **Display Mounting:** The display is now mounted using M3 screws with VORON heat inserts. The display's mounting holes need to be drilled to 3mm to accommodate the M3 screws.
- **Scale Top Surface:** The top surface of the scale was modified to allow M3 socket head cap screws to sit flush with the 3D-printed part. This design ensures that the filament spool rests flat without interference.
- **NFC Reader Mounting:** The NFC reader is also secured using M3 screws and VORON heat inserts, maintaining consistency across all components.
- **Scale Base Mounting:** The only M4 screws required are for attaching the metal part of the scale to its base.
## Benefits of Modifications
- **Cost Reduction:** Sourcing components from AliExpress offers a more affordable alternative to Amazon, making the project more accessible.
- **Standardized Hardware:** Using M3 screws and [VORON](https://vorondesign.com/) heat inserts throughout the assembly simplifies the build process and reduces the variety of required hardware.
- **Enhanced Compatibility:** Adjustments to the 3D models ensure compatibility with readily available components, accommodating variations in part dimensions.
## Assembly Instructions
1. **Component Preparation:**
- Carefully drill the display's mounting holes to 3mm to fit M3 screws.
2. **Heat Insert Installation:**
- install VORON M3 heat inserts into the designated holes in the 3D-printed housing/case for the ESP32 and Scale top &#8594; [heat insert location pictures](./Images/README.md)
3. **Component Mounting:**
- Attach the display, scale, and NFC reader to their respective mounts using M3 screws.
- Secure the metal part of the scale to its base using M4 screws.
4. **Final Assembly:**
- Assemble all components according to the original FilaMan instructions, ensuring that all modified parts fit correctly and function as intended.
For detailed assembly guides and additional resources, refer to the [original FilaMan documentation](https://github.com/ManuelW77/Filaman).
## Conclusion
These modifications to the FilaMan project provide a cost-effective and standardized approach to building a filament management system. By sourcing components from AliExpress and adjusting the 3D models accordingly, users can achieve the same functionality at a reduced cost, with the added benefit of using uniform hardware throughout the assembly.
## Changelog
### Version 1.0 - 2025-03-04
- Initial release of modifications for AliExpress-sourced components.
- Adjusted 3D models to fit different display and scale dimensions.
- Replaced M4 screws with M3 screws and integrated VORON heat inserts.
- Modified display mounting, requiring drilling to 3mm for M3 screws.
- Adjusted scale top surface for flush screw placement.
- Standardized NFC reader mounting with M3 screws and VORON heat inserts.
- Retained M4 screws only for metal scale attachment.