remove OriginID from state service

This commit is contained in:
Proddy
2024-02-12 11:22:07 +01:00
parent 65cf8005a4
commit 1f7c968d0d
20 changed files with 302 additions and 366 deletions

View File

@@ -80,7 +80,7 @@ class FSPersistence {
void enableUpdateHandler() { void enableUpdateHandler() {
if (!_updateHandlerId) { if (!_updateHandlerId) {
_updateHandlerId = _statefulService->addUpdateHandler([&](const String & originId) { writeToFS(); }); _updateHandlerId = _statefulService->addUpdateHandler([&] { writeToFS(); });
} }
} }

View File

@@ -58,7 +58,7 @@ class HttpEndpoint {
return; return;
} else if (outcome == StateUpdateResult::CHANGED || outcome == StateUpdateResult::CHANGED_RESTART) { } else if (outcome == StateUpdateResult::CHANGED || outcome == StateUpdateResult::CHANGED_RESTART) {
// persist changes // persist changes
request->onDisconnect([this]() { _statefulService->callUpdateHandlers(HTTP_ENDPOINT_ORIGIN_ID); }); request->onDisconnect([this] { _statefulService->callUpdateHandlers(); });
if (outcome == StateUpdateResult::CHANGED_RESTART) { if (outcome == StateUpdateResult::CHANGED_RESTART) {
request->send(205); // reboot required request->send(205); // reboot required
return; return;

View File

@@ -36,7 +36,7 @@ MqttSettingsService::MqttSettingsService(AsyncWebServer * server, FS * fs, Secur
, _disconnectReason(espMqttClientTypes::DisconnectReason::TCP_DISCONNECTED) , _disconnectReason(espMqttClientTypes::DisconnectReason::TCP_DISCONNECTED)
, _mqttClient(nullptr) { , _mqttClient(nullptr) {
WiFi.onEvent(std::bind(&MqttSettingsService::WiFiEvent, this, _1, _2)); WiFi.onEvent(std::bind(&MqttSettingsService::WiFiEvent, this, _1, _2));
addUpdateHandler([&](const String & originId) { onConfigUpdated(); }, false); addUpdateHandler([&] { onConfigUpdated(); }, false);
} }
MqttSettingsService::~MqttSettingsService() { MqttSettingsService::~MqttSettingsService() {

View File

@@ -14,7 +14,7 @@ NTPSettingsService::NTPSettingsService(AsyncWebServer * server, FS * fs, Securit
WiFi.onEvent(std::bind(&NTPSettingsService::WiFiEvent, this, _1)); WiFi.onEvent(std::bind(&NTPSettingsService::WiFiEvent, this, _1));
addUpdateHandler([&](const String & originId) { configureNTP(); }, false); addUpdateHandler([&] { configureNTP(); }, false);
} }
void NTPSettingsService::begin() { void NTPSettingsService::begin() {

View File

@@ -8,7 +8,7 @@ NetworkSettingsService::NetworkSettingsService(AsyncWebServer * server, FS * fs,
: _httpEndpoint(NetworkSettings::read, NetworkSettings::update, this, server, NETWORK_SETTINGS_SERVICE_PATH, securityManager) : _httpEndpoint(NetworkSettings::read, NetworkSettings::update, this, server, NETWORK_SETTINGS_SERVICE_PATH, securityManager)
, _fsPersistence(NetworkSettings::read, NetworkSettings::update, this, fs, NETWORK_SETTINGS_FILE) , _fsPersistence(NetworkSettings::read, NetworkSettings::update, this, fs, NETWORK_SETTINGS_FILE)
, _lastConnectionAttempt(0) { , _lastConnectionAttempt(0) {
addUpdateHandler([&](const String & originId) { reconfigureWiFiConnection(); }, false); addUpdateHandler([&] { reconfigureWiFiConnection(); }, false);
// wifi event callbacks // wifi event callbacks
WiFi.onEvent(std::bind(&NetworkSettingsService::WiFiEvent, this, _1, _2)); WiFi.onEvent(std::bind(&NetworkSettingsService::WiFiEvent, this, _1, _2));
} }
@@ -75,6 +75,7 @@ void NetworkSettingsService::manageSTA() {
if (_state.nosleep) { if (_state.nosleep) {
WiFi.setSleep(false); // turn off sleep - WIFI_PS_NONE WiFi.setSleep(false); // turn off sleep - WIFI_PS_NONE
} }
// attempt to connect to the network // attempt to connect to the network
uint mac[6]; uint mac[6];
if (!_state.bssid.isEmpty() && sscanf(_state.bssid.c_str(), "%X:%X:%X:%X:%X:%X", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]) == 6) { if (!_state.bssid.isEmpty() && sscanf(_state.bssid.c_str(), "%X:%X:%X:%X:%X:%X", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]) == 6) {
@@ -92,11 +93,12 @@ void NetworkSettingsService::manageSTA() {
// v1 needs this value, see https://github.com/emsesp/EMS-ESP32/pull/620#discussion_r993173979 // v1 needs this value, see https://github.com/emsesp/EMS-ESP32/pull/620#discussion_r993173979
// https://www.wemos.cc/en/latest/c3/c3_mini_1_0_0.html#about-wifi // https://www.wemos.cc/en/latest/c3/c3_mini_1_0_0.html#about-wifi
WiFi.setTxPower(WIFI_POWER_8_5dBm); WiFi.setTxPower(WIFI_POWER_8_5dBm);
return;
#else #else
if (_state.tx_power != 0) { if (_state.tx_power != 0) {
// if not set to Auto (0) set the Tx power now // if not set to Auto (0) set the Tx power now
WiFi.setTxPower((wifi_power_t)_state.tx_power); if (!WiFi.setTxPower((wifi_power_t)_state.tx_power)) {
emsesp::EMSESP::logger().warning("Failed to set WiFi Tx Power");
}
} }
#endif #endif
} else { // not connected but STA-mode active => disconnect } else { // not connected but STA-mode active => disconnect
@@ -174,7 +176,9 @@ void NetworkSettingsService::setWiFiPowerOnRSSI() {
emsesp::EMSESP::logger().info("Setting WiFi Tx Power to %s dBm", emsesp::Helpers::render_value(result, (double)(p / 4), 1)); emsesp::EMSESP::logger().info("Setting WiFi Tx Power to %s dBm", emsesp::Helpers::render_value(result, (double)(p / 4), 1));
#endif #endif
WiFi.setTxPower(p); if (!WiFi.setTxPower(p)) {
emsesp::EMSESP::logger().warning("Failed to set WiFi Tx Power");
}
} }
// start the multicast UDP service so EMS-ESP is discoverable via .local // start the multicast UDP service so EMS-ESP is discoverable via .local
@@ -184,7 +188,7 @@ void NetworkSettingsService::mDNS_start() const {
if (_state.enableMDNS) { if (_state.enableMDNS) {
if (!MDNS.begin(emsesp::EMSESP::system_.hostname().c_str())) { if (!MDNS.begin(emsesp::EMSESP::system_.hostname().c_str())) {
emsesp::EMSESP::logger().warning("Failed to start mDNS responder service"); emsesp::EMSESP::logger().warning("Failed to start mDNS Responder service");
return; return;
} }
@@ -196,11 +200,11 @@ void NetworkSettingsService::mDNS_start() const {
MDNS.addServiceTxt("http", "tcp", "version", EMSESP_APP_VERSION); MDNS.addServiceTxt("http", "tcp", "version", EMSESP_APP_VERSION);
MDNS.addServiceTxt("http", "tcp", "address", address_s.c_str()); MDNS.addServiceTxt("http", "tcp", "address", address_s.c_str());
emsesp::EMSESP::logger().info("mDNS responder service started"); emsesp::EMSESP::logger().info("mDNS Responder service started");
} }
#else #else
if (_state.enableMDNS) { if (_state.enableMDNS) {
EMSESP::logger().info("mDNS responder service started"); EMSESP::logger().info("mDNS Responder service started");
} }
#endif #endif
} }

View File

@@ -9,7 +9,7 @@ OTASettingsService::OTASettingsService(AsyncWebServer * server, FS * fs, Securit
, _fsPersistence(OTASettings::read, OTASettings::update, this, fs, OTA_SETTINGS_FILE) , _fsPersistence(OTASettings::read, OTASettings::update, this, fs, OTA_SETTINGS_FILE)
, _arduinoOTA(nullptr) { , _arduinoOTA(nullptr) {
WiFi.onEvent(std::bind(&OTASettingsService::WiFiEvent, this, _1, _2)); WiFi.onEvent(std::bind(&OTASettingsService::WiFiEvent, this, _1, _2));
addUpdateHandler([&](const String & originId) { configureArduinoOTA(); }, false); addUpdateHandler([&] { configureArduinoOTA(); }, false);
} }
void OTASettingsService::begin() { void OTASettingsService::begin() {
@@ -35,8 +35,8 @@ void OTASettingsService::configureArduinoOTA() {
_arduinoOTA->setPort(_state.port); _arduinoOTA->setPort(_state.port);
_arduinoOTA->setPassword(_state.password.c_str()); _arduinoOTA->setPassword(_state.password.c_str());
_arduinoOTA->onStart([]() { emsesp::EMSESP::system_.upload_status(true); }); _arduinoOTA->onStart([] { emsesp::EMSESP::system_.upload_status(true); });
_arduinoOTA->onEnd([]() { emsesp::EMSESP::system_.upload_status(false); }); _arduinoOTA->onEnd([] { emsesp::EMSESP::system_.upload_status(false); });
_arduinoOTA->onProgress([](unsigned int progress, unsigned int total) { _arduinoOTA->onProgress([](unsigned int progress, unsigned int total) {
// Serial.printf("Progress: %u%%\r\n", (progress / (total / 100))); // Serial.printf("Progress: %u%%\r\n", (progress / (total / 100)));

View File

@@ -6,7 +6,7 @@ SecuritySettingsService::SecuritySettingsService(AsyncWebServer * server, FS * f
: _httpEndpoint(SecuritySettings::read, SecuritySettings::update, this, server, SECURITY_SETTINGS_PATH, this) : _httpEndpoint(SecuritySettings::read, SecuritySettings::update, this, server, SECURITY_SETTINGS_PATH, this)
, _fsPersistence(SecuritySettings::read, SecuritySettings::update, this, fs, SECURITY_SETTINGS_FILE) , _fsPersistence(SecuritySettings::read, SecuritySettings::update, this, fs, SECURITY_SETTINGS_FILE)
, _jwtHandler(FACTORY_JWT_SECRET) { , _jwtHandler(FACTORY_JWT_SECRET) {
addUpdateHandler([&](const String & originId) { configureJWTHandler(); }, false); addUpdateHandler([&] { configureJWTHandler(); }, false);
server->on(GENERATE_TOKEN_PATH, server->on(GENERATE_TOKEN_PATH,
HTTP_GET, HTTP_GET,
wrapRequest(std::bind(&SecuritySettingsService::generateToken, this, std::placeholders::_1), AuthenticationPredicates::IS_ADMIN)); wrapRequest(std::bind(&SecuritySettingsService::generateToken, this, std::placeholders::_1), AuthenticationPredicates::IS_ADMIN));

View File

@@ -24,7 +24,7 @@ template <typename T>
using JsonStateReader = std::function<void(T & settings, JsonObject root)>; using JsonStateReader = std::function<void(T & settings, JsonObject root)>;
typedef size_t update_handler_id_t; typedef size_t update_handler_id_t;
typedef std::function<void(const String & originId)> StateUpdateCallback; typedef std::function<void()> StateUpdateCallback;
typedef struct StateUpdateHandlerInfo { typedef struct StateUpdateHandlerInfo {
static update_handler_id_t currentUpdatedHandlerId; static update_handler_id_t currentUpdatedHandlerId;
@@ -33,7 +33,7 @@ typedef struct StateUpdateHandlerInfo {
bool _allowRemove; bool _allowRemove;
StateUpdateHandlerInfo(StateUpdateCallback cb, bool allowRemove) StateUpdateHandlerInfo(StateUpdateCallback cb, bool allowRemove)
: _id(++currentUpdatedHandlerId) : _id(++currentUpdatedHandlerId)
, _cb(cb) , _cb(std::move(cb))
, _allowRemove(allowRemove){}; , _allowRemove(allowRemove){};
} StateUpdateHandlerInfo_t; } StateUpdateHandlerInfo_t;
@@ -41,7 +41,7 @@ template <class T>
class StatefulService { class StatefulService {
public: public:
template <typename... Args> template <typename... Args>
StatefulService(Args &&... args) explicit StatefulService(Args &&... args)
: _state(std::forward<Args>(args)...) : _state(std::forward<Args>(args)...)
, _accessMutex(xSemaphoreCreateRecursiveMutex()) { , _accessMutex(xSemaphoreCreateRecursiveMutex()) {
} }
@@ -50,27 +50,28 @@ class StatefulService {
if (!cb) { if (!cb) {
return 0; return 0;
} }
StateUpdateHandlerInfo_t updateHandler(cb, allowRemove); StateUpdateHandlerInfo_t updateHandler(std::move(cb), allowRemove);
_updateHandlers.push_back(updateHandler); _updateHandlers.push_back(std::move(updateHandler));
return updateHandler._id; return updateHandler._id;
} }
void removeUpdateHandler(update_handler_id_t id) { void removeUpdateHandler(update_handler_id_t id) {
for (auto i = _updateHandlers.begin(); i != _updateHandlers.end();) { for (auto it = _updateHandlers.begin(); it != _updateHandlers.end();) {
if ((*i)._allowRemove && (*i)._id == id) { auto & elem = *it;
i = _updateHandlers.erase(i); if (elem._allowRemove && elem._id == id) {
it = _updateHandlers.erase(it);
} else { } else {
++i; ++it;
} }
} }
} }
StateUpdateResult update(std::function<StateUpdateResult(T &)> stateUpdater, const String & originId) { StateUpdateResult update(std::function<StateUpdateResult(T &)> stateUpdater) {
beginTransaction(); beginTransaction();
StateUpdateResult result = stateUpdater(_state); StateUpdateResult result = stateUpdater(_state);
endTransaction(); endTransaction();
if (result == StateUpdateResult::CHANGED) { if (result == StateUpdateResult::CHANGED) {
callUpdateHandlers(originId); callUpdateHandlers();
} }
return result; return result;
} }
@@ -82,12 +83,12 @@ class StatefulService {
return result; return result;
} }
StateUpdateResult update(JsonObject jsonObject, JsonStateUpdater<T> stateUpdater, const String & originId) { StateUpdateResult update(JsonObject jsonObject, JsonStateUpdater<T> stateUpdater) {
beginTransaction(); beginTransaction();
StateUpdateResult result = stateUpdater(jsonObject, _state); StateUpdateResult result = stateUpdater(jsonObject, _state);
endTransaction(); endTransaction();
if (result == StateUpdateResult::CHANGED) { if (result == StateUpdateResult::CHANGED) {
callUpdateHandlers(originId); callUpdateHandlers();
} }
return result; return result;
} }
@@ -111,9 +112,9 @@ class StatefulService {
endTransaction(); endTransaction();
} }
void callUpdateHandlers(const String & originId) { void callUpdateHandlers() {
for (const StateUpdateHandlerInfo_t & updateHandler : _updateHandlers) { for (const StateUpdateHandlerInfo_t & updateHandler : _updateHandlers) {
updateHandler._cb(originId); updateHandler._cb();
} }
} }
@@ -131,7 +132,6 @@ class StatefulService {
private: private:
SemaphoreHandle_t _accessMutex; SemaphoreHandle_t _accessMutex;
std::vector<StateUpdateHandlerInfo_t> _updateHandlers; std::vector<StateUpdateHandlerInfo_t> _updateHandlers;
// std::list<StateUpdateHandlerInfo_t> _updateHandlers;
}; };
#endif #endif

View File

@@ -40,7 +40,7 @@ class FSPersistence {
void enableUpdateHandler() { void enableUpdateHandler() {
if (!_updateHandlerId) { if (!_updateHandlerId) {
_updateHandlerId = _statefulService->addUpdateHandler([&](const String & originId) { writeToFS(); }); _updateHandlerId = _statefulService->addUpdateHandler([&]() { writeToFS(); });
} }
} }

View File

@@ -21,7 +21,7 @@ template <typename T>
using JsonStateReader = std::function<void(T & settings, JsonObject root)>; using JsonStateReader = std::function<void(T & settings, JsonObject root)>;
typedef size_t update_handler_id_t; typedef size_t update_handler_id_t;
typedef std::function<void(const String & originId)> StateUpdateCallback; typedef std::function<void()> StateUpdateCallback;
typedef struct StateUpdateHandlerInfo { typedef struct StateUpdateHandlerInfo {
static update_handler_id_t currentUpdatedHandlerId; static update_handler_id_t currentUpdatedHandlerId;
@@ -68,12 +68,12 @@ class StatefulService {
} }
} }
StateUpdateResult update(std::function<StateUpdateResult(T &)> stateUpdater, const String & originId) { StateUpdateResult update(std::function<StateUpdateResult(T &)> stateUpdater, ) {
beginTransaction(); beginTransaction();
StateUpdateResult result = stateUpdater(_state); StateUpdateResult result = stateUpdater(_state);
endTransaction(); endTransaction();
if (result == StateUpdateResult::CHANGED) { if (result == StateUpdateResult::CHANGED) {
callUpdateHandlers(originId); callUpdateHandlers();
} }
return result; return result;
} }
@@ -85,12 +85,12 @@ class StatefulService {
return result; return result;
} }
StateUpdateResult update(JsonObject jsonObject, JsonStateUpdater<T> stateUpdater, const String & originId) { StateUpdateResult update(JsonObject jsonObject, JsonStateUpdater<T> stateUpdater, ) {
beginTransaction(); beginTransaction();
StateUpdateResult result = stateUpdater(jsonObject, _state); StateUpdateResult result = stateUpdater(jsonObject, _state);
endTransaction(); endTransaction();
if (result == StateUpdateResult::CHANGED) { if (result == StateUpdateResult::CHANGED) {
callUpdateHandlers(originId); callUpdateHandlers();
} }
return result; return result;
} }
@@ -114,9 +114,9 @@ class StatefulService {
endTransaction(); endTransaction();
} }
void callUpdateHandlers(const String & originId) { void callUpdateHandlers() {
for (const StateUpdateHandlerInfo_t & updateHandler : _updateHandlers) { for (const StateUpdateHandlerInfo_t & updateHandler : _updateHandlers) {
updateHandler._cb(originId); updateHandler._cb();
} }
} }

View File

@@ -321,8 +321,7 @@ void AnalogSensor::loop() {
bool AnalogSensor::update(uint8_t gpio, const std::string & name, double offset, double factor, uint8_t uom, int8_t type, bool deleted) { bool AnalogSensor::update(uint8_t gpio, const std::string & name, double offset, double factor, uint8_t uom, int8_t type, bool deleted) {
// first see if we can find the sensor in our customization list // first see if we can find the sensor in our customization list
bool found_sensor = false; bool found_sensor = false;
EMSESP::webCustomizationService.update( EMSESP::webCustomizationService.update([&](WebCustomization & settings) {
[&](WebCustomization & settings) {
for (auto & AnalogCustomization : settings.analogCustomizations) { for (auto & AnalogCustomization : settings.analogCustomizations) {
if (AnalogCustomization.type == AnalogType::COUNTER || AnalogCustomization.type >= AnalogType::DIGITAL_OUT) { if (AnalogCustomization.type == AnalogType::COUNTER || AnalogCustomization.type >= AnalogType::DIGITAL_OUT) {
Command::erase_command(EMSdevice::DeviceType::ANALOGSENSOR, AnalogCustomization.name.c_str()); Command::erase_command(EMSdevice::DeviceType::ANALOGSENSOR, AnalogCustomization.name.c_str());
@@ -350,8 +349,7 @@ bool AnalogSensor::update(uint8_t gpio, const std::string & name, double offset,
} }
} }
return StateUpdateResult::UNCHANGED; return StateUpdateResult::UNCHANGED;
}, });
"local");
// if the sensor exists and we're using HA, delete the old HA record // if the sensor exists and we're using HA, delete the old HA record
if (found_sensor && Mqtt::ha_enabled()) { if (found_sensor && Mqtt::ha_enabled()) {
@@ -360,8 +358,7 @@ bool AnalogSensor::update(uint8_t gpio, const std::string & name, double offset,
// we didn't find it, it's new, so create and store it in the customization list // we didn't find it, it's new, so create and store it in the customization list
if (!found_sensor) { if (!found_sensor) {
EMSESP::webCustomizationService.update( EMSESP::webCustomizationService.update([&](WebCustomization & settings) {
[&](WebCustomization & settings) {
auto newSensor = AnalogCustomization(); auto newSensor = AnalogCustomization();
newSensor.gpio = gpio; newSensor.gpio = gpio;
newSensor.name = name; newSensor.name = name;
@@ -372,8 +369,7 @@ bool AnalogSensor::update(uint8_t gpio, const std::string & name, double offset,
settings.analogCustomizations.push_back(newSensor); settings.analogCustomizations.push_back(newSensor);
LOG_DEBUG("Adding new customization for analog sensor GPIO %02d", gpio); LOG_DEBUG("Adding new customization for analog sensor GPIO %02d", gpio);
return StateUpdateResult::CHANGED; // persist the change return StateUpdateResult::CHANGED; // persist the change
}, });
"local");
} }
// reloads the sensors in the customizations file into the sensors list // reloads the sensors in the customizations file into the sensors list
@@ -818,8 +814,7 @@ bool AnalogSensor::command_setvalue(const char * value, const int8_t gpio) {
return false; return false;
} }
if (oldoffset != sensor.offset()) { if (oldoffset != sensor.offset()) {
EMSESP::webCustomizationService.update( EMSESP::webCustomizationService.update([&](WebCustomization & settings) {
[&](WebCustomization & settings) {
for (auto & AnalogCustomization : settings.analogCustomizations) { for (auto & AnalogCustomization : settings.analogCustomizations) {
if (AnalogCustomization.gpio == sensor.gpio() && AnalogCustomization.type == sensor.type()) { if (AnalogCustomization.gpio == sensor.gpio() && AnalogCustomization.type == sensor.type()) {
AnalogCustomization.offset = sensor.offset(); AnalogCustomization.offset = sensor.offset();
@@ -830,8 +825,7 @@ bool AnalogSensor::command_setvalue(const char * value, const int8_t gpio) {
} else { } else {
return StateUpdateResult::CHANGED; // persist the change return StateUpdateResult::CHANGED; // persist the change
} }
}, });
"local");
publish_sensor(sensor); publish_sensor(sensor);
changed_ = true; changed_ = true;
} }

View File

@@ -184,12 +184,10 @@ static void setup_commands(std::shared_ptr<Commands> & commands) {
shell.enter_password(F_(new_password_prompt2), [password1](Shell & shell, bool completed, const std::string & password2) { shell.enter_password(F_(new_password_prompt2), [password1](Shell & shell, bool completed, const std::string & password2) {
if (completed) { if (completed) {
if (password1 == password2) { if (password1 == password2) {
to_app(shell).esp8266React.getSecuritySettingsService()->update( to_app(shell).esp8266React.getSecuritySettingsService()->update([&](SecuritySettings & securitySettings) {
[&](SecuritySettings & securitySettings) {
securitySettings.jwtSecret = password2.c_str(); securitySettings.jwtSecret = password2.c_str();
return StateUpdateResult::CHANGED; return StateUpdateResult::CHANGED;
}, });
"local");
shell.println("Admin password updated"); shell.println("Admin password updated");
} else { } else {
shell.println("Passwords do not match"); shell.println("Passwords do not match");
@@ -258,12 +256,10 @@ static void setup_commands(std::shared_ptr<Commands> & commands) {
shell.println("The network connection will be reset..."); shell.println("The network connection will be reset...");
Shell::loop_all(); Shell::loop_all();
delay(1000); // wait a second delay(1000); // wait a second
to_app(shell).esp8266React.getNetworkSettingsService()->update( to_app(shell).esp8266React.getNetworkSettingsService()->update([&](NetworkSettings & networkSettings) {
[&](NetworkSettings & networkSettings) {
networkSettings.hostname = arguments.front().c_str(); networkSettings.hostname = arguments.front().c_str();
return StateUpdateResult::CHANGED; return StateUpdateResult::CHANGED;
}, });
"local");
}); });
commands->add_command(ShellContext::MAIN, commands->add_command(ShellContext::MAIN,
@@ -293,8 +289,7 @@ static void setup_commands(std::shared_ptr<Commands> & commands) {
if (arguments.size() == 2 && Helpers::toLower(arguments.back()) == "nvs") { if (arguments.size() == 2 && Helpers::toLower(arguments.back()) == "nvs") {
to_app(shell).nvs_.putString("boot", board_profile.c_str()); to_app(shell).nvs_.putString("boot", board_profile.c_str());
} }
to_app(shell).webSettingsService.update( to_app(shell).webSettingsService.update([&](WebSettings & settings) {
[&](WebSettings & settings) {
settings.board_profile = board_profile.c_str(); settings.board_profile = board_profile.c_str();
settings.led_gpio = data[0]; settings.led_gpio = data[0];
settings.dallas_gpio = data[1]; settings.dallas_gpio = data[1];
@@ -306,8 +301,7 @@ static void setup_commands(std::shared_ptr<Commands> & commands) {
settings.eth_phy_addr = data[7]; settings.eth_phy_addr = data[7];
settings.eth_clock_mode = data[8]; settings.eth_clock_mode = data[8];
return StateUpdateResult::CHANGED; return StateUpdateResult::CHANGED;
}, });
"local");
shell.printfln("Loaded board profile %s", board_profile.c_str()); shell.printfln("Loaded board profile %s", board_profile.c_str());
to_app(shell).system_.network_init(true); to_app(shell).system_.network_init(true);
}); });
@@ -320,13 +314,11 @@ static void setup_commands(std::shared_ptr<Commands> & commands) {
[](Shell & shell, const std::vector<std::string> & arguments) { [](Shell & shell, const std::vector<std::string> & arguments) {
uint8_t device_id = Helpers::hextoint(arguments.front().c_str()); uint8_t device_id = Helpers::hextoint(arguments.front().c_str());
if ((device_id == 0x0B) || (device_id == 0x0D) || (device_id == 0x0A) || (device_id == 0x0F) || (device_id == 0x12)) { if ((device_id == 0x0B) || (device_id == 0x0D) || (device_id == 0x0A) || (device_id == 0x0F) || (device_id == 0x12)) {
to_app(shell).webSettingsService.update( to_app(shell).webSettingsService.update([&](WebSettings & settings) {
[&](WebSettings & settings) {
settings.ems_bus_id = device_id; settings.ems_bus_id = device_id;
shell.printfln(F_(bus_id_fmt), settings.ems_bus_id); shell.printfln(F_(bus_id_fmt), settings.ems_bus_id);
return StateUpdateResult::CHANGED; return StateUpdateResult::CHANGED;
}, });
"local");
} else { } else {
shell.println("Must be 0B, 0D, 0A, 0E, 0F, or 48 - 4D"); shell.println("Must be 0B, 0D, 0A, 0E, 0F, or 48 - 4D");
} }
@@ -342,13 +334,11 @@ static void setup_commands(std::shared_ptr<Commands> & commands) {
[](Shell & shell, const std::vector<std::string> & arguments) { [](Shell & shell, const std::vector<std::string> & arguments) {
uint8_t tx_mode = std::strtol(arguments[0].c_str(), nullptr, 10); uint8_t tx_mode = std::strtol(arguments[0].c_str(), nullptr, 10);
// save the tx_mode // save the tx_mode
to_app(shell).webSettingsService.update( to_app(shell).webSettingsService.update([&](WebSettings & settings) {
[&](WebSettings & settings) {
settings.tx_mode = tx_mode; settings.tx_mode = tx_mode;
shell.printfln(F_(tx_mode_fmt), settings.tx_mode); shell.printfln(F_(tx_mode_fmt), settings.tx_mode);
return StateUpdateResult::CHANGED; return StateUpdateResult::CHANGED;
}, });
"local");
to_app(shell).uart_init(); to_app(shell).uart_init();
}); });

View File

@@ -1047,12 +1047,10 @@ bool Solar::set_SM10MaxFlow(const char * value, const int8_t id) {
return false; return false;
} }
maxFlow_ = (flow * 10); maxFlow_ = (flow * 10);
EMSESP::webSettingsService.update( EMSESP::webSettingsService.update([&](WebSettings & settings) {
[&](WebSettings & settings) {
settings.solar_maxflow = maxFlow_; settings.solar_maxflow = maxFlow_;
return StateUpdateResult::CHANGED; return StateUpdateResult::CHANGED;
}, });
"local");
return true; return true;
} }

View File

@@ -208,8 +208,7 @@ bool System::command_syslog_level(const char * value, const int8_t id) {
changed = true; changed = true;
} }
return StateUpdateResult::CHANGED; return StateUpdateResult::CHANGED;
}, });
"local");
if (changed) { if (changed) {
EMSESP::system_.syslog_init(); EMSESP::system_.syslog_init();
} }
@@ -279,7 +278,7 @@ void System::wifi_reconnect() {
Shell::loop_all(); Shell::loop_all();
delay(1000); // wait a second delay(1000); // wait a second
EMSESP::webSettingsService.save(); // save local settings EMSESP::webSettingsService.save(); // save local settings
EMSESP::esp8266React.getNetworkSettingsService()->callUpdateHandlers("local"); // in case we've changed ssid or password EMSESP::esp8266React.getNetworkSettingsService()->callUpdateHandlers(); // in case we've changed ssid or password
} }
// format the FS. Wipes everything. // format the FS. Wipes everything.
@@ -386,33 +385,6 @@ void System::reload_settings() {
}); });
} }
// adjust WiFi settings
// this for problem solving mesh and connection issues, and also get EMS bus-powered more stable by lowering power
void System::wifi_tweak() {
#if defined(EMSESP_WIFI_TWEAK)
// Default Tx Power is 80 = 20dBm <-- default
// WIFI_POWER_19_5dBm = 78,// 19.5dBm
// WIFI_POWER_19dBm = 76,// 19dBm
// WIFI_POWER_18_5dBm = 74,// 18.5dBm
// WIFI_POWER_17dBm = 68,// 17dBm
// WIFI_POWER_15dBm = 60,// 15dBm
// WIFI_POWER_13dBm = 52,// 13dBm
// WIFI_POWER_11dBm = 44,// 11dBm
// WIFI_POWER_8_5dBm = 34,// 8.5dBm
// WIFI_POWER_7dBm = 28,// 7dBm
// WIFI_POWER_5dBm = 20,// 5dBm
// WIFI_POWER_2dBm = 8,// 2dBm
// WIFI_POWER_MINUS_1dBm = -4// -1dBm
wifi_power_t p1 = WiFi.getTxPower();
(void)WiFi.setTxPower(WIFI_POWER_17dBm);
wifi_power_t p2 = WiFi.getTxPower();
bool s1 = WiFi.getSleep();
WiFi.setSleep(false); // turn off sleep - WIFI_PS_NONE
bool s2 = WiFi.getSleep();
LOG_DEBUG("Adjusting WiFi - Tx power %d->%d, Sleep %d->%d", p1, p2, s1, s2);
#endif
}
// check for valid ESP32 pins. This is very dependent on which ESP32 board is being used. // check for valid ESP32 pins. This is very dependent on which ESP32 board is being used.
// Typically you can't use 1, 6-11, 20, 24, 28-31 and 40+ // Typically you can't use 1, 6-11, 20, 24, 28-31 and 40+
// we allow 0 as it has a special function on the NodeMCU apparently // we allow 0 as it has a special function on the NodeMCU apparently
@@ -1134,25 +1106,21 @@ bool System::check_upgrade(bool factory_settings) {
// if we're coming from 3.4.4 or 3.5.0b14 which had no version stored then we need to apply new settings // if we're coming from 3.4.4 or 3.5.0b14 which had no version stored then we need to apply new settings
if (missing_version) { if (missing_version) {
LOG_INFO("Setting MQTT Entity ID format to v3.4 format"); LOG_INFO("Setting MQTT Entity ID format to v3.4 format");
EMSESP::esp8266React.getMqttSettingsService()->update( EMSESP::esp8266React.getMqttSettingsService()->update([&](MqttSettings & mqttSettings) {
[&](MqttSettings & mqttSettings) {
mqttSettings.entity_format = 0; // use old Entity ID format from v3.4 mqttSettings.entity_format = 0; // use old Entity ID format from v3.4
return StateUpdateResult::CHANGED; return StateUpdateResult::CHANGED;
}, });
"local");
} }
// Network Settings Wifi tx_power is now using the value * 4. // Network Settings Wifi tx_power is now using the value * 4.
EMSESP::esp8266React.getNetworkSettingsService()->update( EMSESP::esp8266React.getNetworkSettingsService()->update([&](NetworkSettings & networkSettings) {
[&](NetworkSettings & networkSettings) {
if (networkSettings.tx_power == 20) { if (networkSettings.tx_power == 20) {
networkSettings.tx_power = WIFI_POWER_19_5dBm; // use 19.5 as we don't have 20 anymore networkSettings.tx_power = WIFI_POWER_19_5dBm; // use 19.5 as we don't have 20 anymore
LOG_INFO("Setting WiFi TX Power to Auto"); LOG_INFO("Setting WiFi TX Power to Auto");
return StateUpdateResult::CHANGED; return StateUpdateResult::CHANGED;
} }
return StateUpdateResult::UNCHANGED; return StateUpdateResult::UNCHANGED;
}, });
"local");
} else if (this_version < settings_version) { } else if (this_version < settings_version) {
// need downgrade // need downgrade
@@ -1164,12 +1132,10 @@ bool System::check_upgrade(bool factory_settings) {
// if we did a change, set the new version and reboot // if we did a change, set the new version and reboot
if (save_version) { if (save_version) {
EMSESP::webSettingsService.update( EMSESP::webSettingsService.update([&](WebSettings & settings) {
[&](WebSettings & settings) {
settings.version = EMSESP_APP_VERSION; settings.version = EMSESP_APP_VERSION;
return StateUpdateResult::CHANGED; return StateUpdateResult::CHANGED;
}, });
"local");
return true; // need reboot return true; // need reboot
} }

View File

@@ -302,8 +302,7 @@ bool TemperatureSensor::update(const std::string & id, const std::string & name,
sensor.set_offset(offset); sensor.set_offset(offset);
// store the new name and offset in our configuration // store the new name and offset in our configuration
EMSESP::webCustomizationService.update( EMSESP::webCustomizationService.update([&](WebCustomization & settings) {
[&](WebCustomization & settings) {
// look it up to see if it exists // look it up to see if it exists
bool found = false; bool found = false;
for (auto & SensorCustomization : settings.sensorCustomizations) { for (auto & SensorCustomization : settings.sensorCustomizations) {
@@ -325,8 +324,7 @@ bool TemperatureSensor::update(const std::string & id, const std::string & name,
} }
sensor.ha_registered = false; // it's changed so we may need to recreate the HA config sensor.ha_registered = false; // it's changed so we may need to recreate the HA config
return StateUpdateResult::CHANGED; return StateUpdateResult::CHANGED;
}, });
"local");
return true; return true;
} }
} }

View File

@@ -628,8 +628,7 @@ bool WebCustomEntityService::get_value(std::shared_ptr<const Telegram> telegram)
// hard coded tests // hard coded tests
#ifdef EMSESP_TEST #ifdef EMSESP_TEST
void WebCustomEntityService::test() { void WebCustomEntityService::test() {
update( update([&](WebCustomEntity & webCustomEntity) {
[&](WebCustomEntity & webCustomEntity) {
webCustomEntity.customEntityItems.clear(); webCustomEntity.customEntityItems.clear();
// test 1 // test 1
auto entityItem = CustomEntityItem(); auto entityItem = CustomEntityItem();
@@ -672,8 +671,7 @@ void WebCustomEntityService::test() {
webCustomEntity.customEntityItems.push_back(entityItem); webCustomEntity.customEntityItems.push_back(entityItem);
return StateUpdateResult::CHANGED; // persist the changes return StateUpdateResult::CHANGED; // persist the changes
}, });
"local");
} }
#endif #endif

View File

@@ -276,8 +276,7 @@ void WebCustomizationService::customization_entities(AsyncWebServerRequest * req
emsdevice->getCustomizationEntities(entity_ids); emsdevice->getCustomizationEntities(entity_ids);
// Save the list to the customization file // Save the list to the customization file
update( update([&](WebCustomization & settings) {
[&](WebCustomization & settings) {
// see if we already have a mask list for this device, if so remove it // see if we already have a mask list for this device, if so remove it
for (auto it = settings.entityCustomizations.begin(); it != settings.entityCustomizations.end();) { for (auto it = settings.entityCustomizations.begin(); it != settings.entityCustomizations.end();) {
if ((*it).product_id == product_id && (*it).device_id == device_id) { if ((*it).product_id == product_id && (*it).device_id == device_id) {
@@ -298,8 +297,7 @@ void WebCustomizationService::customization_entities(AsyncWebServerRequest * req
// add the record and save // add the record and save
settings.entityCustomizations.push_back(new_entry); settings.entityCustomizations.push_back(new_entry);
return StateUpdateResult::CHANGED; return StateUpdateResult::CHANGED;
}, });
"local");
break; break;
} }
@@ -320,8 +318,7 @@ void WebCustomizationService::begin() {
// hard coded tests // hard coded tests
#ifdef EMSESP_TEST #ifdef EMSESP_TEST
void WebCustomizationService::test() { void WebCustomizationService::test() {
update( update([&](WebCustomization & webCustomization) {
[&](WebCustomization & webCustomization) {
// Temperature sensors // Temperature sensors
webCustomization.sensorCustomizations.clear(); webCustomization.sensorCustomizations.clear();
auto sensor = SensorCustomization(); auto sensor = SensorCustomization();
@@ -366,8 +363,7 @@ void WebCustomizationService::test() {
webCustomization.entityCustomizations.push_back(emsEntity); webCustomization.entityCustomizations.push_back(emsEntity);
return StateUpdateResult::CHANGED; // persist the changes return StateUpdateResult::CHANGED; // persist the changes
}, });
"local");
EMSESP::analogsensor_.reload(); // this is needed to active the analog sensors EMSESP::analogsensor_.reload(); // this is needed to active the analog sensors
} }

View File

@@ -59,12 +59,10 @@ uuid::log::Level WebLogService::log_level() const {
} }
void WebLogService::log_level(uuid::log::Level level) { void WebLogService::log_level(uuid::log::Level level) {
EMSESP::webSettingsService.update( EMSESP::webSettingsService.update([&](WebSettings & settings) {
[&](WebSettings & settings) {
settings.weblog_level = level; settings.weblog_level = level;
return StateUpdateResult::CHANGED; return StateUpdateResult::CHANGED;
}, });
"local");
uuid::log::Logger::register_handler(this, level); uuid::log::Logger::register_handler(this, level);
if (level == uuid::log::Level::OFF) { if (level == uuid::log::Level::OFF) {
log_messages_.clear(); log_messages_.clear();
@@ -87,12 +85,10 @@ void WebLogService::maximum_log_messages(size_t count) {
while (log_messages_.size() > maximum_log_messages_) { while (log_messages_.size() > maximum_log_messages_) {
log_messages_.pop_front(); log_messages_.pop_front();
} }
EMSESP::webSettingsService.update( EMSESP::webSettingsService.update([&](WebSettings & settings) {
[&](WebSettings & settings) {
settings.weblog_buffer = count; settings.weblog_buffer = count;
return StateUpdateResult::CHANGED; return StateUpdateResult::CHANGED;
}, });
"local");
} }
bool WebLogService::compact() const { bool WebLogService::compact() const {
@@ -101,12 +97,10 @@ bool WebLogService::compact() const {
void WebLogService::compact(bool compact) { void WebLogService::compact(bool compact) {
compact_ = compact; compact_ = compact;
EMSESP::webSettingsService.update( EMSESP::webSettingsService.update([&](WebSettings & settings) {
[&](WebSettings & settings) {
settings.weblog_compact = compact; settings.weblog_compact = compact;
return StateUpdateResult::CHANGED; return StateUpdateResult::CHANGED;
}, });
"local");
} }
WebLogService::QueuedLogMessage::QueuedLogMessage(unsigned long id, std::shared_ptr<uuid::log::Message> && content) WebLogService::QueuedLogMessage::QueuedLogMessage(unsigned long id, std::shared_ptr<uuid::log::Message> && content)

View File

@@ -432,8 +432,7 @@ void WebSchedulerService::loop() {
// hard coded tests // hard coded tests
#if defined(EMSESP_TEST) #if defined(EMSESP_TEST)
void WebSchedulerService::test() { void WebSchedulerService::test() {
update( update([&](WebScheduler & webScheduler) {
[&](WebScheduler & webScheduler) {
webScheduler.scheduleItems.clear(); webScheduler.scheduleItems.clear();
// test 1 // test 1
auto si = ScheduleItem(); auto si = ScheduleItem();
@@ -449,8 +448,7 @@ void WebSchedulerService::test() {
webScheduler.scheduleItems.push_back(si); webScheduler.scheduleItems.push_back(si);
return StateUpdateResult::CHANGED; // persist the changes return StateUpdateResult::CHANGED; // persist the changes
}, });
"local");
} }
#endif #endif

View File

@@ -32,7 +32,7 @@ WebSettingsService::WebSettingsService(AsyncWebServer * server, FS * fs, Securit
HTTP_GET, HTTP_GET,
securityManager->wrapRequest(std::bind(&WebSettingsService::board_profile, this, _1), AuthenticationPredicates::IS_ADMIN)); securityManager->wrapRequest(std::bind(&WebSettingsService::board_profile, this, _1), AuthenticationPredicates::IS_ADMIN));
addUpdateHandler([&](const String & originId) { onUpdate(); }, false); addUpdateHandler([&] { onUpdate(); }, false);
} }
void WebSettings::read(WebSettings & settings, JsonObject root) { void WebSettings::read(WebSettings & settings, JsonObject root) {