首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将多个ssid和密码写入同一个json文件ESP32

如何将多个ssid和密码写入同一个json文件ESP32
EN

Stack Overflow用户
提问于 2022-07-30 17:10:07
回答 2查看 290关注 0票数 0

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

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

所需的json文件是:

代码语言:javascript
运行
复制
{"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"  }]}

相反,当一个以上的值被序列化并追加时,它将如下所示:

代码语言:javascript
运行
复制
    {
  "information": {},
  "test": [
    "mooiman\n",
    "mooiweer\n"
  ],
  "number": [
    1,
    2
  ]
}

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

我测试的代码:

代码语言:javascript
运行
复制
#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中。下次再做吧。接下来,当您串行写读时,它将向您显示保存的/SSID.json。

提前谢谢。

请注意,DynamicJsonDocument开始为空。

PS。我知道littlefs是新的spiff,但让我们先试着让它工作(或者我需要为每个ssid+password创建分隔文件)

EN

回答 2

Stack Overflow用户

发布于 2022-08-10 07:20:57

这里是一个测试草图,您可以实现到您的项目。我没有时间写比这更详细的素描。

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

代码语言:javascript
运行
复制
#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();
}

// Open the file and put the pretty json into the serial directly.
void printFileContent(){
  File credFile = LittleFS.open(FILE_PATH,FILE_READ);
  if( !credFile ){ Serial.println("Failed to open file"); return; }
  serializeJsonPretty(Serial, credFile);
  credFile.close();
}

void clearFile(){
  if( !LittleFS.exists(FILE_PATH) ){ Serial.println("Credentials file does not exists yet!"); return; }
  File credFile = LittleFS.open(FILE_PATH,FILE_READ);
  credFile.remove();
}

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();
}
票数 0
EN

Stack Overflow用户

发布于 2022-08-10 23:46:11

我是在Dr.Random的帮助下弄明白的。这不是完整的答案,但它有助于获得json格式并正确地附加到该文件。下面的代码是一个工作示例。

代码语言:javascript
运行
复制
#include <Arduino.h>
#include <WiFi.h>
#include "FS.h"
#include "LittleFS.h"
#include <ArduinoJson.h>


#define FORMAT_LITTLEFS_IF_FAILED true
#define DOC_SIZE 5000
#define FILE_PATH "/SSID.json"

String ssid = "yourssid";
String passwords = "yourpass";

String readString;

char FileReadBuff[1024];


void readFile(fs::FS &fs, const char * path){
    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;
    }

    Serial.println("- read from file:");
    while(file.available()){
        Serial.write(file.read());
    }
    file.close();
}


void Showone(int wichone){
  DynamicJsonDocument doc(DOC_SIZE);

  File credFile = LittleFS.open(FILE_PATH, FILE_READ);// open file for reading
  DeserializationError error = deserializeJson(doc, credFile);// deserialize json
  if( !credFile ){ Serial.println("Failed to open file"); return; }// if file doesn't exist, return 
   
  const char* SSID = doc[wichone]["SSID"]; //
  const char* PASS = doc[wichone]["PASS"]; // 

  Serial.print("SSID and PASS = "); Serial.print(SSID); Serial.print(PASS); Serial.print(" "); Serial.println(" ");
  
  credFile.close();

}

void addCredentials(const char * input){
  DynamicJsonDocument doc(DOC_SIZE);// create json doc
  String Serialized; // create string to store serialized json

  File credFile = LittleFS.open(FILE_PATH, FILE_READ);// open file for reading

if( !credFile ){ Serial.println("Failed to open file"); return; }// if file doesn't exist, return
    
DeserializationError error = deserializeJson(doc, credFile);// deserialize json
if( error ){ Serial.printf("Error on deserialization: %s\n", error.c_str() );} //error when spiff is empty or not formatted correctly

JsonArray inforArr = doc["information"].as<JsonArray>();// get array from json


JsonObject newCred = doc.createNestedObject();// create new object in json
newCred["SSID"] = input;
newCred["PASS"] = input;

 
serializeJsonPretty(doc, Serialized);
Serial.print("input = "); Serial.println(input);
Serial.print("Serialized: "); Serial.println(Serialized);

File credFile2 = LittleFS.open(FILE_PATH, FILE_WRITE);// open file for writing

credFile2.print(Serialized);

credFile2.close();
credFile.close();
Serialized = "";      

}

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(LittleFS, "/SSID.json");
      
      Serial.println(FileReadBuff);

      for( int i = 0; i < sizeof(FileReadBuff);  ++i ){
       FileReadBuff[i] = (char)0;
      }
      
    }
    if (readString.indexOf("SHOW") >= 0) {
     readString = "";
      Serial.println("Showing the following input(number): ");   //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
     Showone(readString.toInt());

     }
    }
      
    }
    if (readString.indexOf("CLEAN") >= 0) {                    //CLEAN cleans the SSID.json file
      Serial.println("reading deserialized json");
      File credFile = LittleFS.open(FILE_PATH, FILE_WRITE);// open file for writing
      credFile.print("");
      credFile.close();
    }
    
    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
     addCredentials(readString.c_str());

     }
    }
   }
  }
 }
}

void setup() {
  // put your setup code here, to run once:
   Serial.begin(115200);

   if(!LittleFS.begin(FORMAT_LITTLEFS_IF_FAILED)){
        Serial.println("LittleFS Mount Failed");
        return;
    }
    //if /ssid.json doesn't exist, create it littlefs
    if(!LittleFS.exists(FILE_PATH)){
        Serial.println("File doesn't exist, creating it");
        File credFile = LittleFS.open(FILE_PATH, FILE_WRITE);
        if(!credFile){
            Serial.println("Failed to create file");
            return;
        }
        credFile.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();
}

任何改进仍然是可取的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73177634

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档