fix: handle critical bug

Avoid making it get stuck in the main loop
This commit is contained in:
2025-08-14 20:07:06 +02:00
committed by GitHub
parent 32b136d4cc
commit 48f7065a9a

View File

@@ -23,7 +23,6 @@ uint64_t sleepDuration = 30e6; // Default 30 seconds in microseconds
#define EPD_HEIGHT EPD_7IN5B_V2_HEIGHT #define EPD_HEIGHT EPD_7IN5B_V2_HEIGHT
// =========== IMAGE TUNING PARAMETERS =========== // =========== IMAGE TUNING PARAMETERS ===========
// These will be updated from the configuration
uint8_t blackTextThreshold = 190; // Default (0-255) uint8_t blackTextThreshold = 190; // Default (0-255)
bool enableDithering = true; // Default bool enableDithering = true; // Default
uint8_t ditherStrength = 8; // Default (8-32) uint8_t ditherStrength = 8; // Default (8-32)
@@ -42,13 +41,51 @@ int16_t *errorB = NULL;
// Create an instance of the JPEG decoder // Create an instance of the JPEG decoder
JPEGDEC jpeg; JPEGDEC jpeg;
// Forward declarations
bool fetchConnectionInformation();
void fetchAndDisplayImage();
void clearDisplay();
// Centralized cleanup + deep sleep
void finishAndSleep(const char* reason) {
Serial.println();
Serial.println("========== Going to deep sleep ==========");
if (reason && reason[0]) {
Serial.print("Reason: ");
Serial.println(reason);
}
// Free dithering buffers if allocated
if (errorR) { free(errorR); errorR = NULL; }
if (errorG) { free(errorG); errorG = NULL; }
if (errorB) { free(errorB); errorB = NULL; }
// Put display to sleep (safe to call even if already sleeping)
EPD_7IN5B_V2_Sleep();
// Free framebuffers
if (BlackImage) { free(BlackImage); BlackImage = NULL; }
if (RYImage) { free(RYImage); RYImage = NULL; }
// Tidy up WiFi to save power before deep sleep
WiFi.disconnect(true, true);
WiFi.mode(WIFI_OFF);
delay(50);
Serial.print("Sleeping for ");
Serial.print(sleepDuration / 60000000);
Serial.println(" minutes");
esp_sleep_enable_timer_wakeup(sleepDuration);
esp_deep_sleep_start();
}
// Apply contrast adjustment to RGB values // Apply contrast adjustment to RGB values
void adjustContrast(uint8_t *r, uint8_t *g, uint8_t *b) { void adjustContrast(uint8_t *r, uint8_t *g, uint8_t *b) {
if (!enhanceContrast) return; if (!enhanceContrast) return;
float contrast = (contrastLevel / 100.0) + 1.0; // Convert to decimal & shift range: [0..2] float contrast = (contrastLevel / 100.0) + 1.0; // [1..2]
float intercept = 128 * (1 - contrast); float intercept = 128 * (1 - contrast);
*r = constrain((*r * contrast) + intercept, 0, 255); *r = constrain((*r * contrast) + intercept, 0, 255);
*g = constrain((*g * contrast) + intercept, 0, 255); *g = constrain((*g * contrast) + intercept, 0, 255);
*b = constrain((*b * contrast) + intercept, 0, 255); *b = constrain((*b * contrast) + intercept, 0, 255);
@@ -62,13 +99,13 @@ int jpegDrawCallback(JPEGDRAW *pDraw) {
int y = pDraw->y; int y = pDraw->y;
int width = pDraw->iWidth; int width = pDraw->iWidth;
int height = pDraw->iHeight; int height = pDraw->iHeight;
// Initialize error buffers for dithering if needed // Initialize error buffers for dithering if needed
if (enableDithering && errorR == NULL) { if (enableDithering && errorR == NULL) {
errorR = (int16_t*)malloc(EPD_WIDTH * sizeof(int16_t)); errorR = (int16_t*)malloc(EPD_WIDTH * sizeof(int16_t));
errorG = (int16_t*)malloc(EPD_WIDTH * sizeof(int16_t)); errorG = (int16_t*)malloc(EPD_WIDTH * sizeof(int16_t));
errorB = (int16_t*)malloc(EPD_WIDTH * sizeof(int16_t)); errorB = (int16_t*)malloc(EPD_WIDTH * sizeof(int16_t));
if (errorR && errorG && errorB) { if (errorR && errorG && errorB) {
memset(errorR, 0, EPD_WIDTH * sizeof(int16_t)); memset(errorR, 0, EPD_WIDTH * sizeof(int16_t));
memset(errorG, 0, EPD_WIDTH * sizeof(int16_t)); memset(errorG, 0, EPD_WIDTH * sizeof(int16_t));
@@ -81,7 +118,7 @@ int jpegDrawCallback(JPEGDRAW *pDraw) {
errorR = errorG = errorB = NULL; errorR = errorG = errorB = NULL;
} }
} }
// Process each row in this MCU block // Process each row in this MCU block
for (int iy = 0; iy < height; iy++) { for (int iy = 0; iy < height; iy++) {
// Reset error buffers for each row // Reset error buffers for each row
@@ -90,45 +127,45 @@ int jpegDrawCallback(JPEGDRAW *pDraw) {
memset(errorG, 0, EPD_WIDTH * sizeof(int16_t)); memset(errorG, 0, EPD_WIDTH * sizeof(int16_t));
memset(errorB, 0, EPD_WIDTH * sizeof(int16_t)); memset(errorB, 0, EPD_WIDTH * sizeof(int16_t));
} }
// Process each pixel in the row // Process each pixel in the row
for (int ix = 0; ix < width; ix++) { for (int ix = 0; ix < width; ix++) {
int pos_x = x + ix; int pos_x = x + ix;
int pos_y = y + iy; int pos_y = y + iy;
// Skip if outside display bounds // Skip if outside display bounds
if (pos_x >= EPD_WIDTH || pos_y >= EPD_HEIGHT) continue; if (pos_x >= EPD_WIDTH || pos_y >= EPD_HEIGHT) continue;
// Get the 16-bit pixel value (RGB565) // Get the 16-bit pixel value (RGB565)
uint16_t pixel = pPixels[iy * width + ix]; uint16_t pixel = pPixels[iy * width + ix];
// Extract RGB components (565 format) and convert to 0-255 range // Extract RGB components (565 format) and convert to 0-255 range
uint8_t r = ((pixel >> 11) & 0x1F) << 3; uint8_t r = ((pixel >> 11) & 0x1F) << 3;
uint8_t g = ((pixel >> 5) & 0x3F) << 2; uint8_t g = ((pixel >> 5) & 0x3F) << 2;
uint8_t b = (pixel & 0x1F) << 3; uint8_t b = (pixel & 0x1F) << 3;
// Apply contrast adjustment if enabled // Apply contrast adjustment if enabled
if (enhanceContrast) { if (enhanceContrast) {
adjustContrast(&r, &g, &b); adjustContrast(&r, &g, &b);
} }
// Apply dithering errors if enabled // Apply dithering errors if enabled
if (enableDithering && errorR != NULL) { if (enableDithering && errorR != NULL) {
r = constrain(r + (errorR[pos_x] / ditherStrength), 0, 255); r = constrain(r + (errorR[pos_x] / ditherStrength), 0, 255);
g = constrain(g + (errorG[pos_x] / ditherStrength), 0, 255); g = constrain(g + (errorG[pos_x] / ditherStrength), 0, 255);
b = constrain(b + (errorB[pos_x] / ditherStrength), 0, 255); b = constrain(b + (errorB[pos_x] / ditherStrength), 0, 255);
} }
// Calculate grayscale value // Calculate grayscale value
float gray = (r * 0.299 + g * 0.587 + b * 0.114); float gray = (r * 0.299 + g * 0.587 + b * 0.114);
// ===== IMPROVED COLOR CLASSIFICATION LOGIC ===== // ===== IMPROVED COLOR CLASSIFICATION LOGIC =====
// Variable for final color (0=black, 1=white, 2=red) // Variable for final color (0=black, 1=white, 2=red)
int finalColor; int finalColor;
// Check for "redness" - how much stronger red is than other components // Check for "redness" - how much stronger red is than other components
float redness = r / (float)(g + b + 1); // Add 1 to avoid division by zero float redness = r / (float)(g + b + 1); // Add 1 to avoid division by zero
// Check if this is likely a red pixel based on redness // Check if this is likely a red pixel based on redness
if (r > 100 && redness > 1.5) { if (r > 100 && redness > 1.5) {
finalColor = 2; // Red finalColor = 2; // Red
@@ -140,10 +177,10 @@ int jpegDrawCallback(JPEGDRAW *pDraw) {
else { else {
finalColor = 1; // White finalColor = 1; // White
} }
// Determine target colors for error calculation // Determine target colors for error calculation
uint8_t targetR, targetG, targetB; uint8_t targetR, targetG, targetB;
switch (finalColor) { switch (finalColor) {
case 0: // Black case 0: // Black
targetR = targetG = targetB = 0; targetR = targetG = targetB = 0;
@@ -156,13 +193,13 @@ int jpegDrawCallback(JPEGDRAW *pDraw) {
targetR = targetG = targetB = 255; targetR = targetG = targetB = 255;
break; break;
} }
// Calculate and distribute dithering errors // Calculate and distribute dithering errors
if (enableDithering && errorR != NULL) { if (enableDithering && errorR != NULL) {
int16_t err_r = r - targetR; int16_t err_r = r - targetR;
int16_t err_g = g - targetG; int16_t err_g = g - targetG;
int16_t err_b = b - targetB; int16_t err_b = b - targetB;
// Floyd-Steinberg dithering pattern // Floyd-Steinberg dithering pattern
if (pos_x + 1 < EPD_WIDTH) { if (pos_x + 1 < EPD_WIDTH) {
// Right pixel (7/16) // Right pixel (7/16)
@@ -170,22 +207,22 @@ int jpegDrawCallback(JPEGDRAW *pDraw) {
errorG[pos_x + 1] += (err_g * 7) >> 4; errorG[pos_x + 1] += (err_g * 7) >> 4;
errorB[pos_x + 1] += (err_b * 7) >> 4; errorB[pos_x + 1] += (err_b * 7) >> 4;
} }
if (pos_x > 0 && pos_x + 1 < EPD_WIDTH) { if (pos_x > 0 && pos_x + 1 < EPD_WIDTH) {
errorR[pos_x - 1] += (err_r * 3) >> 4; // left-down (3/16) errorR[pos_x - 1] += (err_r * 3) >> 4; // left-down (3/16)
errorG[pos_x - 1] += (err_g * 3) >> 4; errorG[pos_x - 1] += (err_g * 3) >> 4;
errorB[pos_x - 1] += (err_b * 3) >> 4; errorB[pos_x - 1] += (err_b * 3) >> 4;
errorR[pos_x] += (err_r * 5) >> 4; // down (5/16) errorR[pos_x] += (err_r * 5) >> 4; // down (5/16)
errorG[pos_x] += (err_g * 5) >> 4; errorG[pos_x] += (err_g * 5) >> 4;
errorB[pos_x] += (err_b * 5) >> 4; errorB[pos_x] += (err_b * 5) >> 4;
errorR[pos_x + 1] += (err_r * 1) >> 4; // right-down (1/16) errorR[pos_x + 1] += (err_r * 1) >> 4; // right-down (1/16)
errorG[pos_x + 1] += (err_g * 1) >> 4; errorG[pos_x + 1] += (err_g * 1) >> 4;
errorB[pos_x + 1] += (err_b * 1) >> 4; errorB[pos_x + 1] += (err_b * 1) >> 4;
} }
} }
// Draw the pixel based on the final color // Draw the pixel based on the final color
switch (finalColor) { switch (finalColor) {
case 0: // Black case 0: // Black
@@ -194,14 +231,14 @@ int jpegDrawCallback(JPEGDRAW *pDraw) {
Paint_SelectImage(RYImage); Paint_SelectImage(RYImage);
Paint_SetPixel(pos_x, pos_y, WHITE); Paint_SetPixel(pos_x, pos_y, WHITE);
break; break;
case 2: // Red case 2: // Red
Paint_SelectImage(BlackImage); Paint_SelectImage(BlackImage);
Paint_SetPixel(pos_x, pos_y, WHITE); Paint_SetPixel(pos_x, pos_y, WHITE);
Paint_SelectImage(RYImage); Paint_SelectImage(RYImage);
Paint_SetPixel(pos_x, pos_y, BLACK); // BLACK in RY buffer = RED Paint_SetPixel(pos_x, pos_y, BLACK); // BLACK in RY buffer = RED
break; break;
default: // White default: // White
Paint_SelectImage(BlackImage); Paint_SelectImage(BlackImage);
Paint_SetPixel(pos_x, pos_y, WHITE); Paint_SetPixel(pos_x, pos_y, WHITE);
@@ -211,7 +248,7 @@ int jpegDrawCallback(JPEGDRAW *pDraw) {
} }
} }
} }
return 1; // Continue decoding return 1; // Continue decoding
} }
@@ -221,7 +258,7 @@ void clearDisplay() {
Paint_Clear(WHITE); Paint_Clear(WHITE);
Paint_SelectImage(RYImage); Paint_SelectImage(RYImage);
Paint_Clear(WHITE); Paint_Clear(WHITE);
// Send clear command to the display // Send clear command to the display
EPD_7IN5B_V2_Display(BlackImage, RYImage); EPD_7IN5B_V2_Display(BlackImage, RYImage);
Serial.println("Display cleared."); Serial.println("Display cleared.");
@@ -230,19 +267,20 @@ void clearDisplay() {
void setup() { void setup() {
Serial.begin(115200); Serial.begin(115200);
Serial.println("E-Ink Display Initialization"); Serial.println("E-Ink Display Initialization");
// Calculate buffer size as in Waveshare example // Calculate buffer size as in Waveshare example
UWORD Imagesize = ((EPD_WIDTH % 8 == 0) ? (EPD_WIDTH / 8) : (EPD_WIDTH / 8 + 1)) * EPD_HEIGHT; UWORD Imagesize = ((EPD_WIDTH % 8 == 0) ? (EPD_WIDTH / 8) : (EPD_WIDTH / 8 + 1)) * EPD_HEIGHT;
// Allocate framebuffers // Allocate framebuffers
BlackImage = (UBYTE *)malloc(Imagesize); BlackImage = (UBYTE *)malloc(Imagesize);
RYImage = (UBYTE *)malloc(Imagesize); RYImage = (UBYTE *)malloc(Imagesize);
if ((BlackImage == NULL) || (RYImage == NULL)) { if ((BlackImage == NULL) || (RYImage == NULL)) {
Serial.println("Failed to allocate memory for framebuffers!"); Serial.println("Failed to allocate memory for framebuffers!");
while(1); // Halt if memory allocation fails // Even on failure, deep-sleep to allow recovery on next boot
finishAndSleep("Framebuffer allocation failed");
} }
// Initialize e-ink display exactly as in Waveshare example // Initialize e-ink display exactly as in Waveshare example
DEV_Module_Init(); DEV_Module_Init();
EPD_7IN5B_V2_Init(); EPD_7IN5B_V2_Init();
@@ -252,10 +290,11 @@ void setup() {
// Initialize the Paint library with the buffers // Initialize the Paint library with the buffers
Paint_NewImage(BlackImage, EPD_WIDTH, EPD_HEIGHT, 0, WHITE); Paint_NewImage(BlackImage, EPD_WIDTH, EPD_HEIGHT, 0, WHITE);
Paint_NewImage(RYImage, EPD_WIDTH, EPD_HEIGHT, 0, WHITE); Paint_NewImage(RYImage, EPD_WIDTH, EPD_HEIGHT, 0, WHITE);
Serial.println("Buffers allocated and cleared"); Serial.println("Buffers allocated and cleared");
// Connect to WiFi // Connect to WiFi
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password); WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi"); Serial.print("Connecting to WiFi");
int wifiAttempts = 0; int wifiAttempts = 0;
@@ -264,7 +303,7 @@ void setup() {
Serial.print("."); Serial.print(".");
wifiAttempts++; wifiAttempts++;
} }
if (WiFi.status() == WL_CONNECTED) { if (WiFi.status() == WL_CONNECTED) {
Serial.println(); Serial.println();
Serial.println("WiFi connected"); Serial.println("WiFi connected");
@@ -273,7 +312,8 @@ void setup() {
} else { } else {
Serial.println(); Serial.println();
Serial.println("WiFi connection failed!"); Serial.println("WiFi connection failed!");
return; // IMPORTANT: Do not just return; always deep sleep so we retry later
finishAndSleep("WiFi connection failed");
} }
// Test connectivity to server and get configuration // Test connectivity to server and get configuration
@@ -285,67 +325,48 @@ void setup() {
Serial.println("Server connectivity test failed - skipping image fetch"); Serial.println("Server connectivity test failed - skipping image fetch");
} }
// Free dithering buffers if allocated // Always finish with cleanup and deep sleep (success or failure)
if (errorR) free(errorR); finishAndSleep("Normal cycle complete");
if (errorG) free(errorG);
if (errorB) free(errorB);
errorR = errorG = errorB = NULL;
// Put display to sleep
EPD_7IN5B_V2_Sleep();
// Free framebuffers
free(BlackImage);
free(RYImage);
BlackImage = NULL;
RYImage = NULL;
// Enter deep sleep
Serial.print("Going to sleep for ");
Serial.print(sleepDuration / 60000000);
Serial.println(" minutes");
esp_sleep_enable_timer_wakeup(sleepDuration);
esp_deep_sleep_start();
} }
bool fetchConnectionInformation() { bool fetchConnectionInformation() {
HTTPClient http; HTTPClient http;
http.begin(connectionInformation); http.begin(connectionInformation);
http.setTimeout(10000); http.setTimeout(10000);
int httpCode = http.GET(); int httpCode = http.GET();
Serial.print("HTTP response code: "); Serial.print("HTTP response code: ");
Serial.println(httpCode); Serial.println(httpCode);
// Handle the response payload // Handle the response payload
String payload = ""; String payload = "";
if (httpCode == HTTP_CODE_OK) { if (httpCode == HTTP_CODE_OK) {
payload = http.getString(); payload = http.getString();
// Debug output to show the exact response // Debug output to show the exact response
Serial.println("-----RAW HTTP RESPONSE BEGIN-----"); Serial.println("-----RAW HTTP RESPONSE BEGIN-----");
Serial.println(payload); Serial.println(payload);
Serial.println("-----RAW HTTP RESPONSE END-----"); Serial.println("-----RAW HTTP RESPONSE END-----");
// Check if payload is empty // Check if payload is empty
if (payload.length() == 0) { if (payload.length() == 0) {
Serial.println("Warning: Server returned empty response"); Serial.println("Warning: Server returned empty response");
http.end(); http.end();
return false; return false;
} }
// Try to find JSON content in the response // Try to find JSON content in the response
int jsonStart = payload.indexOf('{'); int jsonStart = payload.indexOf('{');
int jsonEnd = payload.lastIndexOf('}'); int jsonEnd = payload.lastIndexOf('}');
if (jsonStart >= 0 && jsonEnd >= 0 && jsonEnd > jsonStart) { if (jsonStart >= 0 && jsonEnd >= 0 && jsonEnd > jsonStart) {
String jsonPayload = payload.substring(jsonStart, jsonEnd + 1); String jsonPayload = payload.substring(jsonStart, jsonEnd + 1);
Serial.println("-----EXTRACTED JSON BEGIN-----"); Serial.println("-----EXTRACTED JSON BEGIN-----");
Serial.println(jsonPayload); Serial.println(jsonPayload);
Serial.println("-----EXTRACTED JSON END-----"); Serial.println("-----EXTRACTED JSON END-----");
// Deserialize the JSON document - Increased buffer size for more parameters // Deserialize the JSON document - Increased buffer size for more parameters
StaticJsonDocument<768> doc; StaticJsonDocument<768> doc;
DeserializationError error = deserializeJson(doc, jsonPayload); DeserializationError error = deserializeJson(doc, jsonPayload);
@@ -355,7 +376,7 @@ bool fetchConnectionInformation() {
http.end(); http.end();
return false; return false;
} }
// Extract values from the JSON // Extract values from the JSON
if (doc.containsKey("informationBoardImageUrl")) { if (doc.containsKey("informationBoardImageUrl")) {
imageUrl = doc["informationBoardImageUrl"].as<String>(); imageUrl = doc["informationBoardImageUrl"].as<String>();
@@ -366,7 +387,7 @@ bool fetchConnectionInformation() {
http.end(); http.end();
return false; return false;
} }
if (doc.containsKey("updateIntervalMinutes")) { if (doc.containsKey("updateIntervalMinutes")) {
int minutes = doc["updateIntervalMinutes"].as<int>(); int minutes = doc["updateIntervalMinutes"].as<int>();
sleepDuration = (uint64_t)minutes * 60 * 1000000; // Convert minutes to microseconds sleepDuration = (uint64_t)minutes * 60 * 1000000; // Convert minutes to microseconds
@@ -377,38 +398,38 @@ bool fetchConnectionInformation() {
Serial.println("Warning: updateIntervalMinutes not found in JSON"); Serial.println("Warning: updateIntervalMinutes not found in JSON");
// Keep default sleep duration // Keep default sleep duration
} }
// Extract new image processing parameters // Extract new image processing parameters
if (doc.containsKey("blackTextThreshold")) { if (doc.containsKey("blackTextThreshold")) {
blackTextThreshold = doc["blackTextThreshold"].as<uint8_t>(); blackTextThreshold = doc["blackTextThreshold"].as<uint8_t>();
Serial.print("Black text threshold set to: "); Serial.print("Black text threshold set to: ");
Serial.println(blackTextThreshold); Serial.println(blackTextThreshold);
} }
if (doc.containsKey("enableDithering")) { if (doc.containsKey("enableDithering")) {
enableDithering = doc["enableDithering"].as<bool>(); enableDithering = doc["enableDithering"].as<bool>();
Serial.print("Dithering enabled: "); Serial.print("Dithering enabled: ");
Serial.println(enableDithering ? "true" : "false"); Serial.println(enableDithering ? "true" : "false");
} }
if (doc.containsKey("ditheringStrength")) { if (doc.containsKey("ditheringStrength")) {
ditherStrength = doc["ditheringStrength"].as<uint8_t>(); ditherStrength = doc["ditheringStrength"].as<uint8_t>();
Serial.print("Dithering strength set to: "); Serial.print("Dithering strength set to: ");
Serial.println(ditherStrength); Serial.println(ditherStrength);
} }
if (doc.containsKey("enhanceContrast")) { if (doc.containsKey("enhanceContrast")) {
enhanceContrast = doc["enhanceContrast"].as<bool>(); enhanceContrast = doc["enhanceContrast"].as<bool>();
Serial.print("Contrast enhancement enabled: "); Serial.print("Contrast enhancement enabled: ");
Serial.println(enhanceContrast ? "true" : "false"); Serial.println(enhanceContrast ? "true" : "false");
} }
if (doc.containsKey("contrastStrength")) { if (doc.containsKey("contrastStrength")) {
contrastLevel = doc["contrastStrength"].as<uint8_t>(); contrastLevel = doc["contrastStrength"].as<uint8_t>();
Serial.print("Contrast level set to: "); Serial.print("Contrast level set to: ");
Serial.println(contrastLevel); Serial.println(contrastLevel);
} }
http.end(); http.end();
return true; return true;
} else { } else {
@@ -430,51 +451,51 @@ void fetchAndDisplayImage() {
Serial.println("WiFi not connected, cannot fetch image"); Serial.println("WiFi not connected, cannot fetch image");
return; return;
} }
if (imageUrl.length() == 0) { if (imageUrl.length() == 0) {
Serial.println("Image URL not set, cannot fetch image"); Serial.println("Image URL not set, cannot fetch image");
return; return;
} }
HTTPClient http; HTTPClient http;
http.begin(imageUrl); http.begin(imageUrl);
http.setTimeout(30000); // Set 30 second timeout http.setTimeout(30000); // Set 30 second timeout
http.addHeader("User-Agent", "ESP32"); http.addHeader("User-Agent", "ESP32");
Serial.print("Starting HTTP GET for image: "); Serial.print("Starting HTTP GET for image: ");
Serial.println(imageUrl); Serial.println(imageUrl);
int httpCode = http.GET(); int httpCode = http.GET();
Serial.print("HTTP response code: "); Serial.print("HTTP response code: ");
Serial.println(httpCode); Serial.println(httpCode);
if (httpCode == HTTP_CODE_OK) { if (httpCode == HTTP_CODE_OK) {
int len = http.getSize(); int len = http.getSize();
Serial.print("Content length: "); Serial.print("Content length: ");
Serial.println(len); Serial.println(len);
if (len > 0) { if (len > 0) {
Serial.print("Free heap before allocation: "); Serial.print("Free heap before allocation: ");
Serial.println(ESP.getFreeHeap()); Serial.println(ESP.getFreeHeap());
// Check if we have enough memory // Check if we have enough memory
if (ESP.getFreeHeap() < len + 10000) { // Keep 10KB buffer if (ESP.getFreeHeap() < len + 10000) { // Keep 10KB buffer
Serial.println("Not enough memory to load image"); Serial.println("Not enough memory to load image");
http.end(); http.end();
return; return;
} }
uint8_t *buffer = (uint8_t*)malloc(len); uint8_t *buffer = (uint8_t*)malloc(len);
if (buffer) { if (buffer) {
Serial.print("Allocated "); Serial.print("Allocated ");
Serial.print(len); Serial.print(len);
Serial.println(" bytes for image buffer."); Serial.println(" bytes for image buffer.");
// Clear both buffers before processing new image - USING PAINT LIBRARY // Clear both buffers before processing new image - USING PAINT LIBRARY
Paint_SelectImage(BlackImage); Paint_SelectImage(BlackImage);
Paint_Clear(WHITE); Paint_Clear(WHITE);
Paint_SelectImage(RYImage); Paint_SelectImage(RYImage);
Paint_Clear(WHITE); Paint_Clear(WHITE);
WiFiClient *stream = http.getStreamPtr(); WiFiClient *stream = http.getStreamPtr();
int totalBytesRead = 0; int totalBytesRead = 0;
unsigned long timeout = millis() + 30000; // 30 second timeout for reading unsigned long timeout = millis() + 30000; // 30 second timeout for reading
@@ -491,14 +512,15 @@ void fetchAndDisplayImage() {
} else { } else {
totalBytesRead += bytesRead; totalBytesRead += bytesRead;
} }
yield(); // keep WiFi stack happy
} }
Serial.print("Total bytes read: "); Serial.print("Total bytes read: ");
Serial.println(totalBytesRead); Serial.println(totalBytesRead);
if (totalBytesRead == len) { if (totalBytesRead == len) {
// Process and display the image using JPEGDEC // Process and display the image using JPEGDEC
Serial.println("Decoding JPEG image..."); Serial.println("Decoding JPEG image...");
// Open JPEG image from memory // Open JPEG image from memory
if (jpeg.openRAM(buffer, len, jpegDrawCallback)) { if (jpeg.openRAM(buffer, len, jpegDrawCallback)) {
// Get information about the image // Get information about the image
@@ -508,17 +530,17 @@ void fetchAndDisplayImage() {
Serial.print(jpegWidth); Serial.print(jpegWidth);
Serial.print(" x "); Serial.print(" x ");
Serial.println(jpegHeight); Serial.println(jpegHeight);
// Decode the image // Decode the image
if (jpeg.decode(0, 0, 0)) { if (jpeg.decode(0, 0, 0)) {
Serial.println("JPEG image decoded successfully"); Serial.println("JPEG image decoded successfully");
} else { } else {
Serial.println("Error decoding JPEG image"); Serial.println("Error decoding JPEG image");
} }
// Close the file // Close the file
jpeg.close(); jpeg.close();
// Display the processed image - using Waveshare's function // Display the processed image - using Waveshare's function
Serial.println("Sending image to display..."); Serial.println("Sending image to display...");
EPD_7IN5B_V2_Display(BlackImage, RYImage); EPD_7IN5B_V2_Display(BlackImage, RYImage);
@@ -556,7 +578,7 @@ void fetchAndDisplayImage() {
Serial.printf("HTTP GET failed, error: %d\n", httpCode); Serial.printf("HTTP GET failed, error: %d\n", httpCode);
clearDisplay(); clearDisplay();
} }
http.end(); http.end();
} }