Files
project-vesper/src/FileManager/FileManager.cpp
T
bonamin f41332a771 feat(Telemetry,FileManager,LoggingHandler): QA-to-shipping stats reset — telemetry.reset_boot_data + logs.clear
Console wants a "reset device stats before shipping" button for staff to
clear QA-bench data (test reboots, debug log spam) without wiping actual
device configuration. telemetry.reset_strikes and telemetry.reset_metrics
already covered bell strikes and runtime/playback counters — this adds the
two gaps: lifetime boot count + SD boot history, and SD debug logs.

Deliberately does not touch FirmwareValidator's NVS namespace (rollback
safety state, not history) or device identity NVS (serial/hw_family).

Verified: pio run on all four board variants.
2026-07-17 14:14:55 +03:00

564 lines
17 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 built-in library — skip download if found
if (BuiltInMelodies::isBuiltInMelody(melodyUid)) {
LOG_INFO(TAG, "Melody '%s' is a built-in melody, skipping download", melodyUid);
return true;
}
// 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;
}
// Strip trailing slash — SD.exists() returns false for directories when a
// trailing slash is present, even if the directory exists.
String normalizedPath = dirPath;
while (normalizedPath.endsWith("/")) {
normalizedPath.remove(normalizedPath.length() - 1);
}
if (SD.exists(normalizedPath.c_str())) {
return true;
}
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());
if (url.startsWith("https://")) {
LOG_ERROR(TAG, "HTTPS URLs are not supported — serve melody files over HTTP");
return false;
}
HTTPClient http;
http.begin(url);
http.setTimeout(30000);
http.setFollowRedirects(HTTPC_FORCE_FOLLOW_REDIRECTS);
LOG_DEBUG(TAG, "Sending HTTP GET request...");
int httpCode = http.GET();
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();
return false;
}
if (!initializeSD()) {
http.end();
return false;
}
// Ensure directory exists
if (!ensureDirectoryExists(directory)) {
LOG_ERROR(TAG, "Failed to create directory: %s", directory.c_str());
http.end();
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();
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();
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;
}
// ════════════════════════════════════════════════════════════════════════════
// DAY-ROTATED SD LOG FILE
// ════════════════════════════════════════════════════════════════════════════
String FileManager::logFileNameForTimestamp(time_t timestamp) const {
// No wall clock yet (RTC absent and NTP hasn't synced) — bucket these
// early lines together rather than losing them.
if (timestamp <= 0) {
return "unset-date.log";
}
struct tm timeInfo;
gmtime_r(&timestamp, &timeInfo);
char name[16]; // "YYYY-MM-DD.log" + null
snprintf(name, sizeof(name), "%04d-%02d-%02d.log",
timeInfo.tm_year + 1900, timeInfo.tm_mon + 1, timeInfo.tm_mday);
return String(name);
}
bool FileManager::appendLogLine(const String& logDir, const String& line, time_t timestamp,
size_t maxTotalBytes) {
if (!ensureDirectoryExists(logDir)) {
return false;
}
String dirPath = logDir;
if (!dirPath.endsWith("/")) dirPath += "/";
String fullPath = dirPath + logFileNameForTimestamp(timestamp);
if (!appendLine(fullPath, line)) {
return false;
}
// Pruning does a full directory scan — too expensive (stack and I/O) to
// run on every write. Check periodically instead; a day-rotated file
// growing past budget between checks is fine, the next check catches it.
if (maxTotalBytes > 0) {
logWriteCountSinceProbe++;
if (logWriteCountSinceProbe >= LOG_PRUNE_CHECK_INTERVAL) {
logWriteCountSinceProbe = 0;
pruneLogDirectory(logDir, maxTotalBytes);
}
}
return true;
}
// Deletes the oldest dated .log files in logDir until the directory's total
// size is at or under maxTotalBytes. Relies on filenames sorting
// lexicographically oldest-first (YYYY-MM-DD.log).
void FileManager::pruneLogDirectory(const String& logDir, size_t maxTotalBytes) {
if (!initializeSD()) {
return;
}
File dir = SD.open(logDir.c_str());
if (!dir || !dir.isDirectory()) {
return;
}
std::vector<std::pair<String, size_t>> files;
size_t totalBytes = 0;
File file = dir.openNextFile();
while (file) {
if (!file.isDirectory()) {
String name = file.name();
size_t size = file.size();
files.push_back({name, size});
totalBytes += size;
}
file = dir.openNextFile();
}
dir.close();
if (totalBytes <= maxTotalBytes) {
return;
}
std::sort(files.begin(), files.end(),
[](const std::pair<String, size_t>& a, const std::pair<String, size_t>& b) {
return a.first < b.first;
});
String dirPath = logDir;
if (!dirPath.endsWith("/")) dirPath += "/";
for (const auto& entry : files) {
if (totalBytes <= maxTotalBytes) break;
// entry.first may already be a full path (SD.open on some cores
// returns the absolute name) — normalize to dirPath + basename.
String name = entry.first;
int lastSlash = name.lastIndexOf('/');
if (lastSlash >= 0) name = name.substring(lastSlash + 1);
String fullPath = dirPath + name;
if (SD.remove(fullPath.c_str())) {
// Deliberately not logged: this runs from inside the SD log write
// path itself (appendLogLine -> pruneLogDirectory), and LOG_* here
// would re-enter Logging::writeToSd() if FileManager's SD level is
// enabled. Serial-only would be safe but adds complexity for a
// rotation event that isn't actionable at runtime.
totalBytes -= entry.second;
}
}
}
size_t FileManager::deleteAllLogFiles(const String& logDir) {
// Unlike pruneLogDirectory(), this is called from a command handler
// (LoggingHandler::handleLogsClear), not from inside the SD log write
// path — LOG_* here is safe and doesn't risk re-entering Logging::writeToSd().
if (!initializeSD()) {
return 0;
}
File dir = SD.open(logDir.c_str());
if (!dir || !dir.isDirectory()) {
return 0;
}
std::vector<String> names;
File file = dir.openNextFile();
while (file) {
if (!file.isDirectory()) {
names.push_back(file.name());
}
file = dir.openNextFile();
}
dir.close();
String dirPath = logDir;
if (!dirPath.endsWith("/")) dirPath += "/";
size_t deleted = 0;
for (const auto& rawName : names) {
// Same normalization as pruneLogDirectory() — some cores return an
// absolute path from file.name() rather than a bare basename.
String name = rawName;
int lastSlash = name.lastIndexOf('/');
if (lastSlash >= 0) name = name.substring(lastSlash + 1);
String fullPath = dirPath + name;
if (SD.remove(fullPath.c_str())) {
deleted++;
} else {
LOG_WARNING(TAG, "deleteAllLogFiles: failed to remove %s", fullPath.c_str());
}
}
LOG_WARNING(TAG, "deleteAllLogFiles: removed %u of %u file(s) from %s",
(unsigned)deleted, (unsigned)names.size(), logDir.c_str());
return deleted;
}
String FileManager::readLogChunkAsJson(const String& logDir, const String& fileName,
size_t offset, size_t maxBytes) {
// Reject path traversal / nested paths — fileName must be a bare filename
// as returned by listLogFilesAsJson.
if (fileName.indexOf('/') >= 0 || fileName.indexOf("..") >= 0 || fileName.isEmpty()) {
LOG_ERROR(TAG, "readLogChunkAsJson: invalid file name: %s", fileName.c_str());
return "{}";
}
if (!initializeSD()) {
return "{}";
}
String dirPath = logDir;
if (!dirPath.endsWith("/")) dirPath += "/";
String fullPath = dirPath + fileName;
File file = SD.open(fullPath.c_str(), FILE_READ);
if (!file) {
LOG_ERROR(TAG, "readLogChunkAsJson: file not found: %s", fullPath.c_str());
return "{}";
}
size_t fileSize = file.size();
if (offset > fileSize) offset = fileSize;
file.seek(offset);
size_t remaining = fileSize - offset;
size_t toRead = remaining < maxBytes ? remaining : maxBytes;
String chunk;
chunk.reserve(toRead + 1);
while (chunk.length() < toRead && file.available()) {
chunk += (char)file.read();
}
file.close();
size_t nextOffset = offset + chunk.length();
bool eof = nextOffset >= fileSize;
DynamicJsonDocument doc(chunk.length() + 256);
doc["data"] = chunk;
doc["next_offset"] = nextOffset;
doc["eof"] = eof;
String json;
serializeJson(doc, json);
return json;
}
String FileManager::listLogFilesAsJson(const String& logDir) {
if (!initializeSD()) {
LOG_ERROR(TAG, "SD initialization failed");
return "{}";
}
File dir = SD.open(logDir.c_str());
if (!dir || !dir.isDirectory()) {
LOG_ERROR(TAG, "Log directory not found: %s", logDir.c_str());
return "{}";
}
DynamicJsonDocument doc(2048);
JsonArray fileList = doc.createNestedArray("files");
File file = dir.openNextFile();
while (file) {
if (!file.isDirectory()) {
String name = file.name();
int lastSlash = name.lastIndexOf('/');
if (lastSlash >= 0) name = name.substring(lastSlash + 1);
JsonObject entry = fileList.createNestedObject();
entry["name"] = name;
entry["size"] = file.size();
}
file = dir.openNextFile();
}
dir.close();
String json;
serializeJson(doc, json);
return json;
}