Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7fdfc79a2a | ||
|
|
894d1d25dd | ||
|
|
a3dd4b164e | ||
|
|
0f8d3d470d | ||
|
|
20ab21dae5 | ||
|
|
a14ab8fa55 | ||
|
|
96a5e184dd | ||
|
|
bc0d586c9e | ||
|
|
ddf981b971 | ||
|
|
1b7a71b617 |
No files matched your search
+57
-2
@@ -41,11 +41,11 @@
|
||||
|
||||
<div class="fm-card">
|
||||
<h2>System Registration</h2>
|
||||
<p>Current Status: <strong style="color: var(--accent);">{{registered}}</strong></p>
|
||||
<p>Current Status: <strong style="color: var(--accent);">%registered%</strong></p>
|
||||
|
||||
<div class="fm-form-group" style="margin-top: 2rem;">
|
||||
<label class="fm-label" for="filamanUrl">FilaMan API URL</label>
|
||||
<input type="text" id="filamanUrl" class="fm-input" value="{{filamanUrl}}" placeholder="e.g. http://192.168.1.10:8000">
|
||||
<input type="text" id="filamanUrl" class="fm-input" value="%filamanUrl%" placeholder="e.g. http://192.168.1.10:8000">
|
||||
</div>
|
||||
|
||||
<div class="fm-form-group">
|
||||
@@ -69,6 +69,24 @@
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="fm-card">
|
||||
<h2>Display Settings</h2>
|
||||
|
||||
<div class="fm-form-group" style="margin-top: 1rem;">
|
||||
<label class="fm-label" for="sleepTimeoutSelect">OLED Sleep Timeout</label>
|
||||
<select id="sleepTimeoutSelect" class="fm-input">
|
||||
<option value="0">Disabled (always on)</option>
|
||||
<option value="30">30 seconds</option>
|
||||
<option value="60">1 minute</option>
|
||||
<option value="120">2 minutes</option>
|
||||
<option value="300">5 minutes</option>
|
||||
<option value="600">10 minutes</option>
|
||||
</select>
|
||||
<p style="font-size: 0.8rem; margin-top: 0.5rem;">Display wakes automatically on weight change or NFC tag read.</p>
|
||||
</div>
|
||||
<div id="sleepStatusMessage" style="margin-top: 0.5rem;"></div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
@@ -105,6 +123,43 @@
|
||||
.catch(error => console.error('Error saving language:', error));
|
||||
});
|
||||
|
||||
// Display sleep timeout setting
|
||||
fetch('/api/display')
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
const sel = document.getElementById('sleepTimeoutSelect');
|
||||
const val = String(data.sleepTimeout);
|
||||
// Select closest matching option
|
||||
let matched = false;
|
||||
for (let i = 0; i < sel.options.length; i++) {
|
||||
if (sel.options[i].value === val) { sel.value = val; matched = true; break; }
|
||||
}
|
||||
if (!matched) sel.value = '0';
|
||||
})
|
||||
.catch(error => console.error('Error fetching display settings:', error));
|
||||
|
||||
document.getElementById('sleepTimeoutSelect').addEventListener('change', function() {
|
||||
const msg = document.getElementById('sleepStatusMessage');
|
||||
fetch('/api/display', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ sleepTimeout: parseInt(this.value) })
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
msg.textContent = 'Saved.';
|
||||
msg.style.color = 'var(--success-text)';
|
||||
setTimeout(() => { msg.textContent = ''; }, 2000);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
msg.textContent = 'Error saving setting.';
|
||||
msg.style.color = 'var(--error-text)';
|
||||
console.error('Error saving display settings:', error);
|
||||
});
|
||||
});
|
||||
|
||||
document.getElementById('registerBtn').addEventListener('click', () => {
|
||||
const url = document.getElementById('filamanUrl').value;
|
||||
const code = document.getElementById('deviceCode').value;
|
||||
|
||||
+1
-1
@@ -46,7 +46,7 @@
|
||||
<button id="tareBtn" class="fm-btn fm-btn-outline">Tare Scale</button>
|
||||
|
||||
<label class="status-pill" style="display: flex; align-items: center; gap: 0.5rem; cursor: pointer;">
|
||||
<input type="checkbox" id="autoTareCheckbox" onchange="setAutoTare(this.checked);" {{autoTare}}>
|
||||
<input type="checkbox" id="autoTareCheckbox" onchange="setAutoTare(this.checked);" %autoTare%>
|
||||
<span>Enable Auto-TARE</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
+24
-6
@@ -9,12 +9,12 @@
|
||||
; https://docs.platformio.org/page/projectconf.html
|
||||
|
||||
[common]
|
||||
version = "3.2.6"
|
||||
version = "3.2.7-beta1"
|
||||
to_old_version = "3.0.9"
|
||||
|
||||
##
|
||||
[env:esp32dev]
|
||||
platform = espressif32
|
||||
platform = espressif32@^6.0.0
|
||||
board = esp32dev
|
||||
framework = arduino
|
||||
monitor_speed = 115200
|
||||
@@ -55,11 +55,29 @@ build_flags =
|
||||
#-DOTA_DEBUG=1
|
||||
-DCONFIG_OPTIMIZATION_LEVEL_DEBUG=1
|
||||
-DBOOT_APP_PARTITION_OTA_0=1
|
||||
-DCONFIG_LWIP_TCP_MSL=60000
|
||||
-DCONFIG_LWIP_TCP_RCV_BUF_DEFAULT=4096
|
||||
|
||||
# ===== AsyncTCP Optimierungen - KRITISCH für WiFi-Stabilität =====
|
||||
# Core 1 = Arduino/App Core (nicht Core 0 = WiFi/Protocol Core!)
|
||||
# Schwere Callbacks auf Core 0 stören das WiFi-Radio
|
||||
-DCONFIG_ASYNC_TCP_RUNNING_CORE=1
|
||||
# Längerer ACK-Timeout für instabile Verbindungen (10s statt 5s)
|
||||
-DCONFIG_ASYNC_TCP_MAX_ACK_TIME=10000
|
||||
# Größere Queue für mehr gleichzeitige Requests
|
||||
-DCONFIG_ASYNC_TCP_QUEUE_SIZE=128
|
||||
# Mehr Stack für komplexere Callbacks (8KB statt 16KB default, spart RAM)
|
||||
-DCONFIG_ASYNC_TCP_STACK_SIZE=8192
|
||||
# Standard-Priorität beibehalten
|
||||
-DCONFIG_ASYNC_TCP_PRIORITY=10
|
||||
# WDT aktivieren für Crash-Recovery (war deaktiviert!)
|
||||
-DCONFIG_ASYNC_TCP_USE_WDT=1
|
||||
|
||||
# ===== LwIP Optimierungen für OTA-Uploads (1.5-2MB) =====
|
||||
# Schnellere Socket-Freigabe (30s statt 60s TIME_WAIT)
|
||||
-DCONFIG_LWIP_TCP_MSL=30000
|
||||
# Größerer RX-Buffer für große Uploads (8KB statt 4KB)
|
||||
-DCONFIG_LWIP_TCP_RCV_BUF_DEFAULT=8192
|
||||
# Max aktive TCP-Verbindungen (unverändert)
|
||||
-DCONFIG_LWIP_MAX_ACTIVE_TCP=16
|
||||
-DCONFIG_ASYNC_TCP_RUNNING_CORE=0
|
||||
-DCONFIG_ASYNC_TCP_USE_WDT=0
|
||||
|
||||
extra_scripts =
|
||||
scripts/extra_script.py
|
||||
|
||||
+28
-5
@@ -80,10 +80,12 @@ bool registerDevice(const String& deviceCode) {
|
||||
bool sendHeartbeat() {
|
||||
if (!checkFilamanRegistration() || WiFi.status() != WL_CONNECTED) return false;
|
||||
HTTPClient http;
|
||||
http.setTimeout(3000);
|
||||
http.setTimeout(10000); // 10s statt 3s - wichtig für instabile Verbindungen
|
||||
http.setReuse(true); // Keep-Alive aktivieren für bessere Performance
|
||||
http.begin(filamanUrl + "/api/v1/devices/heartbeat");
|
||||
http.addHeader("Content-Type", "application/json");
|
||||
http.addHeader("Authorization", "Device " + filamanToken);
|
||||
http.addHeader("Connection", "keep-alive"); // Explizit Keep-Alive anfordern
|
||||
JsonDocument doc;
|
||||
doc["ip_address"] = WiFi.localIP().toString();
|
||||
String payload;
|
||||
@@ -94,6 +96,21 @@ bool sendHeartbeat() {
|
||||
return filamanConnected;
|
||||
}
|
||||
|
||||
// Heartbeat mit Retry-Logik für mehr Stabilität
|
||||
bool sendHeartbeatWithRetry(int maxRetries = 2) {
|
||||
for (int attempt = 0; attempt <= maxRetries; attempt++) {
|
||||
if (sendHeartbeat()) {
|
||||
return true;
|
||||
}
|
||||
if (attempt < maxRetries) {
|
||||
Serial.printf("Heartbeat failed, retry %d/%d...\n", attempt + 1, maxRetries);
|
||||
vTaskDelay(pdMS_TO_TICKS(1000)); // 1s warten vor Retry
|
||||
}
|
||||
}
|
||||
Serial.println("Heartbeat failed after all retries");
|
||||
return false;
|
||||
}
|
||||
|
||||
bool sendWeight(int spoolId, String tagUuid, float measuredWeight) {
|
||||
Serial.printf("sendWeight: sending to API - spoolId=%d, tagUuid=%s, weight=%.1f\n", spoolId, tagUuid.c_str(), measuredWeight);
|
||||
if (!checkFilamanRegistration() || WiFi.status() != WL_CONNECTED) {
|
||||
@@ -101,10 +118,12 @@ bool sendWeight(int spoolId, String tagUuid, float measuredWeight) {
|
||||
return false;
|
||||
}
|
||||
HTTPClient http;
|
||||
http.setTimeout(3000);
|
||||
http.setTimeout(10000); // 10s Timeout
|
||||
http.setReuse(true);
|
||||
http.begin(filamanUrl + "/api/v1/devices/scale/weight");
|
||||
http.addHeader("Content-Type", "application/json");
|
||||
http.addHeader("Authorization", "Device " + filamanToken);
|
||||
http.addHeader("Connection", "keep-alive");
|
||||
JsonDocument doc;
|
||||
// Only add spool_id if it's > 0 (for NTAG tags with spool ID)
|
||||
// For Bambu tags (spoolId == 0), only send tag_uuid
|
||||
@@ -146,10 +165,12 @@ bool sendWeight(int spoolId, String tagUuid, float measuredWeight) {
|
||||
bool sendLocation(int spoolId, String spoolTagUuid, int locationId, String locationTagUuid) {
|
||||
if (!checkFilamanRegistration() || WiFi.status() != WL_CONNECTED) return false;
|
||||
HTTPClient http;
|
||||
http.setTimeout(3000);
|
||||
http.setTimeout(10000); // 10s Timeout
|
||||
http.setReuse(true);
|
||||
http.begin(filamanUrl + "/api/v1/devices/scale/locate");
|
||||
http.addHeader("Content-Type", "application/json");
|
||||
http.addHeader("Authorization", "Device " + filamanToken);
|
||||
http.addHeader("Connection", "keep-alive");
|
||||
JsonDocument doc;
|
||||
if (spoolId > 0) doc["spool_id"] = spoolId;
|
||||
if (spoolTagUuid.length() > 0) doc["spool_tag_uuid"] = spoolTagUuid;
|
||||
@@ -165,10 +186,12 @@ bool sendLocation(int spoolId, String spoolTagUuid, int locationId, String locat
|
||||
bool sendRfidResult(String tagUuid, int spoolId, int locationId, bool success, String errorMessage, float remainingWeight) {
|
||||
if (!checkFilamanRegistration() || WiFi.status() != WL_CONNECTED) return false;
|
||||
HTTPClient http;
|
||||
http.setTimeout(5000);
|
||||
http.setTimeout(10000); // 10s Timeout
|
||||
http.setReuse(true);
|
||||
http.begin(filamanUrl + "/api/v1/devices/rfid-result");
|
||||
http.addHeader("Content-Type", "application/json");
|
||||
http.addHeader("Authorization", "Device " + filamanToken);
|
||||
http.addHeader("Connection", "keep-alive");
|
||||
|
||||
JsonDocument doc;
|
||||
doc["success"] = success;
|
||||
@@ -205,7 +228,7 @@ void filamanApiTask(void* pvParameters) {
|
||||
if (hasReq) {
|
||||
filamanApiState = API_TRANSMITTING;
|
||||
switch (req.type) {
|
||||
case API_REQUEST_HEARTBEAT: sendHeartbeat(); break;
|
||||
case API_REQUEST_HEARTBEAT: sendHeartbeatWithRetry(2); break; // Mit Retry-Logik
|
||||
case API_REQUEST_WEIGHT: sendWeight(req.id1, req.str1, req.val); break;
|
||||
case API_REQUEST_LOCATE: sendLocation(req.id1, req.str1, req.id2, req.str2); break;
|
||||
case API_REQUEST_RFID_RESULT: sendRfidResult(req.str1, req.id1, req.id2, req.bool1, req.str3, req.remainingWeight); break;
|
||||
|
||||
+12
-2
@@ -57,10 +57,20 @@ String readFile(const char* filename) {
|
||||
Serial.println(filename);
|
||||
return "";
|
||||
}
|
||||
String content = "";
|
||||
|
||||
// Effizient: Speicher vorab allokieren und in Blöcken lesen
|
||||
// Alte Implementierung war O(n²) wegen Byte-für-Byte String-Konkatenation
|
||||
size_t fileSize = file.size();
|
||||
String content;
|
||||
content.reserve(fileSize + 1); // Speicher vorab allokieren
|
||||
|
||||
// Lese in 512-Byte Blöcken statt Byte für Byte
|
||||
char buffer[512];
|
||||
while (file.available()) {
|
||||
content += (char)file.read();
|
||||
size_t bytesRead = file.readBytes(buffer, sizeof(buffer));
|
||||
content.concat(buffer, bytesRead);
|
||||
}
|
||||
|
||||
file.close();
|
||||
return content;
|
||||
}
|
||||
|
||||
+3
-1
@@ -42,7 +42,9 @@ String filamanToken = "";
|
||||
bool filamanRegistered = false;
|
||||
// ***** API
|
||||
|
||||
// ***** Bambu Auto Set Spool
|
||||
// ***** Display Sleep
|
||||
uint16_t oledSleepTimeout = 60; // Default 60 seconds (0 = disabled)
|
||||
// ***** Display Sleep
|
||||
|
||||
// ***** Task Prios
|
||||
uint8_t rfidTaskCore = 1;
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
|
||||
#define NVS_NAMESPACE_SETTINGS "settings"
|
||||
#define NVS_KEY_LANGUAGE "language"
|
||||
#define NVS_KEY_OLED_SLEEP "oled_sleep"
|
||||
#define SCALE_DEFAULT_CALIBRATION_VALUE 430.0f;
|
||||
|
||||
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
|
||||
@@ -70,4 +71,5 @@ extern uint8_t scaleTaskCore;
|
||||
extern uint8_t scaleTaskPrio;
|
||||
|
||||
extern uint16_t defaultScaleCalibrationValue;
|
||||
extern uint16_t oledSleepTimeout;
|
||||
#endif
|
||||
@@ -5,6 +5,7 @@
|
||||
#include "main.h"
|
||||
#include <cstring>
|
||||
#include "lang.h"
|
||||
#include <Preferences.h>
|
||||
|
||||
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
|
||||
|
||||
@@ -16,6 +17,60 @@ static DisplayPriority currentPriority = DISPLAY_PRIORITY_NONE;
|
||||
static unsigned long prioritySetTime = 0;
|
||||
static unsigned long priorityMinDuration = 0;
|
||||
|
||||
// Display sleep management
|
||||
static bool oledAsleep = false;
|
||||
static unsigned long lastActivityMillis = 0;
|
||||
|
||||
void oledWake() {
|
||||
if (oledAsleep) {
|
||||
display.ssd1306_command(SSD1306_DISPLAYON);
|
||||
oledAsleep = false;
|
||||
}
|
||||
lastActivityMillis = millis();
|
||||
}
|
||||
|
||||
void oledSleep() {
|
||||
if (!oledAsleep) {
|
||||
display.ssd1306_command(SSD1306_DISPLAYOFF);
|
||||
oledAsleep = true;
|
||||
}
|
||||
}
|
||||
|
||||
void oledResetActivityTimer() {
|
||||
lastActivityMillis = millis();
|
||||
if (oledAsleep) {
|
||||
oledWake();
|
||||
}
|
||||
}
|
||||
|
||||
void oledCheckSleep() {
|
||||
if (oledSleepTimeout == 0 || oledAsleep) return;
|
||||
if (millis() - lastActivityMillis >= (unsigned long)oledSleepTimeout * 1000UL) {
|
||||
oledSleep();
|
||||
}
|
||||
}
|
||||
|
||||
bool isOledAsleep() {
|
||||
return oledAsleep;
|
||||
}
|
||||
|
||||
void loadOledSleepTimeout() {
|
||||
Preferences preferences;
|
||||
preferences.begin(NVS_NAMESPACE_SETTINGS, true);
|
||||
oledSleepTimeout = preferences.getUShort(NVS_KEY_OLED_SLEEP, 60);
|
||||
preferences.end();
|
||||
Serial.print("OLED sleep timeout loaded: ");
|
||||
Serial.println(oledSleepTimeout);
|
||||
}
|
||||
|
||||
void saveOledSleepTimeout(uint16_t timeoutSecs) {
|
||||
oledSleepTimeout = timeoutSecs;
|
||||
Preferences preferences;
|
||||
preferences.begin(NVS_NAMESPACE_SETTINGS, false);
|
||||
preferences.putUShort(NVS_KEY_OLED_SLEEP, timeoutSecs);
|
||||
preferences.end();
|
||||
}
|
||||
|
||||
bool oledCanUpdate(DisplayPriority newPriority) {
|
||||
if (currentPriority == DISPLAY_PRIORITY_NONE) return true;
|
||||
// Higher priority can always preempt
|
||||
@@ -55,6 +110,9 @@ void setupDisplay() {
|
||||
display.setTextColor(WHITE);
|
||||
display.clearDisplay();
|
||||
|
||||
// Load sleep timeout from NVS
|
||||
loadOledSleepTimeout();
|
||||
lastActivityMillis = millis();
|
||||
|
||||
oledShowTopRow();
|
||||
oledShowProgressBar(0, 7, DISPLAY_BOOT_TEXT, tr(STR_DISPLAY_INIT));
|
||||
|
||||
@@ -30,6 +30,15 @@ void oledcleardata();
|
||||
int oled_center_h(const String &text);
|
||||
int oled_center_v(const String &text);
|
||||
|
||||
// Display sleep management
|
||||
void oledWake();
|
||||
void oledSleep();
|
||||
void oledResetActivityTimer();
|
||||
void oledCheckSleep();
|
||||
bool isOledAsleep();
|
||||
void loadOledSleepTimeout();
|
||||
void saveOledSleepTimeout(uint16_t timeoutSecs);
|
||||
|
||||
void oledShowProgressBar(const uint8_t step, const uint8_t numSteps, const char* largeText, const char* statusMessage);
|
||||
|
||||
void oledShowWeight(int16_t weight);
|
||||
|
||||
+10
-2
@@ -127,6 +127,7 @@ void loop() {
|
||||
{
|
||||
lastButtonPress = currentMillis;
|
||||
scaleTareRequest = true;
|
||||
oledResetActivityTimer(); // Wake display on touch press
|
||||
}
|
||||
|
||||
// Überprüfe regelmäßig die WLAN-Verbindung
|
||||
@@ -139,8 +140,15 @@ void loop() {
|
||||
if (intervalElapsed(currentMillis, lastTopRowUpdateTime, DISPLAY_UPDATE_INTERVAL))
|
||||
{
|
||||
oledShowTopRow();
|
||||
// Clean up dead websocket clients periodically instead of on connect
|
||||
if(currentMillis % 10000 < 50) ws.cleanupClients();
|
||||
oledCheckSleep(); // Put display to sleep if timeout elapsed
|
||||
}
|
||||
|
||||
// WebSocket Cleanup alle 5 Sekunden (häufiger als vorher)
|
||||
// Tote Clients können WiFi-Ressourcen blockieren
|
||||
static unsigned long lastWsCleanup = 0;
|
||||
if (currentMillis - lastWsCleanup >= 5000) {
|
||||
ws.cleanupClients();
|
||||
lastWsCleanup = currentMillis;
|
||||
}
|
||||
|
||||
// Periodic FilaMan heartbeat
|
||||
|
||||
@@ -2050,6 +2050,9 @@ void scanRfidTask(void * parameter) {
|
||||
// Set the current tag as not processed
|
||||
tagProcessed = false;
|
||||
|
||||
// Wake display when a tag is detected
|
||||
oledResetActivityTimer();
|
||||
|
||||
// Display some basic information about the card
|
||||
Serial.println("Found an ISO14443A card");
|
||||
|
||||
|
||||
+31
-24
@@ -16,6 +16,7 @@ static int currentUpdateCommand = 0;
|
||||
static size_t updateTotalSize = 0;
|
||||
static size_t updateWritten = 0;
|
||||
static bool isSpiffsUpdate = false;
|
||||
static size_t lastYieldAt = 0; // Für WiFi-Yield während großer Uploads
|
||||
|
||||
/**
|
||||
* Compares two version strings and determines if version1 is less than version2
|
||||
@@ -64,11 +65,18 @@ void espRestart() {
|
||||
|
||||
void sendUpdateProgress(int progress, const char* status = nullptr, const char* message = nullptr) {
|
||||
static int lastSentProgress = -1;
|
||||
static unsigned long lastSendTime = 0;
|
||||
|
||||
// Verhindere zu häufige Updates
|
||||
unsigned long now = millis();
|
||||
|
||||
// Verhindere zu häufige Updates - mindestens 500ms zwischen Progress-Updates
|
||||
// Dies reduziert WebSocket-Traffic während des Uploads erheblich
|
||||
if (progress == lastSentProgress && !status && !message) {
|
||||
return;
|
||||
}
|
||||
if (now - lastSendTime < 500 && progress < 100 && !status) {
|
||||
return; // Throttle normale Progress-Updates
|
||||
}
|
||||
|
||||
String progressMsg = "{\"type\":\"updateProgress\",\"progress\":" + String(progress);
|
||||
if (status) {
|
||||
@@ -79,23 +87,13 @@ void sendUpdateProgress(int progress, const char* status = nullptr, const char*
|
||||
}
|
||||
progressMsg += "}";
|
||||
|
||||
if (progress >= 100) {
|
||||
// Sende die Nachricht nur einmal für den Abschluss
|
||||
ws.textAll("{\"type\":\"updateProgress\",\"progress\":100,\"status\":\"success\",\"message\":\"Update successful! Restarting device...\"}");
|
||||
delay(50);
|
||||
}
|
||||
|
||||
// Sende die Nachricht mehrmals mit Verzögerung für wichtige Updates
|
||||
if (status || abs(progress - lastSentProgress) >= 10 || progress == 100) {
|
||||
for (int i = 0; i < 2; i++) {
|
||||
ws.textAll(progressMsg);
|
||||
delay(100); // Längerer Delay zwischen Nachrichten
|
||||
}
|
||||
} else {
|
||||
ws.textAll(progressMsg);
|
||||
delay(50);
|
||||
}
|
||||
// Sende Progress-Update (nur einmal, nicht mehrfach)
|
||||
ws.textAll(progressMsg);
|
||||
|
||||
// Yield für WiFi-Stack nach jedem WebSocket-Send
|
||||
vTaskDelay(pdMS_TO_TICKS(10));
|
||||
|
||||
lastSendTime = now;
|
||||
lastSentProgress = progress;
|
||||
}
|
||||
|
||||
@@ -132,6 +130,7 @@ void handleUpdate(AsyncWebServer &server) {
|
||||
if (!index) {
|
||||
updateTotalSize = request->contentLength();
|
||||
updateWritten = 0;
|
||||
lastYieldAt = 0; // Reset yield counter
|
||||
isSpiffsUpdate = (filename.indexOf("website") > -1);
|
||||
|
||||
if (isSpiffsUpdate) {
|
||||
@@ -147,14 +146,14 @@ void handleUpdate(AsyncWebServer &server) {
|
||||
return;
|
||||
}
|
||||
sendUpdateProgress(5, "starting", "Starting SPIFFS update...");
|
||||
vTaskDelay(pdMS_TO_TICKS(200));
|
||||
vTaskDelay(pdMS_TO_TICKS(100));
|
||||
} else {
|
||||
if (!Update.begin(updateTotalSize)) {
|
||||
request->send(400, "application/json", "{\"success\":false,\"message\":\"Update initialization failed\"}");
|
||||
return;
|
||||
}
|
||||
sendUpdateProgress(0, "starting", "Starting firmware update...");
|
||||
vTaskDelay(pdMS_TO_TICKS(200));
|
||||
vTaskDelay(pdMS_TO_TICKS(100));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,22 +164,30 @@ void handleUpdate(AsyncWebServer &server) {
|
||||
}
|
||||
|
||||
updateWritten += len;
|
||||
|
||||
// KRITISCH: Yield alle 32KB für WiFi-Stack bei großen Uploads (1.5-2MB)
|
||||
// Ohne dies kann der WiFi-Stack blockieren und der Upload hängen bleiben
|
||||
if (updateWritten - lastYieldAt >= 32768) {
|
||||
vTaskDelay(pdMS_TO_TICKS(5)); // Kurze Pause für WiFi-Stack
|
||||
lastYieldAt = updateWritten;
|
||||
}
|
||||
|
||||
int currentProgress;
|
||||
|
||||
// Berechne den Fortschritt basierend auf dem Update-Typ
|
||||
if (isSpiffsUpdate) {
|
||||
// SPIFFS: 5-75% für Upload
|
||||
currentProgress = 6 + (updateWritten * 100) / updateTotalSize;
|
||||
// SPIFFS: 5-100% für Upload
|
||||
currentProgress = 5 + (updateWritten * 95) / updateTotalSize;
|
||||
} else {
|
||||
// Firmware: 0-100% für Upload
|
||||
currentProgress = 1 + (updateWritten * 100) / updateTotalSize;
|
||||
currentProgress = (updateWritten * 100) / updateTotalSize;
|
||||
}
|
||||
|
||||
static int lastProgress = -1;
|
||||
if (currentProgress != lastProgress && (currentProgress % 10 == 0 || final)) {
|
||||
// Nur alle 5% Progress-Updates senden (reduziert WebSocket-Traffic)
|
||||
if (currentProgress != lastProgress && (currentProgress % 5 == 0 || final)) {
|
||||
sendUpdateProgress(currentProgress, "uploading");
|
||||
oledShowProgressBar(currentProgress, 100, tr(STR_UPDATE), tr(STR_DOWNLOAD));
|
||||
vTaskDelay(pdMS_TO_TICKS(50));
|
||||
lastProgress = currentProgress;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,6 +196,7 @@ void scale_loop(void * parameter) {
|
||||
// Update global weight variable only if it changed significantly (for API actions)
|
||||
if (stabilizedWeight != weight) {
|
||||
weight = stabilizedWeight;
|
||||
oledResetActivityTimer(); // Wake display on weight change
|
||||
}
|
||||
|
||||
// Prüfen ob die Waage korrekt genullt ist
|
||||
|
||||
+59
-46
@@ -18,6 +18,7 @@
|
||||
#endif
|
||||
|
||||
#define NO_CACHE "no-cache, no-store, must-revalidate"
|
||||
#define CACHE_ASSETS "max-age=86400" // 24h Cache für statische Assets
|
||||
|
||||
AsyncWebServer server(webserverPort);
|
||||
AsyncWebSocket ws("/ws");
|
||||
@@ -25,6 +26,15 @@ AsyncWebSocket ws("/ws");
|
||||
uint8_t lastSuccess = 0;
|
||||
nfcReaderStateType lastnfcReaderState = NFC_IDLE;
|
||||
|
||||
// Template-Processor für dynamische Seiten (ESPAsyncWebServer built-in)
|
||||
// Ersetzt %variable% Platzhalter in HTML-Dateien
|
||||
String templateProcessor(const String& var) {
|
||||
if (var == "registered") return filamanRegistered ? "Registered" : "Not Registered";
|
||||
if (var == "filamanUrl") return filamanUrl;
|
||||
if (var == "autoTare") return autoTare ? "checked" : "";
|
||||
return String(); // Unbekannte Variable - leer zurückgeben
|
||||
}
|
||||
|
||||
void sendNfcDataToClient(AsyncWebSocketClient *client) {
|
||||
if(!client) return;
|
||||
switch(nfcReaderState){
|
||||
@@ -119,69 +129,47 @@ void setupWebserver(AsyncWebServer &server) {
|
||||
ws.onEvent(onWsEvent);
|
||||
server.addHandler(&ws);
|
||||
|
||||
// Static Routes
|
||||
// ===== STATISCHE ASSETS mit serveStatic() =====
|
||||
// Optimiert für concurrent Requests, mit 24h Browser-Cache
|
||||
// serveStatic() ist nicht-blockierend und handhabt parallele Requests besser
|
||||
server.serveStatic("/style.css", LittleFS, "/style.css")
|
||||
.setCacheControl(CACHE_ASSETS);
|
||||
server.serveStatic("/logo.png", LittleFS, "/logo.png")
|
||||
.setCacheControl(CACHE_ASSETS);
|
||||
server.serveStatic("/favicon.ico", LittleFS, "/favicon.ico")
|
||||
.setCacheControl(CACHE_ASSETS);
|
||||
|
||||
// ===== STATISCHE HTML-SEITEN (ohne Template-Ersetzung) =====
|
||||
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
Serial.println("Web: Request /");
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/index.html", "text/html");
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
server.on("/waage", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
Serial.println("Web: Request /waage");
|
||||
String html = readFile("/waage.html");
|
||||
html.replace("{{autoTare}}", autoTare ? "checked" : "");
|
||||
auto response = request->beginResponse(200, "text/html", html);
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
server.on("/setup", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
Serial.println("Web: Request /setup");
|
||||
String html = readFile("/setup.html");
|
||||
html.replace("{{registered}}", filamanRegistered ? "Registered" : "Not Registered");
|
||||
html.replace("{{filamanUrl}}", filamanUrl);
|
||||
auto response = request->beginResponse(200, "text/html", html);
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
request->send(LittleFS, "/index.html", "text/html");
|
||||
});
|
||||
|
||||
server.on("/wifi", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
Serial.println("Web: Request /wifi");
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/wifi.html", "text/html");
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
request->send(LittleFS, "/wifi.html", "text/html");
|
||||
});
|
||||
|
||||
server.on("/upgrade", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
Serial.println("Web: Request /upgrade");
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/upgrade.html", "text/html");
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
request->send(LittleFS, "/upgrade.html", "text/html");
|
||||
});
|
||||
|
||||
server.on("/version.txt", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/version.txt", "text/plain");
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
request->send(LittleFS, "/version.txt", "text/plain");
|
||||
});
|
||||
|
||||
server.on("/style.css", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/style.css", "text/css");
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
// ===== DYNAMISCHE HTML-SEITEN (mit Template-Processor) =====
|
||||
// Nutzt den eingebauten Template-Processor für %variable% Ersetzung
|
||||
// Nicht-blockierend: Datei wird gestreamt und Variablen on-the-fly ersetzt
|
||||
server.on("/waage", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
Serial.println("Web: Request /waage");
|
||||
request->send(LittleFS, "/waage.html", "text/html", false, templateProcessor);
|
||||
});
|
||||
|
||||
server.on("/logo.png", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/logo.png", "image/png");
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
server.on("/favicon.ico", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/favicon.ico", "image/x-icon");
|
||||
response->addHeader("Cache-Control", NO_CACHE);
|
||||
request->send(response);
|
||||
server.on("/setup", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
Serial.println("Web: Request /setup");
|
||||
request->send(LittleFS, "/setup.html", "text/html", false, templateProcessor);
|
||||
});
|
||||
|
||||
// API Routes
|
||||
@@ -272,6 +260,31 @@ void setupWebserver(AsyncWebServer &server) {
|
||||
request->send(200, "application/json", "{\"success\": true}");
|
||||
});
|
||||
|
||||
// Display Settings API
|
||||
server.on("/api/display", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
JsonDocument doc;
|
||||
doc["sleepTimeout"] = oledSleepTimeout;
|
||||
String response;
|
||||
serializeJson(doc, response);
|
||||
request->send(200, "application/json", response);
|
||||
});
|
||||
|
||||
server.on("/api/display", HTTP_POST, [](AsyncWebServerRequest *request){}, NULL, [](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total){
|
||||
JsonDocument doc;
|
||||
DeserializationError error = deserializeJson(doc, (const uint8_t*)data, len);
|
||||
if (error) {
|
||||
request->send(400, "application/json", "{\"success\": false, \"error\": \"Invalid JSON\"}");
|
||||
return;
|
||||
}
|
||||
if (!doc["sleepTimeout"].is<int>()) {
|
||||
request->send(400, "application/json", "{\"success\": false, \"error\": \"Missing sleepTimeout\"}");
|
||||
return;
|
||||
}
|
||||
uint16_t timeout = (uint16_t)constrain((int)doc["sleepTimeout"], 0, 3600);
|
||||
saveOledSleepTimeout(timeout);
|
||||
request->send(200, "application/json", "{\"success\": true}");
|
||||
});
|
||||
|
||||
server.on("/reboot", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
request->send(200, "text/plain", "Rebooting...");
|
||||
delay(500);
|
||||
|
||||
+14
-8
@@ -17,15 +17,15 @@ void wifiSettings() {
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.setHostname("FilaMan");
|
||||
|
||||
// Wir lassen das Power Management (Sleep) auf dem ESP-Standard.
|
||||
// Ein erzwungenes Ausschalten führt zu RF-Abstürzen bei vielen asynchronen HTTP-Requests.
|
||||
// KRITISCH: Power-Save deaktivieren für stabilen Webserver-Betrieb
|
||||
// Ohne dies geht WiFi in Modem-Sleep und verpasst Requests/Responses
|
||||
// Dies ist die Hauptursache für Verbindungsabbrüche bei regelmäßigen API-Calls
|
||||
esp_wifi_set_ps(WIFI_PS_NONE);
|
||||
|
||||
// Angemessene Sendeleistung (reduziert Hitzeprobleme)
|
||||
WiFi.setTxPower(WIFI_POWER_17dBm); // Set stable transmit power (default is 19.5 which gets hot)
|
||||
|
||||
// Wir überlassen die Protokoll-Aushandlung (b/g/n) dem Treiber. Harte Vorgaben crashen unter Last.
|
||||
WiFi.setTxPower(WIFI_POWER_17dBm);
|
||||
|
||||
// Aktiviere WiFi-Roaming für bessere Stabilität
|
||||
// Aktiviere WiFi-Roaming für bessere Stabilität bei schwachem Signal
|
||||
esp_wifi_set_rssi_threshold(-80);
|
||||
}
|
||||
|
||||
@@ -76,10 +76,13 @@ void checkWiFiConnection() {
|
||||
if (WiFi.status() != WL_CONNECTED)
|
||||
{
|
||||
if (wifiOn) {
|
||||
Serial.println("WiFi connection lost. LwIP is auto-reconnecting...");
|
||||
Serial.println("WiFi connection lost. Attempting active reconnect...");
|
||||
wifiOn = false;
|
||||
oledShowTopRow();
|
||||
oledDisplayText(tr(STR_WIFI_RECONNECTING));
|
||||
|
||||
// Aktiver Reconnect-Versuch statt nur auf LwIP auto-reconnect zu warten
|
||||
WiFi.reconnect();
|
||||
}
|
||||
|
||||
wifiErrorCounter++;
|
||||
@@ -95,10 +98,13 @@ void checkWiFiConnection() {
|
||||
else
|
||||
{
|
||||
if (!wifiOn) {
|
||||
Serial.println("WiFi reconnected.");
|
||||
Serial.println("WiFi reconnected successfully.");
|
||||
wifiErrorCounter = 0;
|
||||
wifiOn = true;
|
||||
oledShowTopRow();
|
||||
|
||||
// Power-Save erneut deaktivieren nach Reconnect (wird manchmal zurückgesetzt)
|
||||
esp_wifi_set_ps(WIFI_PS_NONE);
|
||||
} else {
|
||||
// Reset error counter if we are connected (just to be safe)
|
||||
wifiErrorCounter = 0;
|
||||
|
||||
Reference in new issue
Block a user