Repository navigation
Expand file tree
/
Copy pathConfigFile.ino
More file actions
95 lines (77 loc) · 2.22 KB
/
Copy pathConfigFile.ino
File metadata and controls
95 lines (77 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Example: storing JSON configuration file in flash file system
//
// Uses ArduinoJson library by Benoit Blanchon.
// https://github.com/bblanchon/ArduinoJson
//
// Created Aug 10, 2015 by Ivan Grokhotkov.
//
// This example code is in the public domain.
#include <ArduinoJson.h>
#include "FS.h"
bool loadConfig() {
File configFile = SPIFFS.open("/config.json", "r");
if (!configFile) {
Serial.println("Failed to open config file");
return false;
}
size_t size = configFile.size();
if (size > 1024) {
Serial.println("Config file size is too large");
return false;
}
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
// We don't use String here because ArduinoJson library requires the input
// buffer to be mutable. If you don't use ArduinoJson, you may as well
// use configFile.readString instead.
configFile.readBytes(buf.get(), size);
StaticJsonDocument<200> doc;
auto error = deserializeJson(doc, buf.get());
if (error) {
Serial.println("Failed to parse config file");
return false;
}
const char* serverName = doc["serverName"];
const char* accessToken = doc["accessToken"];
// Real world application would store these values in some variables for
// later use.
Serial.print("Loaded serverName: ");
Serial.println(serverName);
Serial.print("Loaded accessToken: ");
Serial.println(accessToken);
return true;
}
bool saveConfig() {
StaticJsonDocument<200> doc;
doc["serverName"] = "api.example.com";
doc["accessToken"] = "128du9as8du12eoue8da98h123ueh9h98";
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
Serial.println("Failed to open config file for writing");
return false;
}
serializeJson(doc, configFile);
return true;
}
void setup() {
Serial.begin(115200);
Serial.println("");
delay(1000);
Serial.println("Mounting FS...");
if (!SPIFFS.begin()) {
Serial.println("Failed to mount file system");
return;
}
if (!saveConfig()) {
Serial.println("Failed to save config");
} else {
Serial.println("Config saved");
}
if (!loadConfig()) {
Serial.println("Failed to load config");
} else {
Serial.println("Config loaded");
}
}
void loop() {
}