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



我目前正在使用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": [
"mooimann",
"mooiweern"
],
"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: %srn", 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("rn- file cleaned");
} else {
Serial.println("rn- 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: %srn", 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+密码制作sepperate文件(

这里有一个可以在项目中实现的测试草图。我没有时间写比这更详细的草图。

如果你对这个有任何疑问,请告诉我

#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: %sn", 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();
}

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

#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: %srn", 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: %sn", 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();
}

任何改进都是可取的。

最新更新