noam76

config_json_file

Jan 23rd, 2018
701
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.00 KB | None | 0 0
  1. void loadConfig()
  2. {
  3.  if (SPIFFS.exists("/config.json"))
  4.  {
  5.   //file exists, reading and loading
  6.   Serial.println("reading config file");
  7.   File configFile = SPIFFS.open("/config.json", "r");
  8.   if (configFile)
  9.   {
  10.    Serial.println("opened config file");
  11.    size_t size = configFile.size();
  12.    // Allocate a buffer to store contents of the file.
  13.    std::unique_ptr<char[]> buf(new char[size]);
  14.  
  15.    configFile.readBytes(buf.get(), size);
  16.    DynamicJsonBuffer jsonBuffer;
  17.    JsonObject& json = jsonBuffer.parseObject(buf.get());
  18.    // json.printTo(Serial); // print to serial the json file
  19.    if (json.success())
  20.    {
  21.     PlantS1 = json["TargetSoilPlant1"];
  22.     PlantS2 = json["TargetSoilPlant2"];
  23.     PlantS3 = json["TargetSoilPlant3"];
  24.     PlantS4 = json["TargetSoilPlant4"];
  25.    }
  26.    else{ Serial.println("failed to load json config"); }
  27.   }
  28.   else{ Serial.println("Failed to open config file"); }
  29.   configFile.close();
  30.   Serial.print("TargetSoilPlant1 :");Serial.println(PlantS1);
  31.   Serial.print("TargetSoilPlant2 :");Serial.println(PlantS2);
  32.   Serial.print("TargetSoilPlant3 :");Serial.println(PlantS3);
  33.   Serial.print("TargetSoilPlant4 :");Serial.println(PlantS4);
  34.  }
  35.  else{ Serial.println("The JSON file doesn't exist "); }
  36. }
  37.  
  38. void saveConfig()
  39. {
  40.  if (SPIFFS.exists("/config.json"))
  41.  {
  42.   //file exists, Saving configuration
  43.   Serial.println("saving config");
  44.   DynamicJsonBuffer jsonBuffer;
  45.   JsonObject& json = jsonBuffer.createObject();
  46.   json["TargetSoilPlant1"] = PlantS1;
  47.   json["TargetSoilPlant2"] = PlantS2;
  48.   json["TargetSoilPlant3"] = PlantS3;
  49.   json["TargetSoilPlant4"] = PlantS4;
  50.    
  51.   File configFile = SPIFFS.open("/config.json", "w");
  52.   if (!configFile) { Serial.println("failed to open config file for writing"); }
  53.   // json.prettyPrintTo(Serial);
  54.   json.printTo(configFile);
  55.  
  56.   if (json.printTo(configFile) == 0)
  57.    { Serial.println(F("Failed to write to file")); }
  58.   configFile.close();
  59.   //end save
  60.  }
  61.  else{ Serial.println("The JSON file doesn't exist "); }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment