Save files appending on same session and new file on new session

This commit is contained in:
Emanuele Trabattoni
2026-04-07 15:53:52 +02:00
parent 668b590d7c
commit 877236ee4e
11 changed files with 1112 additions and 1043 deletions

View File

@@ -1,6 +1,8 @@
#include "datasave.h"
void save_history(const PSRAMVector<ignitionBoxStatus> &history)
static constexpr size_t min_free = 1024 * 1024; // minimum free space in SPIFFS to allow saving history (1MB)
void save_history(const PSRAMVector<ignitionBoxStatus> &history, const std::filesystem::path &file_path)
{
// Initialize SPIFFS
if (!SPIFFS.begin(true))
@@ -10,25 +12,49 @@ void save_history(const PSRAMVector<ignitionBoxStatus> &history)
vTaskDelay(pdMS_TO_TICKS(5000));
esp_restart();
}
else
LOG_INFO("SPIFFS mounted successfully");
if (SPIFFS.totalBytes() - SPIFFS.usedBytes() < min_free ) // check if at least 1MB is free for saving history
{
LOG_INFO("SPIFFS mounted successfully");
LOG_ERROR("Not enough space in SPIFFS to save history");
return;
}
std::ofstream ofs("/spiffs/ignA_history.csv", std::ios::out | std::ios::trunc);
std::filesystem::path to_save = file_path;
if (file_path.root_path() != "/spiffs")
to_save = std::filesystem::path("/spiffs") / file_path;
auto save_flags = std::ios::out;
static bool first_save = true;
if (first_save || !SPIFFS.exists(to_save.c_str()))
{
save_flags |= std::ios::trunc; // overwrite existing file
first_save = false;
LOG_INFO("Saving history to SPIFFS, new file: ", to_save.c_str());
}
else
{
save_flags |= std::ios::app; // append to new file
LOG_INFO("Saving history to SPIFFS, appending to existing file: ", to_save.c_str());
}
std::ofstream ofs(to_save, save_flags);
if (ofs.fail())
{
LOG_ERROR("Failed to open file for writing");
return;
}
//write csv header
ofs << "TS,\
EVENTS_12,DLY_12,STAT_12,V_12_1,V_12_2,V_12_3,V_12_4,IGNITION_MODE_12,\
EVENTS_34,DLY_34,STAT_34,V_34_1,V_34_2,V_34_3,V_34_4,IGNITION_MODE_34,\
ENGINE_RPM,ADC_READTIME,N_QUEUE_ERRORS";
for (auto &entry : history)
// write csv header
if (first_save)
{
ofs << "TS,\
EVENTS_12,DLY_12,STAT_12,V_12_1,V_12_2,V_12_3,V_12_4,IGNITION_MODE_12,\
EVENTS_34,DLY_34,STAT_34,V_34_1,V_34_2,V_34_3,V_34_4,IGNITION_MODE_34,\
ENGINE_RPM,ADC_READTIME,N_QUEUE_ERRORS";
}
for (const auto &entry : history)
{
ofs << std::to_string(entry.timestamp) << ","
<< std::to_string(entry.coils12.n_events) << ","
@@ -52,9 +78,9 @@ void save_history(const PSRAMVector<ignitionBoxStatus> &history)
<< std::to_string(entry.n_queue_errors);
ofs << std::endl;
}
auto written_bytes = ofs.tellp();
ofs.flush();
ofs.close();
LOG_INFO("Ignition A history saved to SPIFFS, bytes written: ", (uint32_t)written_bytes);
LOG_INFO("Ignition A history saved to SPIFFS, records written: ", history.size());
SPIFFS.end(); // unmount SPIFFS to ensure data is written and avoid corruption on next mount
}