Save configuration to preferences in NVS
This commit is contained in:
237
src/config.cpp
237
src/config.cpp
@@ -14,7 +14,7 @@ Config::Config(Preferences& prefs)
|
||||
for (size_t i = 0; i < configdefsCount; ++i) {
|
||||
defs[configdefs[i].key] = &configdefs[i];
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
[[noreturn]] void Config::error_abort() const {
|
||||
@@ -83,83 +83,70 @@ void Config::load() {
|
||||
prefs.end();
|
||||
}
|
||||
|
||||
bool Config::save(JsonObject json) {
|
||||
|
||||
// TODO Not fail if one single value is wrong?
|
||||
void Config::updateValue(const char* key, ConfigType type, ConfigValue newvalue) {
|
||||
switch (type) {
|
||||
case ConfigType::BYTE:
|
||||
prefs.putUChar(key, std::get<uint8_t>(newvalue));
|
||||
break;
|
||||
case ConfigType::SHORT:
|
||||
prefs.putShort(key, std::get<int16_t>(newvalue));
|
||||
break;
|
||||
case ConfigType::INT:
|
||||
prefs.putInt(key, std::get<int32_t>(newvalue));
|
||||
break;
|
||||
case ConfigType::BOOL:
|
||||
prefs.putBool(key, std::get<bool>(newvalue));
|
||||
break;
|
||||
case ConfigType::FLOAT:
|
||||
prefs.putFloat(key, std::get<float>(newvalue));
|
||||
break;
|
||||
case ConfigType::CHAR:
|
||||
prefs.putChar(key, std::get<char>(newvalue));
|
||||
break;
|
||||
case ConfigType::STRING:
|
||||
prefs.putString(key, std::get<String>(newvalue));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void Config::save() {
|
||||
ConfigValue oldval;
|
||||
prefs.begin(PREF_NAME, false);
|
||||
|
||||
int errors = 0;
|
||||
for (JsonPair kv : json) {
|
||||
const char* key = kv.key().c_str();
|
||||
JsonVariant v = kv.value();
|
||||
|
||||
auto it = values.find(key);
|
||||
if (it == values.end()) {
|
||||
LOGE(TAG, "Unexpected missing key: %s", key);
|
||||
return false;
|
||||
}
|
||||
|
||||
auto itdef = defs.find(key);
|
||||
if (itdef == defs.end()) {
|
||||
LOGE(TAG, "Unexpected missing defs key: %s", key);
|
||||
return false;
|
||||
}
|
||||
|
||||
// const ConfigDef* def = itdef->second;
|
||||
|
||||
switch (itdef->second->type) {
|
||||
case ConfigType::BYTE: {
|
||||
if (!v.is<uint8_t>()) {
|
||||
errors++;
|
||||
for (const auto& def : configdefs) {
|
||||
if (prefs.isKey(def.key)) {
|
||||
switch (def.type) {
|
||||
case ConfigType::BYTE:
|
||||
oldval = (uint8_t)prefs.getUChar(def.key, std::get<uint8_t>(def.defval));
|
||||
break;
|
||||
case ConfigType::SHORT:
|
||||
oldval = (int16_t)prefs.getShort(def.key, std::get<int16_t>(def.defval));
|
||||
break;
|
||||
case ConfigType::INT:
|
||||
oldval = prefs.getInt(def.key, std::get<int32_t>(def.defval));
|
||||
break;
|
||||
case ConfigType::BOOL:
|
||||
oldval = prefs.getBool(def.key, std::get<bool>(def.defval));
|
||||
break;
|
||||
case ConfigType::FLOAT:
|
||||
oldval = prefs.getFloat(def.key, std::get<float>(def.defval));
|
||||
break;
|
||||
case ConfigType::CHAR:
|
||||
oldval = (char)prefs.getChar(def.key, std::get<char>(def.defval));
|
||||
break;
|
||||
case ConfigType::STRING:
|
||||
oldval = prefs.getString(def.key, std::get<String>(def.defval));
|
||||
break;
|
||||
}
|
||||
uint8_t newval = v.as<uint8_t>();
|
||||
uint8_t *curval = std::get_if<uint8_t>(&values[key]);
|
||||
if (newval != *curval) {
|
||||
values[key] = newval;
|
||||
//prefs.putUChar(key, newval);
|
||||
LOGI(TAG, "changing %s, replacing %d with %d", key, *curval, newval);
|
||||
}
|
||||
break;
|
||||
}
|
||||
/* case ConfigType::SHORT:
|
||||
if (!v.is<int16_t>()) return false;
|
||||
values[key] = v.as<int16_t>();
|
||||
prefs.putShort(key, v.as<int16_t>());
|
||||
break;
|
||||
case ConfigType::INT:
|
||||
if (!v.is<int32_t>()) return false;
|
||||
values[key] = v.as<int32_t>();
|
||||
prefs.putInt(key, v.as<int32_t>());
|
||||
break;
|
||||
case ConfigType::BOOL:
|
||||
if (!v.is<bool>()) return false;
|
||||
values[key] = v.as<bool>();
|
||||
prefs.putBool(key, v.as<bool>());
|
||||
break;
|
||||
case ConfigType::FLOAT:
|
||||
if (!v.is<float>()) return false;
|
||||
values[key] = v.as<float>();
|
||||
prefs.putFloat(key, v.as<float>());
|
||||
break;
|
||||
case ConfigType::CHAR:
|
||||
if (!v.is<const char*>()) return false;
|
||||
values[key] = v.as<const char*>()[0];
|
||||
prefs.putChar(key, v.as<const char*>()[0]);
|
||||
break;
|
||||
case ConfigType::STRING:
|
||||
if (!v.is<const char*>()) return false;
|
||||
values[key] = String(v.as<const char*>());
|
||||
prefs.putString(key, v.as<const char*>());
|
||||
break; */
|
||||
default:
|
||||
ESP_LOGE("CFG", "Unsupported type for key %s", key);
|
||||
if (values[def.key] != oldval) {
|
||||
LOGD(TAG, "NVS update needed for %s", def.key);
|
||||
updateValue(def.key, def.type, values[def.key]);
|
||||
}
|
||||
} else {
|
||||
LOGD(TAG, "Key does not exist in NVS: %s, creating", def.key);
|
||||
updateValue(def.key, def.type, values[def.key]);
|
||||
}
|
||||
}
|
||||
|
||||
prefs.end();
|
||||
return true;
|
||||
}
|
||||
|
||||
void Config::dump() {
|
||||
@@ -211,6 +198,16 @@ T Config::get(const char* key) const {
|
||||
return std::get<T>(values.at(key));
|
||||
}
|
||||
|
||||
ConfigValue Config::get(const char* key) const {
|
||||
auto it = values.find(key);
|
||||
return it->second;
|
||||
}
|
||||
|
||||
bool Config::hasKey(const char* key) {
|
||||
auto it = values.find(key);
|
||||
return ! (it == values.end());
|
||||
}
|
||||
|
||||
uint8_t Config::getByte(const char* key) const {
|
||||
auto it = values.find(key);
|
||||
if (it == values.end()) {
|
||||
@@ -249,13 +246,14 @@ int32_t Config::getInt(const char* key) const {
|
||||
|
||||
bool Config::getBool(const char* key) const {
|
||||
auto it = values.find(key);
|
||||
if (it == values.end())
|
||||
if (it == values.end()) {
|
||||
LOGE(TAG, "Missing config key: %s", key);
|
||||
abort();
|
||||
error_abort();
|
||||
}
|
||||
if (auto v = std::get_if<bool>(&it->second))
|
||||
return *v;
|
||||
LOGE(TAG, "Type mismatch for key: %s", key);
|
||||
abort();
|
||||
error_abort();
|
||||
}
|
||||
|
||||
float Config::getFloat(const char* key) const {
|
||||
@@ -297,3 +295,94 @@ const String& Config::getString(const char* key) const {
|
||||
const char* Config::getCString(const char* key) const {
|
||||
return getString(key).c_str();
|
||||
}
|
||||
|
||||
bool Config::setValue(const char* key, const char* value) {
|
||||
// sets data associated to a key to a new value
|
||||
// does not write back to preferences, that has to be done
|
||||
// separately
|
||||
LOGD(TAG, "setting: %s to %s", key, value);
|
||||
bool success = false;
|
||||
char* end;
|
||||
unsigned long byte_temp;
|
||||
long int_temp;
|
||||
bool bool_temp;
|
||||
float float_temp;
|
||||
switch (defs[key]->type) {
|
||||
case ConfigType::BYTE:
|
||||
byte_temp = strtoul(value, &end, 10);
|
||||
if (*end != '\0') {
|
||||
LOGW(TAG, "not a number");
|
||||
break;
|
||||
}
|
||||
if (temp > 255) {
|
||||
LOGW(TAG, "byte out of range");
|
||||
break;
|
||||
}
|
||||
values[key] = static_cast<uint8_t>(byte_temp);
|
||||
LOGD(TAG, "converted to BYTE");
|
||||
success = true;
|
||||
break;
|
||||
case ConfigType::SHORT:
|
||||
int_temp = strtoul(value, &end, 10);
|
||||
if (*end != '\0') {
|
||||
LOGW(TAG, "not a number");
|
||||
break;
|
||||
}
|
||||
if (temp < INT16_MIN || temp > INT16_MAX) {
|
||||
LOGW(TAG, "short out of range");
|
||||
break;
|
||||
}
|
||||
values[key] = static_cast<int16_t>(int_temp);
|
||||
LOGD(TAG, "converted to SHORT");
|
||||
success = true;
|
||||
break;
|
||||
case ConfigType::INT:
|
||||
int_temp = strtoul(value, &end, 10);
|
||||
if (*end != '\0') {
|
||||
LOGW(TAG, "not a number");
|
||||
break;
|
||||
}
|
||||
if (temp < INT32_MIN || temp > INT32_MAX) {
|
||||
LOGW(TAG, "integer out of range");
|
||||
break;
|
||||
}
|
||||
values[key] = static_cast<int16_t>(int_temp);
|
||||
LOGD(TAG, "converted to INT");
|
||||
success = true;
|
||||
break;
|
||||
case ConfigType::BOOL:
|
||||
if ((value[0] == '1' && value[1] == '\0') || (strcasecmp(value, "true") == 0)) {
|
||||
bool_temp = true;
|
||||
} else if ((value[0] == '0' && value[1] == '\0') || (strcasecmp(value, "false") == 0)) {
|
||||
bool_temp = false;
|
||||
} else {
|
||||
LOGW(TAG, "invalid value for boolean");
|
||||
break;
|
||||
}
|
||||
values[key] = bool_temp;
|
||||
LOGD(TAG, "converted to BOOL");
|
||||
success = true;
|
||||
break;
|
||||
case ConfigType::FLOAT:
|
||||
float_temp = strtof(value, &end);
|
||||
if (*end != '\0') {
|
||||
LOGW(TAG, "invalid float");
|
||||
break;
|
||||
}
|
||||
values[key] = float_temp;
|
||||
LOGD(TAG, "converted to FLOAT");
|
||||
success = true;
|
||||
break;
|
||||
case ConfigType::CHAR:
|
||||
values[key] = value[0];
|
||||
LOGD(TAG, "converted to CHAR");
|
||||
success = true;
|
||||
break;
|
||||
case ConfigType::STRING:
|
||||
values[key] = String(value);
|
||||
LOGD(TAG, "converted to STRING");
|
||||
success = true;
|
||||
break;
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
44
src/main.cpp
44
src/main.cpp
@@ -40,6 +40,7 @@ uint8_t loglevel = 5;
|
||||
const char* wifi_ssid = "OBPKP61";
|
||||
const char* wifi_pass = "keypad61";
|
||||
bool ap_enabled = false;
|
||||
bool ap_hidden = false;
|
||||
|
||||
unsigned long firstStart = 0;
|
||||
unsigned long lastSensor = 0;
|
||||
@@ -248,33 +249,20 @@ void setup() {
|
||||
}
|
||||
|
||||
// N2K basics
|
||||
nodeid = N2K_DEFAULT_NODEID;
|
||||
LOGI(TAG, "N2K default node is %d", nodeid);
|
||||
//preferences.begin(PREF_NAME, false);
|
||||
//nodeid = preferences.getInt("LastNodeId", N2K_DEFAULT_NODEID);
|
||||
//preferences.end();
|
||||
LOGI(TAG, "N2K default node is %d", N2K_DEFAULT_NODEID);
|
||||
nodeid = config.getByte("LastNodeId");
|
||||
LOGI(TAG, "N2K node id set to %d from preferences", nodeid);
|
||||
|
||||
//cpuspeed = preferences.getInt("cpuSpeed", 160);
|
||||
// some other settings of interest
|
||||
cpuspeed = config.getShort("cpuSpeed");
|
||||
//int apstoptime = preferences.getInt("stopApTime", 0);
|
||||
int16_t apstoptime = config.getShort("stopApTime");
|
||||
//String apip = preferences.getString("apIp", "192.168.15.1");
|
||||
//String apmask = preferences.getString("apMask", "255.255.255.0");
|
||||
String apip = config.getString("apIp");
|
||||
String apmask = config.getString("apMask");
|
||||
//preferences.end();
|
||||
|
||||
// Setup webserver
|
||||
WiFi.persistent(false);
|
||||
WiFi.mode(WIFI_MODE_AP);
|
||||
|
||||
int channel = WIFI_CHANNEL;
|
||||
bool hidden = false;
|
||||
// TODO do not enable if preferences apEnable = false
|
||||
// but prepare later switch on by config key
|
||||
WiFi.softAP(wifi_ssid, wifi_pass, channel, hidden, WIFI_MAX_STA);
|
||||
|
||||
// IPAddress ap_addr(192, 168, 15, 1);
|
||||
IPAddress ap_addr;
|
||||
@@ -287,7 +275,14 @@ void setup() {
|
||||
IPAddress ap_gateway(ap_addr);
|
||||
|
||||
WiFi.softAPConfig(ap_addr, ap_gateway, ap_subnet);
|
||||
ap_enabled = true;
|
||||
|
||||
// Only enable if preferences apEnable is true
|
||||
// But later switch on by config key is possible
|
||||
ap_hidden = config.getBool("apHidden");
|
||||
ap_enabled = config.getBool("apEnable");
|
||||
if (ap_enabled) {
|
||||
WiFi.softAP(wifi_ssid, wifi_pass, WIFI_CHANNEL, ap_hidden, WIFI_MAX_STA);
|
||||
}
|
||||
|
||||
// Initialize WebGUI
|
||||
webserver_init();
|
||||
@@ -309,12 +304,11 @@ void setup() {
|
||||
1 // LoadEquivalency (LEN)
|
||||
);
|
||||
|
||||
// TODO Read configuration information from preferences
|
||||
// Manufacturer information is not changeable
|
||||
NMEA2000.SetConfigurationInformation(
|
||||
"Open boat projects / NMEA2000 library", // Manufacturer
|
||||
"", // Info 1
|
||||
"" // Info 2
|
||||
"Open Boat Projects / NMEA2000 library", // Manufacturer
|
||||
config.getCString("instDesc1"), // Info 1
|
||||
config.getCString("instDesc2") // Info 2
|
||||
);
|
||||
|
||||
uint32_t uid; // ISO 21bit identity number devived from chipid (MAC)
|
||||
@@ -354,8 +348,6 @@ void setup() {
|
||||
// Debug: NMEA2000.EnableForward(true);
|
||||
NMEA2000.Open();
|
||||
|
||||
|
||||
|
||||
led_init();
|
||||
|
||||
// Buzzer
|
||||
@@ -373,7 +365,7 @@ void setup() {
|
||||
digitalWrite(RGBLED_R, LOW); // boot status off
|
||||
delay(500);
|
||||
led_test();
|
||||
|
||||
|
||||
// select current destination
|
||||
switch (destination) {
|
||||
case 'A':
|
||||
@@ -388,8 +380,6 @@ void setup() {
|
||||
}
|
||||
|
||||
// I²C
|
||||
// Serial.print("SHT31_LIB_VERSION: ");
|
||||
// Serial.println(SHT31_LIB_VERSION);
|
||||
LOGI(TAG, "SHT31_LIB_VERSION: %s", SHT31_LIB_VERSION);
|
||||
Wire.begin(I2C_SDA, I2C_SCL);
|
||||
Wire.setClock(I2C_SPEED);
|
||||
@@ -613,7 +603,7 @@ void loop() {
|
||||
ap_enabled = false;
|
||||
} else {
|
||||
Serial.println("Enable Accesspoint");
|
||||
WiFi.softAP(wifi_ssid, wifi_pass);
|
||||
WiFi.softAP(wifi_ssid, wifi_pass, WIFI_CHANNEL, ap_hidden, WIFI_MAX_STA);
|
||||
ap_enabled = true;
|
||||
}
|
||||
break;
|
||||
@@ -638,7 +628,7 @@ void loop() {
|
||||
}
|
||||
}
|
||||
|
||||
NMEA2000.loop();
|
||||
// NMEA2000.loop(); // not implemented yet
|
||||
NMEA2000.ParseMessages();
|
||||
|
||||
if ((millis() - lastSensor >= 5000) and sht_available) {
|
||||
|
||||
@@ -83,6 +83,7 @@ void webserver_init() {
|
||||
|
||||
// API fast hack
|
||||
server.on("/api/capabilities", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
LOGD(TAG, "capabilities called");
|
||||
StaticJsonDocument<100> doc;
|
||||
doc["apPwChange"] = "true";
|
||||
String out;
|
||||
@@ -91,6 +92,7 @@ void webserver_init() {
|
||||
});
|
||||
|
||||
server.on("/api/checkpass", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
LOGD(TAG, "checkpass called");
|
||||
StaticJsonDocument<100> doc;
|
||||
doc["status"] = "FAILED";
|
||||
String out;
|
||||
@@ -99,24 +101,28 @@ void webserver_init() {
|
||||
});
|
||||
|
||||
server.on("/api/config", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
LOGD(TAG, "config called");
|
||||
StaticJsonDocument<1024> doc;
|
||||
doc["systemName"] = config.getString("systemName");
|
||||
doc["systemMode"] = String(config.getChar("systemMode"));
|
||||
doc["instDesc1"] = config.getString("instDesc1");
|
||||
doc["instDesc2"] = config.getString("instDesc2");
|
||||
doc["logLevel"] = loglevel;
|
||||
doc["version"] = VERSION;
|
||||
doc["fwtype"] = "unknown"; // TODO ?
|
||||
doc["salt"] = "secret";
|
||||
doc["AdminPassword"] = "********";
|
||||
doc["useAdminPass"] = "false"; //config.getBool("useAdminPass") ? "true" : "false";
|
||||
doc["apEnable"] = "true";
|
||||
doc["useAdminPass"] = config.getBool("useAdminPass") ? "true" : "false";
|
||||
doc["apEnable"] = config.getBool("apEnable") ? "true" : "false";
|
||||
doc["apIp"] = config.getString("apIp");
|
||||
doc["apMask"] = config.getString("apMask");
|
||||
doc["apPassword"] = "********";
|
||||
doc["stopApTime"] = config.getShort("stopApTime");
|
||||
doc["apHidden"] = config.getBool("apHidden") ? "true" : "false";
|
||||
doc["cpuSpeed"] = 160;
|
||||
doc["tempFormat"] = String(config.getChar("tempFormat"));
|
||||
doc["ledBrightness"] = led_brightness;
|
||||
doc["ledRgbBrightness"] = rgb_brightness;
|
||||
doc["rgbBrightness"] = rgb_brightness;
|
||||
doc["switchBank"] = config.getByte("switchBank");
|
||||
doc["key1"] = keycode[BUTTON_1];
|
||||
doc["key2"] = keycode[BUTTON_2];
|
||||
@@ -140,6 +146,7 @@ void webserver_init() {
|
||||
});
|
||||
|
||||
server.on("/api/resetconfig", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
LOGD(TAG, "resetconfig called");
|
||||
StaticJsonDocument<100> doc;
|
||||
doc["status"] = "FAILED";
|
||||
String out;
|
||||
@@ -190,9 +197,37 @@ void webserver_init() {
|
||||
});
|
||||
|
||||
server.on("/api/setconfig", HTTP_POST, [](AsyncWebServerRequest *request) {
|
||||
LOGD(TAG, "API setconfig called");
|
||||
LOGD(TAG, "setconfig called");
|
||||
// TODO _hash must be first parameter
|
||||
int count = request->params();
|
||||
bool need_save = false;
|
||||
LOGD(TAG, "setconfig Received %d params", count);
|
||||
for (int i = 0; i < count; i++) {
|
||||
const AsyncWebParameter* p = request->getParam(i);
|
||||
if (!config.hasKey(p->name().c_str())) {
|
||||
LOGD(TAG, "POST %s=%s; key not found!", p->name(), p->value());
|
||||
continue;
|
||||
}
|
||||
LOGD(TAG, "POST %s=%s", p->name(), p->value());
|
||||
// get old value for comparison
|
||||
ConfigValue oldval = config.get(p->name().c_str());
|
||||
config.setValue(p->name().c_str(), p->value().c_str());
|
||||
// check if value was changed
|
||||
if (config.get(p->name().c_str()) == oldval) {
|
||||
// comparison of variants!
|
||||
LOGD(TAG, "Values are equal. No change detected.");
|
||||
} else {
|
||||
need_save = true;
|
||||
}
|
||||
}
|
||||
if (need_save) {
|
||||
LOGI(TAG, "Writing changed values to NVS");
|
||||
config.save();
|
||||
} else {
|
||||
LOGI(TAG, "No changes, no action taken");
|
||||
}
|
||||
StaticJsonDocument<100> doc;
|
||||
doc["status"] = "FAILED";
|
||||
doc["status"] = "OK";
|
||||
String out;
|
||||
serializeJson(doc, out);
|
||||
request->send(200, "application/json", out);
|
||||
@@ -201,13 +236,13 @@ void webserver_init() {
|
||||
server.on("/api/update", HTTP_POST, [](AsyncWebServerRequest *request) {
|
||||
// the request handler is triggered after the upload has finished...
|
||||
// create the response, add header, and send response
|
||||
|
||||
LOGD(TAG, "update called");
|
||||
StaticJsonDocument<100> doc;
|
||||
doc["status"] = "FAILED";
|
||||
String out;
|
||||
serializeJson(doc, out);
|
||||
request->send(200, "application/json", out);
|
||||
}, [](AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final){
|
||||
}, [](AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final) {
|
||||
// this is the new image upload part
|
||||
Serial.print("Retrieving firmware image named: ");
|
||||
Serial.println(filename);
|
||||
@@ -230,6 +265,7 @@ void webserver_init() {
|
||||
|
||||
server.on("/api/devicelist", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
// NMEA2000 device list
|
||||
LOGD(TAG, "devicelist called");
|
||||
AsyncResponseStream *response = request->beginResponseStream("application/json");
|
||||
response->print("[");
|
||||
bool first = true;
|
||||
|
||||
Reference in New Issue
Block a user