Dear forum
My application requires some variables that I'd like to have optional. I currently have a 'secret.h' file filled with the variables, but that requires a recompile everytime I want to alter one or more of these variables.
The variables are e.g my Local IP addres, gateway, DNS, but also my SSID and password, and some API Identifiers that may change.
So I came up with the following:
- create a (JSON) 'variables.txt' file in LittleFS
- Read this file in the setup.
My variables file could look like this:
[
{ "name": "local_IP", "value": "192.168.1.5" },
{ "name": "Gateway", "value": "192.168.1.254" },
{ "name": "Subnet", "value": "255.255.255.0" },
{ "name": "primaryDNS", "value": "192.168.1.254" },
{ "name": "SSID", "value": "mySsid" },
{ "name": "Password", "value": "myphrase" },
{ "name": "SomeAPI", "value": "1234568ugerf5364747" }
]
I then try and read this with the following snippet:
if ((linelength = readFile(LittleFS, "variables.txt", variable_chars, sizeof(variable_chars))) > 0) {
Serial.printf("Read %d characters from variables.txt\n", linelength);
JsonDocument JSONvariables;
DeserializationError error = deserializeJson(JSONvariables, variable_chars);
if (error) {
Serial.print("deserializeJson() failed: ");
Serial.println(error.c_str());
}
else {
for (JsonObject elem : JSONvariables.as<JsonArray>()) {
const char* name1 = elem["name"];
const char* value1 = elem["value"];
// const char* unit1 = elem["unit"];
Serial.println(name1);
Serial.println(value1);
// Serial.println(unit1);
if (!strcmp(name1, "local_IP")) local_IP.fromString(value1);
if (!strcmp(name1, "Gateway")) Gateway.fromString(value1);
if (!strcmp(name1, "Subnet")) Subnet.fromString(value1);
if (!strcmp(name1, "primaryDNS")) primaryDNS.fromString(value1);
if (!strcmp(name1, "SSID")) strcpy(mySSID, value1);
if (!strcmp(name1, "Password")) strcpy(myPassword, value1);
}
}
}
else {
Serial.println("No variables.txt.. aborting....");
}
if (!WiFi.config(local_IP, Gateway, Subnet, primaryDNS)) {
Serial.println("STA Failed to configure");
}
function readFile() just opens and returns all characters in the file.
This will work, however, it seems a bit lengthy.
What I'd like is a setup in which the Json in variables.txt is independent of my declared variables. So e.g if I add in variables.txt the Json line
{"name": "Pete", "value": "friend"}
I'd like to add a variable 'Pete' with the value "friend", without declaring Pete up front.
Hope the question is clear.
Maybe I am on the wrong track here. Your input is appreciated.
The 'name' in the Json is the actual variable used in my program. Can I somehow use the 'name' of the Json to define a variable? Maybe in a struct?