|
| 1 | +#include "ConfigUtils.h" |
| 2 | +#include <FS.h> |
| 3 | +#include <SPIFFS.h> |
| 4 | + |
| 5 | +#define FORMAT_SPIFFS_IF_FAILED true |
| 6 | +static bool ready = false; |
| 7 | + |
| 8 | +bool spiffs_init(){ |
| 9 | + if(!SPIFFS.begin(FORMAT_SPIFFS_IF_FAILED)){ |
| 10 | + Serial.println("SPIFFS Mount Failed"); |
| 11 | + return false; |
| 12 | + } |
| 13 | + ready = true; |
| 14 | + return true; |
| 15 | +} |
| 16 | + |
| 17 | +bool load_json(DynamicJsonDocument &config,const char* FileName,bool verbose){ |
| 18 | + if(!ready){ |
| 19 | + if(!spiffs_init()){ |
| 20 | + return false; |
| 21 | + } |
| 22 | + } |
| 23 | + File file = SPIFFS.open(FileName,"r"); |
| 24 | + |
| 25 | + DeserializationError error = deserializeJson(config, file); |
| 26 | + if (error){ |
| 27 | + Serial.println(F("Failed to read json file")); |
| 28 | + file.close(); |
| 29 | + return false; |
| 30 | + }else{ |
| 31 | + if(verbose){ |
| 32 | + Serial.println(); |
| 33 | + Serial.println("Loaded json :"); |
| 34 | + serializeJsonPretty(config, Serial); |
| 35 | + Serial.println(); |
| 36 | + } |
| 37 | + file.close(); |
| 38 | + return true; |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +bool save_json(DynamicJsonDocument &config,const char* FileName){ |
| 43 | + if(!ready){ |
| 44 | + if(!spiffs_init()){ |
| 45 | + return false; |
| 46 | + } |
| 47 | + } |
| 48 | + File file = SPIFFS.open(FileName,"w"); |
| 49 | + file.close(); |
| 50 | + return true; |
| 51 | +} |
| 52 | + |
| 53 | +bool load_config(DynamicJsonDocument &config,bool verbose){ |
| 54 | + bool result = load_json(config,"/config.json"); |
| 55 | + if(verbose){ |
| 56 | + if(result){ |
| 57 | + Serial.println(); |
| 58 | + Serial.println("Loaded configuration :"); |
| 59 | + serializeJsonPretty(config, Serial); |
| 60 | + Serial.println(); |
| 61 | + }else{ |
| 62 | + Serial.println("Failed to load configuration"); |
| 63 | + } |
| 64 | + } |
| 65 | + return result; |
| 66 | +} |
| 67 | + |
| 68 | +bool save_config(DynamicJsonDocument &config){ |
| 69 | + return save_json(config,"/config.json"); |
| 70 | +} |
| 71 | + |
| 72 | +void timelog(String Text){ |
| 73 | + Serial.println(String(millis())+" : "+Text);//micros() |
| 74 | +} |
| 75 | + |
0 commit comments