Skip to content

root is destroy in the void loop #715

Closed
@Ostrochibi

Description

@Ostrochibi

Hi Benoit,

First, thank you about the work you offer to us with this library.

I'm facing to an issue i can't resolve by myself. I wanna get back data to the spiff. I get it, i can see it with root.prettyPrintTo(Serial) in the void setup but when i wanna do the same in the void loop there is nothing in except an empty Json than i create in the beginning of the sketch.
Due to that, when i lost my data after each reboot because when i use my add function in the void loop root was empty.
I try to do a second object "root2" and surprise, when i do a root2.prettyPrintTo(Serial) in the void setup it's worked well but when i do the same in the void loop, i have an error root2 was not declared in this scope.

Can you help with that pls?

Version of your library 5.13.1
The scketch:

#include <ESP8266WiFi.h>
 #include <ESP8266WebServer.h>
 #include <TimeLib.h>
 #include <NtpClientLib.h>
 #include <ArduinoJson.h>
 #include <FS.h>
 
 #define ssid1      "Livebox"      // WiFi SSID
 #define password1  ""  // WiFi password
 #define ssid     "ESP"      // WiFi SSID
 #define password ""  // WiFi password
 #define HISTORY_FILE "/history.json"
 char json[10000];  
 String connectionMethod = "default";  // WiFi password
 String selectedPlastic = "none";
 
 
 const uint8_t GPIOPIN[9] = {13,5,14,12,16};  // Led
  
 ESP8266WebServer server ( 80 );
 String rootStrAfterLoad ;
 StaticJsonBuffer<10000> jsonBuffer;     
 JsonObject& root = jsonBuffer.createObject();
 JsonArray& plasticKind = root.createNestedArray("plasticKind");
 

 void savePlastic(){          
  File historyFile = SPIFFS.open(HISTORY_FILE, "r+");
  root.prettyPrintTo(Serial);
  root.printTo(historyFile);
  historyFile.close();  
 }


 

 void loadPlastic(){
  File file = SPIFFS.open(HISTORY_FILE, "r");
  if (!file){
    Serial.println("Aucun historique existe - No History Exist");
  } else {
    size_t size = file.size();
    if ( size == 0 ) {
      Serial.println("Fichier historique vide - History file empty !");
    } else {
        std::unique_ptr<char[]> buf (new char[size]);
        file.readBytes(buf.get(), size);
        JsonObject& root = jsonBuffer.parseObject(buf.get());
        if (!root.success()) {
          Serial.println("Impossible de lire le JSON - Impossible to read JSON file");
        } else {
          Serial.println("Historique charge - History loaded");
          root.prettyPrintTo(Serial);
          root.printTo(rootStrAfterLoad);
          
          }
      }
    file.close();
  }
}

 void addPlastic() {
  String tps = NTP.getTimeDateString();
  JsonObject& item = plasticKind.createNestedObject();
  item["plName"]= "Global";
  item["weltTemp"]= "210";
  item["timeRecycling"]= 0;
  item["timestamp"]= tps;
  loadPlastic();
}



  void sendPlasticList(){  
  root.printTo(json, sizeof(json));         
  server.send(200, "application/json", json);  
  Serial.println("Historique envoye");   
  }



  void setup() {

  
   for ( int x = 0 ; x < 8 ; x++ ) {
     pinMode(GPIOPIN[x], OUTPUT);
   }

  Serial.begin ( 115200 );
  Serial.println("scan start");

  // WiFi.scanNetworks will return the number of networks found
  int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0) {
    Serial.println("no networks found");
  } else {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i) {
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*");
      if (WiFi.SSID(i) == ssid1) {
        connectionMethod = "home";
        Serial.println ( connectionMethod );
      }else {      
        };
      delay(10);
    }
  }

  
   

   if (connectionMethod == "home"){
    Serial.print ( "Connecting to " ); 
    Serial.println ( ssid1 );
    WiFi.begin ( ssid1, password1 );
  // Attente de la connexion au réseau WiFi / Wait for connection
    while ( WiFi.status() != WL_CONNECTED ) {
      delay ( 500 ); Serial.print ( "." );
    }
  // Connexion WiFi établie / WiFi connexion is OK
    Serial.println ( "" );
    Serial.print ( "Connected to " ); Serial.println ( ssid1 );
    Serial.print ( "IP address: " ); Serial.println ( WiFi.localIP() );
   }else{
    WiFi.mode(WIFI_AP_STA);
    WiFi.softAP( ssid, password );
    Serial.print ( "Connected to " ); 
    Serial.println ( ssid );
    Serial.print ( "IP address: " ); 
    Serial.println ( WiFi.softAPIP());
    
   }
   delay(10);

   NTP.begin("pool.ntp.org", 1, true);
   NTP.setInterval(60);
   Serial.println(NTP.getTime());
   NTP.onNTPSyncEvent([](NTPSyncEvent_t error) {
    if (error) {
     Serial.print("Time Sync error: ");
      if (error == noResponse)
        Serial.println("NTP server not reachable");
      else if (error == invalidAddress)
        Serial.println("Invalid NTP server address");
    }
    else {
      Serial.print("Got NTP time: ");
      Serial.println(NTP.getTimeDateString(NTP.getLastNTPSync()));
    }
  });

   if (!SPIFFS.begin()){
     Serial.println("SPIFFS Mount failed");
    } else {
     Serial.println("SPIFFS Mount succesfull");
    }

loadPlastic();
JsonObject& root = jsonBuffer.parseObject(rootStrAfterLoad);
root.prettyPrintTo(Serial);

JsonObject& root2 = jsonBuffer.parseObject(rootStrAfterLoad);
root2.prettyPrintTo(Serial);
  

   server.on("/plasticList.json", sendPlasticList);

   server.serveStatic("/js", SPIFFS, "/js");
   server.serveStatic("/css", SPIFFS, "/css");
   server.serveStatic("/img", SPIFFS, "/img");
   server.serveStatic("/", SPIFFS, "/index.html");
 
   server.begin();
   Serial.println();
   Serial.println ( "HTTP server started" );
   
 }
 
 void loop() {
   server.handleClient();
  delay(100);
  delay(10000);
  Serial.println(rootStrAfterLoad);
  Serial.println();
  Serial.println();
  root.prettyPrintTo(Serial);
  Serial.println();
//  root2.prettyPrintTo(Serial);
  Serial.println();
//  
//  addPlastic();
//  savePlastic();
//  loadPlastic();
//  delay(10000);
 }

Have a good day!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions