Files
project-vesper/src/FileManager/FileManager.hpp
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

105 lines
4.9 KiB
C++

/*
* ═══════════════════════════════════════════════════════════════════════════════════
* FILEMANAGER.HPP - SD Card and File Operations Manager
* ═══════════════════════════════════════════════════════════════════════════════════
*
* 📁 THE FILE SYSTEM ORCHESTRATOR OF VESPER 📁
*
* This class provides a clean, robust interface for all file operations
* including melody file management, configuration persistence, and
* comprehensive error handling with automatic recovery.
*
* 📋 VERSION: 2.0 (Enhanced file management)
* 📅 DATE: 2025
* 👨‍💻 AUTHOR: Advanced Bell Systems
* ═══════════════════════════════════════════════════════════════════════════════════
*/
#ifndef FILEMANAGER_HPP
#define FILEMANAGER_HPP
#include <Arduino.h>
#include <SD.h>
#include <HTTPClient.h>
#include <WiFiClient.h>
#include <ArduinoJson.h>
#include <vector>
#include <algorithm>
#include <time.h>
#include "../Logging/Logging.hpp"
#include "../ConfigManager/ConfigManager.hpp"
class FileManager {
private:
ConfigManager* configManager;
public:
// Constructor
FileManager(ConfigManager* config);
// Core file operations
bool downloadFile(const String& url, const String& directory, const String& filename);
bool addMelody(JsonVariant doc); // Download melody file from JSON data
String listFilesAsJson(const char* dirPath);
// File utilities
bool fileExists(const String& filePath);
bool deleteFile(const String& filePath);
bool createDirectory(const String& dirPath);
size_t getFileSize(const String& filePath);
// Generic read/write for JSON data
bool writeJsonFile(const String& filePath, JsonDocument& doc);
bool readJsonFile(const String& filePath, JsonDocument& doc);
// Append a single text line to a file (used by SD log channel)
bool appendLine(const String& filePath, const String& line);
// Append a line to a day-rotated log file under logDir (e.g. "/logs").
// Creates the directory if missing, names the file YYYY-MM-DD.log using
// `timestamp` (falls back to a fixed bucket if timestamp <= 0, i.e. no
// wall clock yet), and prunes oldest dated files once the directory
// exceeds maxTotalBytes.
bool appendLogLine(const String& logDir, const String& line, time_t timestamp,
size_t maxTotalBytes);
// List dated log files under logDir as JSON: {"files":[{"name":"2026-07-14.log","size":1234}, ...]}
String listLogFilesAsJson(const String& logDir);
// Deletes every dated log file under logDir (e.g. all of "/logs"). Used
// by logs.clear — a QA-to-shipping reset, not part of normal log rotation
// (that's pruneLogDirectory(), which only trims oldest files over budget).
// Returns the number of files actually deleted.
size_t deleteAllLogFiles(const String& logDir);
// Read a bounded chunk of a log file for remote retrieval (paginated —
// callers loop, feeding next_offset back in, until eof is true).
// Returns JSON: {"data":"<raw text chunk>","next_offset":N,"eof":bool}
// Empty JSON object on error (file not found, etc).
String readLogChunkAsJson(const String& logDir, const String& fileName,
size_t offset, size_t maxBytes);
// ═══════════════════════════════════════════════════════════════════════════════
// HEALTH CHECK METHOD
// ═══════════════════════════════════════════════════════════════════════════════
/** @brief Check if FileManager is in healthy state */
bool isHealthy() const;
private:
// Helper functions
bool initializeSD();
bool ensureDirectoryExists(const String& dirPath);
String logFileNameForTimestamp(time_t timestamp) const;
void pruneLogDirectory(const String& logDir, size_t maxTotalBytes);
// pruneLogDirectory() does a full directory scan (SD.open + iterate every
// file) — too expensive to run on every single log line, and the calling
// task's stack may not have room for it (e.g. the 3KB MQTT connect task).
// Only check every LOG_PRUNE_CHECK_INTERVAL writes.
static constexpr uint16_t LOG_PRUNE_CHECK_INTERVAL = 50;
uint16_t logWriteCountSinceProbe = 0;
};
#endif