Files
project-vesper/src/FileManager/FileManager.cpp
T

354 lines
11 KiB
C++

#include "FileManager.hpp"
#define TAG "FileManager"
#include "../BuiltInMelodies/BuiltInMelodies.hpp"
FileManager::FileManager(ConfigManager* config) : configManager(config) {
// Constructor - store reference to ConfigManager
}
bool FileManager::initializeSD() {
uint8_t sdPin = configManager->getHardwareConfig().sdChipSelect;
if (!SD.begin(sdPin)) {
LOG_ERROR(TAG, "SD Card initialization failed!");
return false;
}
return true;
}
bool FileManager::addMelody(JsonVariant doc) {
LOG_INFO(TAG, "Adding melody from JSON data...");
// Extract URL and filename from JSON
if (!doc.containsKey("download_url") || !doc.containsKey("melodys_uid")) {
LOG_ERROR(TAG, "Missing required parameters: download_url or melodys_uid");
return false;
}
const char* url = doc["download_url"];
const char* melodyUid = doc["melodys_uid"];
// Check if this is a built-in melody - skip download if it exists
if (BuiltInMelodies::isBuiltInMelody(melodyUid)) {
const BuiltInMelodies::MelodyInfo* builtinMelody = BuiltInMelodies::findMelodyByUID(melodyUid);
if (builtinMelody != nullptr) {
LOG_INFO(TAG, "Melody '%s' is a built-in melody, skipping download", melodyUid);
return true; // Success - no download needed
}
// If starts with builtin_ but not found, log warning and try download anyway
LOG_WARNING(TAG, "Melody '%s' has builtin_ prefix but not found in library, attempting download", melodyUid);
}
// Download the melody file to /melodies directory
if (downloadFile(url, "/melodies", melodyUid)) {
LOG_INFO(TAG, "Melody download successful: %s", melodyUid);
return true;
}
LOG_ERROR(TAG, "Melody download failed: %s", melodyUid);
return false;
}
bool FileManager::ensureDirectoryExists(const String& dirPath) {
if (!initializeSD()) {
return false;
}
// Ensure the directory ends with '/'
String normalizedPath = dirPath;
if (!normalizedPath.endsWith("/")) {
normalizedPath += "/";
}
// Check if directory already exists
if (SD.exists(normalizedPath.c_str())) {
return true; // Directory already exists, success
}
// Create directory if it doesn't exist
return SD.mkdir(normalizedPath.c_str());
}
bool FileManager::downloadFile(const String& url, const String& directory, const String& filename) {
LOG_INFO(TAG, "Starting download from: %s", url.c_str());
// Check if URL is HTTPS
bool isHttps = url.startsWith("https://");
HTTPClient http;
WiFiClientSecure* secureClient = nullptr;
// Configure HTTP client based on protocol
if (isHttps) {
secureClient = new WiFiClientSecure();
secureClient->setInsecure(); // Skip certificate validation for Firebase
secureClient->setTimeout(15); // 15 second timeout for TLS operations
http.begin(*secureClient, url);
LOG_DEBUG(TAG, "Using HTTPS with secure client");
} else {
http.begin(url);
LOG_DEBUG(TAG, "Using HTTP");
}
http.setTimeout(30000); // 30 second timeout for large files
http.setFollowRedirects(HTTPC_FORCE_FOLLOW_REDIRECTS); // Follow redirects automatically
// Disable task watchdog for current task during blocking HTTPS operation
// The TLS handshake can take several seconds and would trigger watchdog
LOG_DEBUG(TAG, "Disabling watchdog for download...");
esp_task_wdt_delete(NULL);
LOG_DEBUG(TAG, "Sending HTTP GET request...");
int httpCode = http.GET();
// Re-enable task watchdog after HTTP request completes
esp_task_wdt_add(NULL);
LOG_DEBUG(TAG, "Watchdog re-enabled after HTTP request");
if (httpCode != HTTP_CODE_OK && httpCode != HTTP_CODE_MOVED_PERMANENTLY && httpCode != HTTP_CODE_FOUND) {
LOG_ERROR(TAG, "HTTP GET failed, code: %d, error: %s", httpCode, http.errorToString(httpCode).c_str());
http.end();
if (secureClient) delete secureClient;
return false;
}
if (!initializeSD()) {
http.end();
if (secureClient) delete secureClient;
return false;
}
// Ensure directory exists
if (!ensureDirectoryExists(directory)) {
LOG_ERROR(TAG, "Failed to create directory: %s", directory.c_str());
http.end();
if (secureClient) delete secureClient;
return false;
}
// Build full file path
String dirPath = directory;
if (!dirPath.endsWith("/")) dirPath += "/";
String fullPath = dirPath + filename;
File file = SD.open(fullPath.c_str(), FILE_WRITE);
if (!file) {
LOG_ERROR(TAG, "Failed to open file for writing: %s", fullPath.c_str());
http.end();
if (secureClient) delete secureClient;
return false;
}
// Get stream and file size
WiFiClient* stream = http.getStreamPtr();
int contentLength = http.getSize();
LOG_DEBUG(TAG, "Content length: %d bytes", contentLength);
uint8_t buffer[512]; // Smaller buffer for better responsiveness
size_t totalBytes = 0;
unsigned long lastYield = millis();
unsigned long lastLog = millis();
// Download with aggressive watchdog feeding
while (http.connected() && (contentLength <= 0 || totalBytes < contentLength)) {
// Check available data
size_t availableSize = stream->available();
if (availableSize) {
// Read available data (up to buffer size)
size_t readSize = availableSize > sizeof(buffer) ? sizeof(buffer) : availableSize;
int bytesRead = stream->readBytes(buffer, readSize);
if (bytesRead > 0) {
file.write(buffer, bytesRead);
totalBytes += bytesRead;
// Log progress every 5 seconds
if (millis() - lastLog > 5000) {
LOG_DEBUG(TAG, "Download progress: %u bytes", totalBytes);
lastLog = millis();
}
}
}
// Aggressive task yielding every 50ms to prevent watchdog timeout
if (millis() - lastYield > 50) {
yield();
vTaskDelay(5 / portTICK_PERIOD_MS); // Let other tasks run (5ms)
lastYield = millis();
}
// Exit if no data and connection closed
if (!availableSize && !http.connected()) {
break;
}
// Yield and small delay if no data available yet
if (!availableSize) {
yield();
vTaskDelay(10 / portTICK_PERIOD_MS);
}
}
file.close();
http.end();
if (secureClient) delete secureClient;
LOG_INFO(TAG, "Download complete, file saved to: %s (%u bytes)", fullPath.c_str(), totalBytes);
return true;
}
String FileManager::listFilesAsJson(const char* dirPath) {
if (!initializeSD()) {
LOG_ERROR(TAG, "SD initialization failed");
return "{}";
}
File dir = SD.open(dirPath);
if (!dir || !dir.isDirectory()) {
LOG_ERROR(TAG, "Directory not found: %s", dirPath);
return "{}";
}
DynamicJsonDocument doc(1024);
JsonArray fileList = doc.createNestedArray("files");
File file = dir.openNextFile();
while (file) {
if (!file.isDirectory()) {
fileList.add(file.name());
}
file = dir.openNextFile();
}
String json;
serializeJson(doc, json);
return json;
}
bool FileManager::fileExists(const String& filePath) {
if (!initializeSD()) {
return false;
}
File file = SD.open(filePath.c_str());
if (file) {
file.close();
return true;
}
return false;
}
bool FileManager::deleteFile(const String& filePath) {
if (!initializeSD()) {
return false;
}
if (SD.remove(filePath.c_str())) {
LOG_INFO(TAG, "File deleted: %s", filePath.c_str());
return true;
} else {
LOG_ERROR(TAG, "Failed to delete file: %s", filePath.c_str());
return false;
}
}
bool FileManager::createDirectory(const String& dirPath) {
return ensureDirectoryExists(dirPath);
}
size_t FileManager::getFileSize(const String& filePath) {
if (!initializeSD()) {
return 0;
}
File file = SD.open(filePath.c_str());
if (!file) {
return 0;
}
size_t size = file.size();
file.close();
return size;
}
bool FileManager::writeJsonFile(const String& filePath, JsonDocument& doc) {
if (!initializeSD()) {
return false;
}
File file = SD.open(filePath.c_str(), FILE_WRITE);
if (!file) {
LOG_ERROR(TAG, "Failed to open file for writing: %s", filePath.c_str());
return false;
}
if (serializeJson(doc, file) == 0) {
LOG_ERROR(TAG, "Failed to write JSON to file: %s", filePath.c_str());
file.close();
return false;
}
file.close();
LOG_DEBUG(TAG, "JSON file written successfully: %s", filePath.c_str());
return true;
}
bool FileManager::readJsonFile(const String& filePath, JsonDocument& doc) {
if (!initializeSD()) {
return false;
}
File file = SD.open(filePath.c_str(), FILE_READ);
if (!file) {
LOG_ERROR(TAG, "Failed to open file for reading: %s", filePath.c_str());
return false;
}
DeserializationError error = deserializeJson(doc, file);
file.close();
if (error) {
LOG_ERROR(TAG, "Failed to parse JSON from file: %s, error: %s",
filePath.c_str(), error.c_str());
return false;
}
LOG_DEBUG(TAG, "JSON file read successfully: %s", filePath.c_str());
return true;
}
// ════════════════════════════════════════════════════════════════════════════
// HEALTH CHECK IMPLEMENTATION
// ════════════════════════════════════════════════════════════════════════════
bool FileManager::isHealthy() const {
if (!configManager) {
LOG_DEBUG(TAG, "FileManager: Unhealthy - ConfigManager not available");
return false;
}
// Use SD.cardType() as a lightweight presence check — avoids calling SD.begin()
// on every health poll (which is expensive and crashes without a card inserted).
if (SD.cardType() == CARD_NONE) {
LOG_DEBUG(TAG, "FileManager: Unhealthy - SD Card initialization failed");
return false;
}
return true;
}
bool FileManager::appendLine(const String& filePath, const String& line) {
if (!initializeSD()) {
return false;
}
File file = SD.open(filePath.c_str(), FILE_APPEND);
if (!file) {
return false;
}
file.println(line);
file.close();
return true;
}