【问题标题】:How to write multiple ssid's and passwords to the same json file ESP32如何将多个 ssid 和密码写入同一个 json 文件 ESP32
【发布时间】:2022-08-10 15:20:57
【问题描述】:

我目前正在使用 arduinojson6 测试一段代码。我的目标是将多个 ssid 和密码存储到 esp32 SPIFF。

未经编辑的问题包含一段将附加到文件而不是读取文档、删除/SSID.json、添加到文档序列化并像我现在一样再次保存文件的代码,也不是解决方案。

所需的 json 文件将是:

{\"information\":[{ \"SSID\":\"variable blaat1\", \"PASS1\":\"variable Abc1\", \"NUMBER\": \"1\" },{ \"SSID\":\"variable blaat2\", \"PASS2\":\"variable Abc2\", \"NUMBER\": \"2\"  },{ \"SSID\":\"variable blaat3\", \"PASS3\":\"variable Abc3\", \"NUMBER\": \"3\"  },{ \"SSID\":\"variable blaat4\", \"PASS4\":\"variable Abc4\", \"NUMBER\": \"4\"  },{ \"SSID\":\"variable blaat5\", \"PASS5\":\"variable Abc5\", \"NUMBER\": \"5\"  }]}

相反,当超过 1 个值被序列化并附加时,它将如下所示:

    {
  \"information\": {},
  \"test\": [
    \"mooiman\\n\",
    \"mooiweer\\n\"
  ],
  \"number\": [
    1,
    2
  ]
}

也许你们中的一些人知道如何正确序列化它。

我测试的代码:

#include <Arduino.h>
#include <WiFi.h>
//#include <time.h>
//#include <ESP32Ping.h>
#include \"FS.h\"
#include \"SPIFFS.h\"
//#include <HTTPClient.h>
#include <ArduinoJson.h>


int numberofInputs = 1;

String ssid = \"YourSSID\";
String passwords = \"YourPassword\";

String readString;

char FileReadBuff[1024];

DynamicJsonDocument doc(1024);


