Fix 8 bugs: SD 1-bit mode GPIO conflict, PNG file handle leak, audio stack overflow, null terminator, error degradation logic, modulo div-by-zero, upload file validation, screen clear before PNG draw. Improve web UI with progress bar and toast feedback.

This commit is contained in:
drjones
2026-07-02 21:54:57 -07:00
parent bac1af80fe
commit 7a9d971310
5 changed files with 244 additions and 77 deletions

View File

@@ -29,7 +29,7 @@ void initAudioPlayer() {
xTaskCreatePinnedToCore(
audioLoopTask,
"audioLoopTask",
8192, // Stack size (ESP32-audioI2S requires a larger stack size for decoding)
16384, // Increased from 8192 — ESP32-audioI2S MP3 decode needs ~12-16KB stack
NULL,
5, // Priority
&audioTaskHandle,
@@ -66,6 +66,14 @@ uint8_t getPlayerVolume() {
return currentVolume;
}
// Case-insensitive check if filename ends with a given extension
static bool hasExtension(const char* name, const char* ext) {
size_t nLen = strlen(name);
size_t eLen = strlen(ext);
if (nLen < eLen) return false;
return strcasecmp(name + nLen - eLen, ext) == 0;
}
void Search_Audio(const char* directory) {
File Path = SD_MMC.open(directory);
if (!Path) {
@@ -79,8 +87,8 @@ void Search_Audio(const char* directory) {
while (file && fileCount < 100) {
if (!file.isDirectory()) {
const char* name = file.name();
// Match WAV or MP3 files
if (strstr(name, ".wav") || strstr(name, ".mp3") || strstr(name, ".WAV") || strstr(name, ".MP3")) {
// Case-insensitive extension match to handle FAT32 uppercase names
if (hasExtension(name, ".wav") || hasExtension(name, ".mp3")) {
strncpy(Audio_Names[fileCount], name, sizeof(Audio_Names[fileCount]) - 1);
Audio_Names[fileCount][sizeof(Audio_Names[fileCount]) - 1] = '\0';
fileCount++;

View File

@@ -16,8 +16,8 @@ void * pngOpen(const char *filePath, int32_t *size) {
}
void pngClose(void *handle) {
File Image_file = *((File*)handle);
if (Image_file) Image_file.close();
File* fp = (File*)handle;
if (fp && *fp) fp->close();
}
int32_t pngRead(PNGFILE *page, uint8_t *buffer, int32_t length) {
@@ -44,6 +44,15 @@ void Search_Images(const char* directory) {
Image_Count = Folder_retrieval(directory, ".png", Image_Names, 100);
}
// Fill entire screen with black before drawing a new image
static void clearScreen() {
static uint16_t blackLine[MAX_IMAGE_WIDTH];
memset(blackLine, 0, sizeof(blackLine));
for (int y = 0; y < LCD_HEIGHT; y++) {
LCD_addWindow(0, y, LCD_WIDTH - 1, y, blackLine);
}
}
void Display_Image_By_Path(const char* filePath) {
printf("Displaying image: %s\r\n", filePath);
int16_t ret = png.open(filePath, pngOpen, pngClose, pngRead, pngSeek, pngDraw);
@@ -52,6 +61,7 @@ void Display_Image_By_Path(const char* filePath) {
if (png.getWidth() > MAX_IMAGE_WIDTH) {
printf("Image is too wide for line buffer!\r\n");
} else {
clearScreen(); // Clear leftovers from previous smaller image
ret = png.decode(NULL, 0);
png.close();
}

View File

@@ -7,11 +7,11 @@ uint16_t SDCard_Size;
uint16_t Flash_Size;
void SD_Init() {
if(!SD_MMC.setPins(SD_CLK_PIN, SD_CMD_PIN, SD_D0_PIN, SD_D1_PIN, SD_D2_PIN, SD_D3_PIN)){
if(!SD_MMC.setPins(SD_CLK_PIN, SD_CMD_PIN, SD_D0_PIN)){
printf("SD MMC: Pin change failed!\r\n");
return;
}
if (SD_MMC.begin("/sdcard", false, true)) {
if (SD_MMC.begin("/sdcard", true, true)) { // true = 1-bit mode (avoids GPIO conflict on D3/CS)
printf("SD card initialization successful (4-bit mode)!\r\n");
} else {
printf("SD card initialization failed!\r\n");
@@ -81,7 +81,8 @@ uint16_t Folder_retrieval(const char* directory, const char* fileExtension, char
File file = Path.openNextFile();
while (file && fileCount < maxFiles) {
if (!file.isDirectory() && strstr(file.name(), fileExtension)) {
strncpy(File_Name[fileCount], file.name(), sizeof(File_Name[fileCount]));
strncpy(File_Name[fileCount], file.name(), sizeof(File_Name[fileCount]) - 1);
File_Name[fileCount][sizeof(File_Name[fileCount]) - 1] = '\0'; // Ensure null-termination
if (strcmp(directory, "/") == 0) {
snprintf(filePath, 100, "%s%s", directory, file.name());
} else {

View File

@@ -7,103 +7,224 @@
WebServer server(80);
File uploadFile;
bool uploadSuccess = false;
String uploadedFilename = "";
const char* uploadPage = R"rawliteral(
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Photo Upload Panel</title>
<meta charset="UTF-8">
<title>Photo Frame Upload</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap');
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
background: linear-gradient(135deg, #0f172a, #1e293b);
color: #f8fafc;
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
background: linear-gradient(135deg, #0f0c29, #302b63, #24243e);
color: #f1f5f9;
min-height: 100vh;
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
height: 100vh;
margin: 0;
justify-content: center;
padding: 20px;
}
.card {
background: rgba(30, 41, 59, 0.7);
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 16px;
padding: 32px;
width: 90%;
max-width: 400px;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
background: rgba(255,255,255,0.07);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
border: 1px solid rgba(255,255,255,0.12);
border-radius: 20px;
padding: 36px 32px;
width: 100%;
max-width: 420px;
box-shadow: 0 20px 60px rgba(0,0,0,0.5);
}
.logo { font-size: 32px; margin-bottom: 4px; text-align: center; }
h1 { font-size: 22px; font-weight: 600; text-align: center; color: #e2e8f0; margin-bottom: 6px; }
.subtitle { font-size: 13px; color: #94a3b8; text-align: center; margin-bottom: 28px; }
.drop-zone {
border: 2px dashed rgba(139,92,246,0.5);
border-radius: 12px;
padding: 32px 16px;
text-align: center;
}
h1 { font-size: 24px; margin-bottom: 24px; color: #38bdf8; }
.input-group { margin-bottom: 20px; }
input[type="file"] { display: none; }
.file-label {
display: inline-block;
padding: 12px 24px;
background: #0284c7;
color: white;
border-radius: 8px;
cursor: pointer;
font-weight: 600;
transition: background 0.2s;
transition: all 0.2s;
margin-bottom: 16px;
background: rgba(139,92,246,0.05);
}
.drop-zone:hover, .drop-zone.dragover {
border-color: #8b5cf6;
background: rgba(139,92,246,0.12);
}
.drop-icon { font-size: 36px; margin-bottom: 8px; }
.drop-text { font-size: 14px; color: #94a3b8; }
.drop-text span { color: #a78bfa; font-weight: 500; cursor: pointer; }
input[type="file"] { display: none; }
.file-name {
font-size: 13px;
color: #a78bfa;
text-align: center;
min-height: 20px;
margin-bottom: 20px;
font-weight: 500;
word-break: break-all;
}
.file-label:hover { background: #0369a1; }
button {
width: 100%;
padding: 12px;
background: #10b981;
padding: 14px;
background: linear-gradient(135deg, #7c3aed, #a855f7);
color: white;
border: none;
border-radius: 8px;
font-size: 16px;
border-radius: 12px;
font-size: 15px;
font-weight: 600;
cursor: pointer;
transition: background 0.2s;
margin-top: 10px;
transition: all 0.2s;
letter-spacing: 0.3px;
}
button:hover { background: #059669; }
#status { margin-top: 15px; font-size: 14px; color: #94a3b8; }
button:hover { opacity: 0.9; transform: translateY(-1px); }
button:active { transform: translateY(0); }
button:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }
.hint { font-size: 11px; color: #64748b; text-align: center; margin-top: 14px; }
.toast {
border-radius: 10px;
padding: 12px 16px;
margin-bottom: 20px;
font-size: 13px;
font-weight: 500;
display: flex;
align-items: center;
gap: 10px;
}
.toast.success { background: rgba(16,185,129,0.15); border: 1px solid rgba(16,185,129,0.3); color: #34d399; }
.toast.error { background: rgba(239,68,68,0.15); border: 1px solid rgba(239,68,68,0.3); color: #f87171; }
.progress { display: none; margin-top: 14px; }
.progress-bar {
height: 4px;
background: rgba(255,255,255,0.1);
border-radius: 99px;
overflow: hidden;
}
.progress-fill {
height: 100%;
background: linear-gradient(90deg, #7c3aed, #a855f7);
border-radius: 99px;
width: 0%;
transition: width 0.3s;
}
.progress-text { font-size: 12px; color: #94a3b8; text-align: center; margin-top: 6px; }
</style>
</head>
<body>
<div class="card">
<h1>Upload Photo / Audio</h1>
<div class="logo">&#x1F5BC;&#xFE0F;</div>
<h1>Photo Frame</h1>
<p class="subtitle">Upload media to the SD card wirelessly</p>
%TOAST%
<form method="POST" action="/upload" enctype="multipart/form-data" id="uploadForm">
<div class="input-group">
<label for="file" class="file-label">Choose File (.png / .mp3 / .wav)</label>
<input type="file" id="file" name="file" accept=".png,.mp3,.wav" onchange="updateFilename()">
<div class="drop-zone" id="dropZone" onclick="document.getElementById('file').click()">
<div class="drop-icon">&#x1F4C1;</div>
<div class="drop-text">Drop a file here or <span>browse</span></div>
<input type="file" id="file" name="file" accept=".png,.mp3,.wav" onchange="onFileSelected(this)">
</div>
<div class="file-name" id="fileName">No file selected</div>
<button type="submit" id="uploadBtn" disabled>Upload to Frame</button>
<div class="progress" id="progress">
<div class="progress-bar"><div class="progress-fill" id="progressFill"></div></div>
<div class="progress-text" id="progressText">Uploading...</div>
</div>
<div id="filename" style="margin-bottom: 20px; font-size: 14px; color: #38bdf8;">No file selected</div>
<button type="submit">Upload to Frame</button>
</form>
<div id="status">Supports PNG (172x320 max) and MP3/WAV.</div>
<p class="hint">Accepted: .png (172x320) &nbsp;&middot;&nbsp; .mp3 &nbsp;&middot;&nbsp; .wav</p>
</div>
<script>
function updateFilename() {
const fileInput = document.getElementById('file');
const filenameDiv = document.getElementById('filename');
if (fileInput.files.length > 0) {
filenameDiv.textContent = fileInput.files[0].name;
const dropZone = document.getElementById('dropZone');
const uploadBtn = document.getElementById('uploadBtn');
const fileName = document.getElementById('fileName');
const form = document.getElementById('uploadForm');
const progress = document.getElementById('progress');
const progressFill = document.getElementById('progressFill');
const progressText = document.getElementById('progressText');
function onFileSelected(input) {
if (input.files.length > 0) {
fileName.textContent = input.files[0].name;
uploadBtn.disabled = false;
} else {
filenameDiv.textContent = 'No file selected';
fileName.textContent = 'No file selected';
uploadBtn.disabled = true;
}
}
dropZone.addEventListener('dragover', function(e) { e.preventDefault(); dropZone.classList.add('dragover'); });
dropZone.addEventListener('dragleave', function() { dropZone.classList.remove('dragover'); });
dropZone.addEventListener('drop', function(e) {
e.preventDefault();
dropZone.classList.remove('dragover');
var dt = e.dataTransfer;
if (dt.files.length > 0) {
document.getElementById('file').files = dt.files;
onFileSelected(document.getElementById('file'));
}
});
form.addEventListener('submit', function(e) {
e.preventDefault();
var file = document.getElementById('file').files[0];
if (!file) return;
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload');
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
var pct = Math.round((e.loaded / e.total) * 100);
progressFill.style.width = pct + '%';
progressText.textContent = 'Uploading... ' + pct + '%';
}
});
xhr.onload = function() {
var ok = xhr.status === 200 || xhr.status === 303;
window.location.href = '/?status=' + (ok ? 'ok&file=' + encodeURIComponent(file.name) : 'fail');
};
xhr.onerror = function() { window.location.href = '/?status=fail'; };
progress.style.display = 'block';
uploadBtn.disabled = true;
uploadBtn.textContent = 'Uploading...';
xhr.send(formData);
});
</script>
</body>
</html>
)rawliteral";
static bool isAllowedExtension(const String& filename) {
String lower = filename;
lower.toLowerCase();
return lower.endsWith(".png") || lower.endsWith(".mp3") || lower.endsWith(".wav");
}
void handleUpload() {
HTTPUpload& upload = server.upload();
if (upload.status == UPLOAD_FILE_START) {
String filename = upload.filename;
if (!filename.startsWith("/")) {
filename = "/" + filename;
if (!filename.startsWith("/")) filename = "/" + filename;
// Reject files that are not PNG, MP3, or WAV
if (!isAllowedExtension(filename)) {
printf("WebUpload: Rejected non-media file: %s\r\n", filename.c_str());
uploadSuccess = false;
return;
}
printf("WebUpload: Starting upload of %s\r\n", filename.c_str());
uploadedFilename = filename;
uploadFile = SD_MMC.open(filename, "w");
uploadSuccess = (bool)uploadFile;
}
else if (upload.status == UPLOAD_FILE_WRITE) {
if (uploadFile) {
@@ -114,29 +235,48 @@ void handleUpload() {
if (uploadFile) {
uploadFile.close();
printf("WebUpload: Successfully uploaded %s (%d bytes)\r\n", upload.filename.c_str(), upload.totalSize);
// Re-scan SD card folders to index the new file
uploadSuccess = true;
// Re-scan SD card to index the new file
Search_Images("/");
Search_Audio("/");
} else {
uploadSuccess = false;
}
}
}
static String buildPage(const String& status, const String& file) {
String toast = "";
if (status == "ok") {
String safeName = file;
safeName.replace("<", "&lt;");
safeName.replace(">", "&gt;");
toast = "<div class=\"toast success\">&#x2705; <span>\"" + safeName + "\" uploaded successfully!</span></div>";
} else if (status == "fail") {
toast = "<div class=\"toast error\">&#x274C; <span>Upload failed. Only .png, .mp3 and .wav files are accepted.</span></div>";
}
String page = String(uploadPage);
page.replace("%TOAST%", toast);
return page;
}
void initWebServer() {
// Start WiFi Access Point with SSID "love" and password "love"
WiFi.softAP("love", "love");
IPAddress IP = WiFi.softAPIP();
printf("WiFi AP Started. SSID: 'love'\r\n");
printf("Web Server IP address: %s\r\n", IP.toString().c_str());
printf("WiFi AP Started. SSID: 'love' Password: 'love'\r\n");
printf("Web Server IP: %s\r\n", IP.toString().c_str());
// Serve Page
server.on("/", HTTP_GET, []() {
server.send(200, "text/html", uploadPage);
String status = server.hasArg("status") ? server.arg("status") : "";
String file = server.hasArg("file") ? server.arg("file") : "";
server.send(200, "text/html", buildPage(status, file));
});
// Handle file uploads
server.on("/upload", HTTP_POST, []() {
// Redirect back to main upload page on success
server.sendHeader("Location", "/");
String loc = uploadSuccess
? "/?status=ok&file=" + uploadedFilename
: "/?status=fail";
server.sendHeader("Location", loc);
server.send(303);
}, handleUpload);

View File

@@ -68,13 +68,17 @@ void setup() {
printf("Initialization complete!\r\n");
printf("Found %d PNG images and %d Audio files (.mp3/.wav).\r\n", Image_Count, Audio_Count);
if (Image_Count == 0 || Audio_Count == 0) {
if (Image_Count == 0 && Audio_Count == 0) {
hasError = true;
currentState = STATE_ERROR;
printf("ERROR: No media found on microSD card!\r\n");
} else {
if (Image_Count == 0) printf("WARNING: No PNG images found — audio-only mode.\r\n");
if (Audio_Count == 0) printf("WARNING: No audio files found — silent slideshow mode.\r\n");
if (Image_Count > 0) {
printf("Displaying initial image (index 0): %s\r\n", Image_Names[0]);
Display_Image_By_Index("/", 0);
}
currentState = STATE_IDLE;
}
@@ -111,11 +115,13 @@ void playCurrentPair() {
void handleSinglePress() {
printf("Gesture: Single Click - Next Slide\r\n");
if (!hasError) {
uint16_t total = std::max(Image_Count, Audio_Count);
if (total == 0) return;
if (currentState == STATE_AUTOPLAY) {
currentState = STATE_IDLE;
printf("Autoplay Disabled.\r\n");
}
currentIndex = (currentIndex + 1) % std::max(Image_Count, Audio_Count);
currentIndex = (currentIndex + 1) % total;
playCurrentPair();
}
}
@@ -130,12 +136,13 @@ void handleDoublePress() {
void handleTriplePress() {
printf("Gesture: Triple Click - Previous Slide\r\n");
if (!hasError) {
uint16_t total = std::max(Image_Count, Audio_Count);
if (total == 0) return;
if (currentState == STATE_AUTOPLAY) {
currentState = STATE_IDLE;
printf("Autoplay Disabled.\r\n");
}
uint16_t totalMedia = std::max(Image_Count, Audio_Count);
currentIndex = (currentIndex + totalMedia - 1) % totalMedia;
currentIndex = (currentIndex + total - 1) % total;
playCurrentPair();
}
}
@@ -214,10 +221,11 @@ void loop() {
// Handle slideshow auto-advance in Autoplay mode
if (currentState == STATE_AUTOPLAY && !hasError) {
uint16_t total = std::max(Image_Count, Audio_Count);
// Only advance when the audio stops playing and slideShowInterval (5s) has passed
if (!isAudioPlaying() && (now - lastSlideTime > slideShowInterval)) {
if (total > 0 && !isAudioPlaying() && (now - lastSlideTime > slideShowInterval)) {
lastSlideTime = now;
currentIndex = (currentIndex + 1) % std::max(Image_Count, Audio_Count);
currentIndex = (currentIndex + 1) % total;
playCurrentPair();
}
}