diff --git a/src/AgValue.cpp b/src/AgValue.cpp index dc41896..b25fc1f 100644 --- a/src/AgValue.cpp +++ b/src/AgValue.cpp @@ -2,6 +2,7 @@ #include "AgConfigure.h" #include "AirGradient.h" #include "App/AppDef.h" +#include "SPIFFS.h" #define json_prop_pmFirmware "firmware" #define json_prop_pm01Ae "pm01" @@ -1065,4 +1066,61 @@ JSONVar Measurements::buildPMS(AirGradient &ag, int ch, bool allCh, bool withTem return pms; } -void Measurements::setDebug(bool debug) { _debug = debug; } \ No newline at end of file +void Measurements::setDebug(bool debug) { _debug = debug; } + +void Measurements::saveLocalStorage(AirGradient &ag) { + File file; + if (!SPIFFS.exists(FILE_PATH)) { + file = SPIFFS.open(FILE_PATH, FILE_APPEND, true); + file.println("pm0.3 count,pm1,pm2.5,pm10,temp,rhum,co2,tvoc,nox"); // header + } else { + file = SPIFFS.open(FILE_PATH, FILE_APPEND, false); + } + + if (!file) { + Serial.println("Failed local storage file path"); + return; + } + + // Save new measurements + file.printf("%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,%d,%d,%d\n", ag.round2(_pm_03_pc[0].update.avg), + ag.round2(_pm_01[0].update.avg), ag.round2(_pm_25[0].update.avg), + ag.round2(_pm_10[0].update.avg), ag.round2(_temperature[0].update.avg), + ag.round2(_humidity[0].update.avg), (int)round(_co2.update.avg), + (int)round(_tvoc.update.avg), (int)round(_nox.update.avg)); + + Serial.println("Success save measurements to local storage"); +} + +char *Measurements::getLocalStorage() { + char *buf = new char[1024]; + if (buf == nullptr) { + Serial.println("NEW getLocal buffer failed"); + return nullptr; + } + memset(buf, 0, 1024); + + // TODO: Buffer based on file size + bool success = false; + File file = SPIFFS.open(FILE_PATH); + if (file && !file.isDirectory()) { + if (file.readBytes(buf, file.size()) != file.size()) { + Serial.println("Reading measurements file: failed - size not match"); + } else { + Serial.println("Reading measurements file: success"); + success = true; + } + file.close(); + } else { + SPIFFS.format(); + } + + if (!success) { + Serial.println("Reading measurements file failed"); + delete buf; + return nullptr; + } + + // NOTE: Don't forget to free + return buf; +} \ No newline at end of file diff --git a/src/AgValue.h b/src/AgValue.h index f6ae46d..c7182e3 100644 --- a/src/AgValue.h +++ b/src/AgValue.h @@ -142,6 +142,9 @@ public: String toString(bool localServer, AgFirmwareMode fwMode, int rssi, AirGradient &ag, Configuration &config); + void saveLocalStorage(AirGradient &ag); + char *getLocalStorage(); + /** * Set to true if want to debug every update value */ @@ -173,6 +176,7 @@ private: IntegerValue _pm_10_pc[2]; // particle count 10 bool _debug = false; + const char *FILE_PATH = "/measurement.csv"; // Local storage file path /** * @brief Get PMS5003 firmware version string