void readFile(fs::FS &fs, const char * path){
   if (SPIFFS.exists(\"/SSID.json\") == false)
  {
   File file = SPIFFS.open(\"/SSID.json\", FILE_WRITE);
 
   if (!file) {
    Serial.println(\"There was an error opening the file for writing\");
    return;
  }
 
  if (file.print(\"SSID\")) {
    Serial.println(\"File was written\");
  } else {
    Serial.println(\"File write failed\");
  }
  file.close();
 }
    Serial.printf(\"Reading file: %s\\r\\n\", path);

    File file = fs.open(path);
    if(!file || file.isDirectory()){
        Serial.println(\"- failed to open file for reading\");
        return;
    }
    uint16_t i = 0;
    Serial.println(\"reading\");
    while (file.available()) {
    FileReadBuff[i] = file.read();
    i++;
  }
    file.close();
}
void CleanFile(fs::FS &fs, const char * path, const char * message) {
  for( int i = 0; i < sizeof(FileReadBuff);  ++i ){
  FileReadBuff[i] = (char)0;
  }
  File file = SPIFFS.open(path, FILE_WRITE);
  if (fs.remove(path)) {
    Serial.println(\"\\r\\n- file cleaned\");
  } else {
    Serial.println(\"\\r\\n- Cleaning failed\");
  }
  file.print(path);
  
}
void appendFile(fs::FS &fs, const char * path, const char * message){
   if (SPIFFS.exists(\"/SSID.json\") == false)
  {
   File file = SPIFFS.open(\"/SSID.json\", FILE_WRITE);
 
   if (!file) {
    Serial.println(\"There was an error opening the file for writing\");
    return;
  }
 
  if (file.print(\"SSID\")) {
    Serial.println(\"File was written\");
  } else {
    Serial.println(\"File write failed\");
  }
  file.close();
 }
    Serial.printf(\"Appending to file: %s\\r\\n\", path);

    File file = fs.open(path, FILE_APPEND);
    if(!file){
        Serial.println(\"- failed to open file for appending\");
        return;
    }
    if(file.println(message)){
        Serial.println(\"- message appended\");
    } else {
        Serial.println(\"- append failed\");
    }
    file.close();
}

void Deserialization(){
 

  for( int i = 0; i < sizeof(FileReadBuff);  ++i ){
  FileReadBuff[i] = (char)0;
  }

  readFile(SPIFFS, \"/SSID.json\");  //read everything from ssid.json file
  const char * JsonFF = FileReadBuff; // put everything in to const char
  Serial.print(\"Json From File:\"); Serial.println(JsonFF);
  
  DeserializationError error = deserializeJson(doc, JsonFF);
  if(error){
     Serial.print(F(\"deserializeJson() failed: \")); Serial.println(error.f_str()); // if not legit print error
  }
  if(!error){
    String information = doc[\"information\"];

     Serial.println(information);
     information = \"\";
  }
}

void testjson(){


  readString = \"\";

while(readString.length() < 1) {
  while (Serial.available()) {
    delay(10);  //small delay to allow input buffer to fill
    if (Serial.available() > 0) {
      char c = Serial.read();  //gets one byte from serial buffer
      if (c == \',\') {
        break;
      }  //breaks out of capture loop to print readstring
      readString += c;
    } //makes the string readString
  }
  if (readString.length() > 0) {
    Serial.println(readString); //prints string to serial port out

    if (readString.indexOf(\"READ\") >= 0) {
      Serial.println(\"reading file\");
      readFile(SPIFFS, \"/SSID.json\");
      
      Serial.println(FileReadBuff);

      for( int i = 0; i < sizeof(FileReadBuff);  ++i ){
       FileReadBuff[i] = (char)0;
      }
      
    }
    if (readString.indexOf(\"DES\") >= 0) {                      //DEZ deserialize will result in an error because json file is currently not valid 
      Serial.println(\"reading deserialized json\");
      Deserialization();
      
    }
    if (readString.indexOf(\"CLEAN\") >= 0) {                    //CLEAN cleans the SSID.json file
      Serial.println(\"reading deserialized json\");
      CleanFile(SPIFFS, \"/SSID.json\", \"\");
    }
    
    if (readString.indexOf(\"WRANDOM\") >= 0){                   //WRANDOM writes a random string to the SSID.json file
      readString = \"\";
      Serial.println(\"Going to write the following input:\");   //waiting for user input
      while(readString.length() < 1) {
       while (Serial.available()) {
        delay(10);  //small delay to allow input buffer to fill
        if (Serial.available() > 0) {
        char c = Serial.read();  //gets one byte from serial buffer
        if (c == \',\') {
        break;
        }  //breaks out of capture loop to print readstring
        readString += c;
    } //makes the string readString
  }
  if (readString.length() > 0) {
    Serial.println(readString); //prints string to serial port out
    `here is the part we\'re talking about`
      CleanFile(SPIFFS, \"/SSID.json\", \"\");
      JsonObject information = doc.createNestedObject(\"information\");

      String SerializedJson = \"\";

      doc[\"test\"].add(readString);
      doc[\"number\"].add(numberofInputs);
      
      serializeJsonPretty(doc, SerializedJson);
     
      appendFile(SPIFFS, \"/SSID.json\", SerializedJson.c_str());
      SerializedJson = \"\";
      numberofInputs ++;
      return;

     }
    }
   }
  }
 }
}


void setup() {
  // put your setup code here, to run once:
   Serial.begin(115200);
    if (!SPIFFS.begin(true)) {
      Serial.println(\"An Error has occurred while mounting SPIFFS\");
   return;
  }
  
  if (SPIFFS.exists(\"/SSID.json\") == false)
  {
   File file = SPIFFS.open(\"/SSID.json\", FILE_WRITE);
 
   if (!file) {
    Serial.println(\"There was an error opening the file for writing\");
    return;
  }
 
  if (file.print(\"SSID\")) {
    Serial.println(\"File was written\");
  } else {
    Serial.println(\"File write failed\");
  }
  file.close();
 }
   WiFi.mode(WIFI_MODE_STA);

   WiFi.begin(ssid.c_str(), passwords.c_str());

   while (WiFi.status() != WL_CONNECTED) { //Check for the connection
    delay(1000);
    Serial.print(\".\");
    }

  Serial.println(\"Connected\");


}

void loop() {
  // put your main code here, to run repeatedly:
  readString = \"\"; //clears variable for new input
  Serial.println(\"Ready for new input: \");
  testjson();
}

所以当你连续写 WRANDOM 时,你会得到提示输入一些东西。 当收到它时,它将存储在 json 中。 再做一次。 接下来,当您串行写入 READ 时,它将显示已保存的 /SSID.json。

提前致谢。

请注意,DynamicJsonDocument 开始时为空。

PS。我知道 littlefs 是新的 spiff,但让我们首先尝试完成这项工作(或者我需要为每个 ssid+密码制作单独的文件)

  • ArduinoJson 提供了一个assistant 工具供您创建所需的代码。
  • 我知道并且我试图弄清楚我的 json 结构应该如何以及如何对其进行序列化/反序列化。
  • 你是 JSON 绑定的吗?您还可以使用您需要的信息制作一个小型结构,然后将二进制文件写入 ESP32 闪存上的特定分区,并使用已知的结构大小将它们一个接一个地添加。

标签: json esp32 platformio arduino-esp32


【解决方案1】:

这是您可以在项目中实施的测试草图。 我没有时间写比这更详细的草图。

如果您对此有任何疑问,请告诉我

#include <Arduino.h>
#include "FS.h"
#include <LittleFS.h>
#include <ArduinoJson.h>

#define DOC_SIZE 5000

/*
Example JSON :
{
  "information":[
    { "SSID":"variable blaat1", "PASS1":"variable Abc1", "NUMBER": "1" },
    { "SSID":"variable blaat2", "PASS2":"variable Abc2", "NUMBER": "2"  },
    { "SSID":"variable blaat3", "PASS3":"variable Abc3", "NUMBER": "3"  },
    { "SSID":"variable blaat4", "PASS4":"variable Abc4", "NUMBER": "4"  },
    { "SSID":"variable blaat5", "PASS5":"variable Abc5", "NUMBER": "5"  }
  ]
}
*/

/*
  When you create a JSON array, you don't need to push the index of the object, since you can later
  ask for the array size, therefor you know the indexes. Also you don't need to separate the passwords
  like PASS1 or PASS2 since every cred is a separate object.
*/
void addCredentials( const char* SSID, const char* PW ){
    // Create a static JSON document.
    StaticJsonDocument fileDoc(DOC_SIZE);
    // Open the file containing the credentials
    File credFile = LittleFS.open(FILE_PATH,FILE_READ);
    // Check if it opened.
    if( !credFile ){ Serial.println("Failed to open file"); return; }
    // Deserialize the file
    DeserializationError error = deserializeJson(fileDoc, credFile );
    // Check if the deserialization has any errors.
    if( error ){ Serial.printf("Error on deserialization: %s\n", error.c_str() );
    // Get the info array from the JSON.
    JsonArray infoArr = fileDoc["information"].as<JsonArray>();
    // Create a new object inside the array.
    JsonObject newCred = infoArr.createNestedObject();
    // Add credentials to the object.
    newCred["SSID"] = SSID;
    newCred["PASS"] = PW;
    // Serialize everythig back to the file.
    serializeJson(fileDoc, credFile);
    // Close the file.
    credFile.close();
}

void getUserInput(){
  if( !Serial.available() ){ return; }
  // Get the credentials or whatever from the serial and call the addCredentials( const char* SSID, const char* PW ); function.
}


void setup() {
  Serial.begin(115200);
}

void loop() {
  getUserInput();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-09
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多