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() {
if (!_updateHandlerId) {
_updateHandlerId = _statefulService->addUpdateHandler([&](const String & originId) { writeToFS(); });
_updateHandlerId = _statefulService->addUpdateHandler([&] { writeToFS(); });
}
}

View File

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

View File

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

View File

@@ -14,7 +14,7 @@ NTPSettingsService::NTPSettingsService(AsyncWebServer * server, FS * fs, Securit
WiFi.onEvent(std::bind(&NTPSettingsService::WiFiEvent, this, _1));
addUpdateHandler([&](const String & originId) { configureNTP(); }, false);
addUpdateHandler([&] { configureNTP(); }, false);
}
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)
, _fsPersistence(NetworkSettings::read, NetworkSettings::update, this, fs, NETWORK_SETTINGS_FILE)
, _lastConnectionAttempt(0) {
addUpdateHandler([&](const String & originId) { reconfigureWiFiConnection(); }, false);
addUpdateHandler([&] { reconfigureWiFiConnection(); }, false);
// wifi event callbacks
WiFi.onEvent(std::bind(&NetworkSettingsService::WiFiEvent, this, _1, _2));
}
@@ -75,6 +75,7 @@ void NetworkSettingsService::manageSTA() {
if (_state.nosleep) {
WiFi.setSleep(false); // turn off sleep - WIFI_PS_NONE
}
// attempt to connect to the network
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) {
@@ -92,11 +93,12 @@ void NetworkSettingsService::manageSTA() {
// 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
WiFi.setTxPower(WIFI_POWER_8_5dBm);
return;
#else
if (_state.tx_power != 0) {
// 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
} 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));
#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
@@ -184,7 +188,7 @@ void NetworkSettingsService::mDNS_start() const {
if (_state.enableMDNS) {
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;
}
@@ -196,11 +200,11 @@ void NetworkSettingsService::mDNS_start() const {
MDNS.addServiceTxt("http", "tcp", "version", EMSESP_APP_VERSION);
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
if (_state.enableMDNS) {
EMSESP::logger().info("mDNS responder service started");
EMSESP::logger().info("mDNS Responder service started");
}
#endif
}

View File

@@ -9,7 +9,7 @@ OTASettingsService::OTASettingsService(AsyncWebServer * server, FS * fs, Securit
, _fsPersistence(OTASettings::read, OTASettings::update, this, fs, OTA_SETTINGS_FILE)
, _arduinoOTA(nullptr) {
WiFi.onEvent(std::bind(&OTASettingsService::WiFiEvent, this, _1, _2));
addUpdateHandler([&](const String & originId) { configureArduinoOTA(); }, false);
addUpdateHandler([&] { configureArduinoOTA(); }, false);
}
void OTASettingsService::begin() {
@@ -35,8 +35,8 @@ void OTASettingsService::configureArduinoOTA() {
_arduinoOTA->setPort(_state.port);
_arduinoOTA->setPassword(_state.password.c_str());
_arduinoOTA->onStart([]() { emsesp::EMSESP::system_.upload_status(true); });
_arduinoOTA->onEnd([]() { emsesp::EMSESP::system_.upload_status(false); });
_arduinoOTA->onStart([] { emsesp::EMSESP::system_.upload_status(true); });
_arduinoOTA->onEnd([] { emsesp::EMSESP::system_.upload_status(false); });
_arduinoOTA->onProgress([](unsigned int progress, unsigned int total) {
// 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)
, _fsPersistence(SecuritySettings::read, SecuritySettings::update, this, fs, SECURITY_SETTINGS_FILE)
, _jwtHandler(FACTORY_JWT_SECRET) {
addUpdateHandler([&](const String & originId) { configureJWTHandler(); }, false);
addUpdateHandler([&] { configureJWTHandler(); }, false);
server->on(GENERATE_TOKEN_PATH,
HTTP_GET,
wrapRequest(std::bind(&SecuritySettingsService::generateToken, this, std::placeholders::_1), AuthenticationPredicates::IS_ADMIN));

View File

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

View File

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

View File

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

View File

@@ -321,37 +321,35 @@ 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) {
// first see if we can find the sensor in our customization list
bool found_sensor = false;
EMSESP::webCustomizationService.update(
[&](WebCustomization & settings) {
for (auto & AnalogCustomization : settings.analogCustomizations) {
if (AnalogCustomization.type == AnalogType::COUNTER || AnalogCustomization.type >= AnalogType::DIGITAL_OUT) {
Command::erase_command(EMSdevice::DeviceType::ANALOGSENSOR, AnalogCustomization.name.c_str());
}
if (AnalogCustomization.gpio == gpio) {
found_sensor = true; // found the record
// see if it's marked for deletion
if (deleted) {
EMSESP::nvs_.remove(AnalogCustomization.name.c_str());
LOG_DEBUG("Removing analog sensor GPIO %02d", gpio);
settings.analogCustomizations.remove(AnalogCustomization);
} else {
// update existing record
if (name != AnalogCustomization.name) {
EMSESP::nvs_.remove(AnalogCustomization.name.c_str());
}
AnalogCustomization.name = name;
AnalogCustomization.offset = offset;
AnalogCustomization.factor = factor;
AnalogCustomization.uom = uom;
AnalogCustomization.type = type;
LOG_DEBUG("Customizing existing analog GPIO %02d", gpio);
}
return StateUpdateResult::CHANGED; // persist the change
}
EMSESP::webCustomizationService.update([&](WebCustomization & settings) {
for (auto & AnalogCustomization : settings.analogCustomizations) {
if (AnalogCustomization.type == AnalogType::COUNTER || AnalogCustomization.type >= AnalogType::DIGITAL_OUT) {
Command::erase_command(EMSdevice::DeviceType::ANALOGSENSOR, AnalogCustomization.name.c_str());
}
return StateUpdateResult::UNCHANGED;
},
"local");
if (AnalogCustomization.gpio == gpio) {
found_sensor = true; // found the record
// see if it's marked for deletion
if (deleted) {
EMSESP::nvs_.remove(AnalogCustomization.name.c_str());
LOG_DEBUG("Removing analog sensor GPIO %02d", gpio);
settings.analogCustomizations.remove(AnalogCustomization);
} else {
// update existing record
if (name != AnalogCustomization.name) {
EMSESP::nvs_.remove(AnalogCustomization.name.c_str());
}
AnalogCustomization.name = name;
AnalogCustomization.offset = offset;
AnalogCustomization.factor = factor;
AnalogCustomization.uom = uom;
AnalogCustomization.type = type;
LOG_DEBUG("Customizing existing analog GPIO %02d", gpio);
}
return StateUpdateResult::CHANGED; // persist the change
}
}
return StateUpdateResult::UNCHANGED;
});
// if the sensor exists and we're using HA, delete the old HA record
if (found_sensor && Mqtt::ha_enabled()) {
@@ -360,20 +358,18 @@ 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
if (!found_sensor) {
EMSESP::webCustomizationService.update(
[&](WebCustomization & settings) {
auto newSensor = AnalogCustomization();
newSensor.gpio = gpio;
newSensor.name = name;
newSensor.offset = offset;
newSensor.factor = factor;
newSensor.uom = uom;
newSensor.type = type;
settings.analogCustomizations.push_back(newSensor);
LOG_DEBUG("Adding new customization for analog sensor GPIO %02d", gpio);
return StateUpdateResult::CHANGED; // persist the change
},
"local");
EMSESP::webCustomizationService.update([&](WebCustomization & settings) {
auto newSensor = AnalogCustomization();
newSensor.gpio = gpio;
newSensor.name = name;
newSensor.offset = offset;
newSensor.factor = factor;
newSensor.uom = uom;
newSensor.type = type;
settings.analogCustomizations.push_back(newSensor);
LOG_DEBUG("Adding new customization for analog sensor GPIO %02d", gpio);
return StateUpdateResult::CHANGED; // persist the change
});
}
// reloads the sensors in the customizations file into the sensors list
@@ -818,20 +814,18 @@ bool AnalogSensor::command_setvalue(const char * value, const int8_t gpio) {
return false;
}
if (oldoffset != sensor.offset()) {
EMSESP::webCustomizationService.update(
[&](WebCustomization & settings) {
for (auto & AnalogCustomization : settings.analogCustomizations) {
if (AnalogCustomization.gpio == sensor.gpio() && AnalogCustomization.type == sensor.type()) {
AnalogCustomization.offset = sensor.offset();
}
EMSESP::webCustomizationService.update([&](WebCustomization & settings) {
for (auto & AnalogCustomization : settings.analogCustomizations) {
if (AnalogCustomization.gpio == sensor.gpio() && AnalogCustomization.type == sensor.type()) {
AnalogCustomization.offset = sensor.offset();
}
if (sensor.type() == AnalogType::COUNTER || (sensor.type() == AnalogType::DIGITAL_OUT && sensor.uom() > 0)) {
return StateUpdateResult::UNCHANGED; // temporary change
} else {
return StateUpdateResult::CHANGED; // persist the change
}
},
"local");
}
if (sensor.type() == AnalogType::COUNTER || (sensor.type() == AnalogType::DIGITAL_OUT && sensor.uom() > 0)) {
return StateUpdateResult::UNCHANGED; // temporary change
} else {
return StateUpdateResult::CHANGED; // persist the change
}
});
publish_sensor(sensor);
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) {
if (completed) {
if (password1 == password2) {
to_app(shell).esp8266React.getSecuritySettingsService()->update(
[&](SecuritySettings & securitySettings) {
securitySettings.jwtSecret = password2.c_str();
return StateUpdateResult::CHANGED;
},
"local");
to_app(shell).esp8266React.getSecuritySettingsService()->update([&](SecuritySettings & securitySettings) {
securitySettings.jwtSecret = password2.c_str();
return StateUpdateResult::CHANGED;
});
shell.println("Admin password updated");
} else {
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::loop_all();
delay(1000); // wait a second
to_app(shell).esp8266React.getNetworkSettingsService()->update(
[&](NetworkSettings & networkSettings) {
networkSettings.hostname = arguments.front().c_str();
return StateUpdateResult::CHANGED;
},
"local");
to_app(shell).esp8266React.getNetworkSettingsService()->update([&](NetworkSettings & networkSettings) {
networkSettings.hostname = arguments.front().c_str();
return StateUpdateResult::CHANGED;
});
});
commands->add_command(ShellContext::MAIN,
@@ -293,21 +289,19 @@ static void setup_commands(std::shared_ptr<Commands> & commands) {
if (arguments.size() == 2 && Helpers::toLower(arguments.back()) == "nvs") {
to_app(shell).nvs_.putString("boot", board_profile.c_str());
}
to_app(shell).webSettingsService.update(
[&](WebSettings & settings) {
settings.board_profile = board_profile.c_str();
settings.led_gpio = data[0];
settings.dallas_gpio = data[1];
settings.rx_gpio = data[2];
settings.tx_gpio = data[3];
settings.pbutton_gpio = data[4];
settings.phy_type = data[5];
settings.eth_power = data[6]; // can be -1
settings.eth_phy_addr = data[7];
settings.eth_clock_mode = data[8];
return StateUpdateResult::CHANGED;
},
"local");
to_app(shell).webSettingsService.update([&](WebSettings & settings) {
settings.board_profile = board_profile.c_str();
settings.led_gpio = data[0];
settings.dallas_gpio = data[1];
settings.rx_gpio = data[2];
settings.tx_gpio = data[3];
settings.pbutton_gpio = data[4];
settings.phy_type = data[5];
settings.eth_power = data[6]; // can be -1
settings.eth_phy_addr = data[7];
settings.eth_clock_mode = data[8];
return StateUpdateResult::CHANGED;
});
shell.printfln("Loaded board profile %s", board_profile.c_str());
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) {
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)) {
to_app(shell).webSettingsService.update(
[&](WebSettings & settings) {
settings.ems_bus_id = device_id;
shell.printfln(F_(bus_id_fmt), settings.ems_bus_id);
return StateUpdateResult::CHANGED;
},
"local");
to_app(shell).webSettingsService.update([&](WebSettings & settings) {
settings.ems_bus_id = device_id;
shell.printfln(F_(bus_id_fmt), settings.ems_bus_id);
return StateUpdateResult::CHANGED;
});
} else {
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) {
uint8_t tx_mode = std::strtol(arguments[0].c_str(), nullptr, 10);
// save the tx_mode
to_app(shell).webSettingsService.update(
[&](WebSettings & settings) {
settings.tx_mode = tx_mode;
shell.printfln(F_(tx_mode_fmt), settings.tx_mode);
return StateUpdateResult::CHANGED;
},
"local");
to_app(shell).webSettingsService.update([&](WebSettings & settings) {
settings.tx_mode = tx_mode;
shell.printfln(F_(tx_mode_fmt), settings.tx_mode);
return StateUpdateResult::CHANGED;
});
to_app(shell).uart_init();
});

View File

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

View File

@@ -208,8 +208,7 @@ bool System::command_syslog_level(const char * value, const int8_t id) {
changed = true;
}
return StateUpdateResult::CHANGED;
},
"local");
});
if (changed) {
EMSESP::system_.syslog_init();
}
@@ -277,9 +276,9 @@ void System::wifi_reconnect() {
EMSESP::esp8266React.getNetworkSettingsService()->read(
[](NetworkSettings & networkSettings) { LOG_INFO("WiFi reconnecting to SSID '%s'...", networkSettings.ssid.c_str()); });
Shell::loop_all();
delay(1000); // wait a second
EMSESP::webSettingsService.save(); // save local settings
EMSESP::esp8266React.getNetworkSettingsService()->callUpdateHandlers("local"); // in case we've changed ssid or password
delay(1000); // wait a second
EMSESP::webSettingsService.save(); // save local settings
EMSESP::esp8266React.getNetworkSettingsService()->callUpdateHandlers(); // in case we've changed ssid or password
}
// 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.
// 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
@@ -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 (missing_version) {
LOG_INFO("Setting MQTT Entity ID format to v3.4 format");
EMSESP::esp8266React.getMqttSettingsService()->update(
[&](MqttSettings & mqttSettings) {
mqttSettings.entity_format = 0; // use old Entity ID format from v3.4
return StateUpdateResult::CHANGED;
},
"local");
EMSESP::esp8266React.getMqttSettingsService()->update([&](MqttSettings & mqttSettings) {
mqttSettings.entity_format = 0; // use old Entity ID format from v3.4
return StateUpdateResult::CHANGED;
});
}
// Network Settings Wifi tx_power is now using the value * 4.
EMSESP::esp8266React.getNetworkSettingsService()->update(
[&](NetworkSettings & networkSettings) {
if (networkSettings.tx_power == 20) {
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");
return StateUpdateResult::CHANGED;
}
return StateUpdateResult::UNCHANGED;
},
"local");
EMSESP::esp8266React.getNetworkSettingsService()->update([&](NetworkSettings & networkSettings) {
if (networkSettings.tx_power == 20) {
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");
return StateUpdateResult::CHANGED;
}
return StateUpdateResult::UNCHANGED;
});
} else if (this_version < settings_version) {
// 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 (save_version) {
EMSESP::webSettingsService.update(
[&](WebSettings & settings) {
settings.version = EMSESP_APP_VERSION;
return StateUpdateResult::CHANGED;
},
"local");
EMSESP::webSettingsService.update([&](WebSettings & settings) {
settings.version = EMSESP_APP_VERSION;
return StateUpdateResult::CHANGED;
});
return true; // need reboot
}

View File

@@ -302,31 +302,29 @@ bool TemperatureSensor::update(const std::string & id, const std::string & name,
sensor.set_offset(offset);
// store the new name and offset in our configuration
EMSESP::webCustomizationService.update(
[&](WebCustomization & settings) {
// look it up to see if it exists
bool found = false;
for (auto & SensorCustomization : settings.sensorCustomizations) {
if (SensorCustomization.id == id) {
SensorCustomization.name = name;
SensorCustomization.offset = offset;
found = true;
LOG_DEBUG("Customizing existing sensor ID %s", id.c_str());
break;
}
EMSESP::webCustomizationService.update([&](WebCustomization & settings) {
// look it up to see if it exists
bool found = false;
for (auto & SensorCustomization : settings.sensorCustomizations) {
if (SensorCustomization.id == id) {
SensorCustomization.name = name;
SensorCustomization.offset = offset;
found = true;
LOG_DEBUG("Customizing existing sensor ID %s", id.c_str());
break;
}
if (!found) {
SensorCustomization newSensor = SensorCustomization();
newSensor.id = id;
newSensor.name = name;
newSensor.offset = offset;
settings.sensorCustomizations.push_back(newSensor);
LOG_DEBUG("Adding new customization for sensor ID %s", id.c_str());
}
sensor.ha_registered = false; // it's changed so we may need to recreate the HA config
return StateUpdateResult::CHANGED;
},
"local");
}
if (!found) {
SensorCustomization newSensor = SensorCustomization();
newSensor.id = id;
newSensor.name = name;
newSensor.offset = offset;
settings.sensorCustomizations.push_back(newSensor);
LOG_DEBUG("Adding new customization for sensor ID %s", id.c_str());
}
sensor.ha_registered = false; // it's changed so we may need to recreate the HA config
return StateUpdateResult::CHANGED;
});
return true;
}
}

View File

@@ -628,52 +628,50 @@ bool WebCustomEntityService::get_value(std::shared_ptr<const Telegram> telegram)
// hard coded tests
#ifdef EMSESP_TEST
void WebCustomEntityService::test() {
update(
[&](WebCustomEntity & webCustomEntity) {
webCustomEntity.customEntityItems.clear();
// test 1
auto entityItem = CustomEntityItem();
entityItem.ram = 0;
entityItem.device_id = 8;
entityItem.type_id = 24;
entityItem.offset = 0;
entityItem.factor = 1;
entityItem.name = "test_custom";
entityItem.uom = 1;
entityItem.value_type = 1;
entityItem.writeable = true;
entityItem.data = "70";
webCustomEntity.customEntityItems.push_back(entityItem);
update([&](WebCustomEntity & webCustomEntity) {
webCustomEntity.customEntityItems.clear();
// test 1
auto entityItem = CustomEntityItem();
entityItem.ram = 0;
entityItem.device_id = 8;
entityItem.type_id = 24;
entityItem.offset = 0;
entityItem.factor = 1;
entityItem.name = "test_custom";
entityItem.uom = 1;
entityItem.value_type = 1;
entityItem.writeable = true;
entityItem.data = "70";
webCustomEntity.customEntityItems.push_back(entityItem);
// test 2
entityItem.ram = 0;
entityItem.device_id = 24;
entityItem.type_id = 677;
entityItem.offset = 3;
entityItem.factor = 1;
entityItem.name = "test_read_only";
entityItem.uom = 0;
entityItem.value_type = 2;
entityItem.writeable = false;
entityItem.data = "48";
webCustomEntity.customEntityItems.push_back(entityItem);
// test 2
entityItem.ram = 0;
entityItem.device_id = 24;
entityItem.type_id = 677;
entityItem.offset = 3;
entityItem.factor = 1;
entityItem.name = "test_read_only";
entityItem.uom = 0;
entityItem.value_type = 2;
entityItem.writeable = false;
entityItem.data = "48";
webCustomEntity.customEntityItems.push_back(entityItem);
// test 2
entityItem.ram = 1;
entityItem.device_id = 0;
entityItem.type_id = 0;
entityItem.offset = 0;
entityItem.factor = 1;
entityItem.name = "test_ram";
entityItem.uom = 0;
entityItem.value_type = 8;
entityItem.writeable = true;
entityItem.data = "14";
webCustomEntity.customEntityItems.push_back(entityItem);
// test 2
entityItem.ram = 1;
entityItem.device_id = 0;
entityItem.type_id = 0;
entityItem.offset = 0;
entityItem.factor = 1;
entityItem.name = "test_ram";
entityItem.uom = 0;
entityItem.value_type = 8;
entityItem.writeable = true;
entityItem.data = "14";
webCustomEntity.customEntityItems.push_back(entityItem);
return StateUpdateResult::CHANGED; // persist the changes
},
"local");
return StateUpdateResult::CHANGED; // persist the changes
});
}
#endif

View File

@@ -276,30 +276,28 @@ void WebCustomizationService::customization_entities(AsyncWebServerRequest * req
emsdevice->getCustomizationEntities(entity_ids);
// Save the list to the customization file
update(
[&](WebCustomization & settings) {
// 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();) {
if ((*it).product_id == product_id && (*it).device_id == device_id) {
it = settings.entityCustomizations.erase(it);
break;
} else {
++it;
}
update([&](WebCustomization & settings) {
// 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();) {
if ((*it).product_id == product_id && (*it).device_id == device_id) {
it = settings.entityCustomizations.erase(it);
break;
} else {
++it;
}
}
// create a new entry for this device if there are values
EntityCustomization new_entry;
new_entry.product_id = product_id;
new_entry.device_id = device_id;
// create a new entry for this device if there are values
EntityCustomization new_entry;
new_entry.product_id = product_id;
new_entry.device_id = device_id;
new_entry.entity_ids = entity_ids;
new_entry.entity_ids = entity_ids;
// add the record and save
settings.entityCustomizations.push_back(new_entry);
return StateUpdateResult::CHANGED;
},
"local");
// add the record and save
settings.entityCustomizations.push_back(new_entry);
return StateUpdateResult::CHANGED;
});
break;
}
@@ -320,54 +318,52 @@ void WebCustomizationService::begin() {
// hard coded tests
#ifdef EMSESP_TEST
void WebCustomizationService::test() {
update(
[&](WebCustomization & webCustomization) {
// Temperature sensors
webCustomization.sensorCustomizations.clear();
auto sensor = SensorCustomization();
sensor.id = "01-0203-0405-0607";
sensor.name = "test_sensor1";
sensor.offset = 0;
webCustomization.sensorCustomizations.push_back(sensor);
update([&](WebCustomization & webCustomization) {
// Temperature sensors
webCustomization.sensorCustomizations.clear();
auto sensor = SensorCustomization();
sensor.id = "01-0203-0405-0607";
sensor.name = "test_sensor1";
sensor.offset = 0;
webCustomization.sensorCustomizations.push_back(sensor);
sensor = SensorCustomization();
sensor.id = "0B-0C0D-0E0F-1011";
sensor.name = "test_sensor2";
sensor.offset = 4;
webCustomization.sensorCustomizations.push_back(sensor);
sensor = SensorCustomization();
sensor.id = "0B-0C0D-0E0F-1011";
sensor.name = "test_sensor2";
sensor.offset = 4;
webCustomization.sensorCustomizations.push_back(sensor);
// Analog sensors
// This actually adds the sensors as we use customizations to store them
webCustomization.analogCustomizations.clear();
auto analog = AnalogCustomization();
analog.gpio = 36;
analog.name = "test_analog1";
analog.offset = 0;
analog.factor = 0.1;
analog.uom = 17;
analog.type = 3;
webCustomization.analogCustomizations.push_back(analog);
// Analog sensors
// This actually adds the sensors as we use customizations to store them
webCustomization.analogCustomizations.clear();
auto analog = AnalogCustomization();
analog.gpio = 36;
analog.name = "test_analog1";
analog.offset = 0;
analog.factor = 0.1;
analog.uom = 17;
analog.type = 3;
webCustomization.analogCustomizations.push_back(analog);
analog = AnalogCustomization();
analog.gpio = 37;
analog.name = "test_analog2";
analog.offset = 0;
analog.factor = 1;
analog.uom = 0;
analog.type = 1;
webCustomization.analogCustomizations.push_back(analog);
analog = AnalogCustomization();
analog.gpio = 37;
analog.name = "test_analog2";
analog.offset = 0;
analog.factor = 1;
analog.uom = 0;
analog.type = 1;
webCustomization.analogCustomizations.push_back(analog);
// EMS entities
webCustomization.entityCustomizations.clear();
auto emsEntity = EntityCustomization();
emsEntity.product_id = 123;
emsEntity.device_id = 8;
emsEntity.entity_ids.push_back("08heatingactive|is my heating on?");
webCustomization.entityCustomizations.push_back(emsEntity);
// EMS entities
webCustomization.entityCustomizations.clear();
auto emsEntity = EntityCustomization();
emsEntity.product_id = 123;
emsEntity.device_id = 8;
emsEntity.entity_ids.push_back("08heatingactive|is my heating on?");
webCustomization.entityCustomizations.push_back(emsEntity);
return StateUpdateResult::CHANGED; // persist the changes
},
"local");
return StateUpdateResult::CHANGED; // persist the changes
});
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) {
EMSESP::webSettingsService.update(
[&](WebSettings & settings) {
settings.weblog_level = level;
return StateUpdateResult::CHANGED;
},
"local");
EMSESP::webSettingsService.update([&](WebSettings & settings) {
settings.weblog_level = level;
return StateUpdateResult::CHANGED;
});
uuid::log::Logger::register_handler(this, level);
if (level == uuid::log::Level::OFF) {
log_messages_.clear();
@@ -87,12 +85,10 @@ void WebLogService::maximum_log_messages(size_t count) {
while (log_messages_.size() > maximum_log_messages_) {
log_messages_.pop_front();
}
EMSESP::webSettingsService.update(
[&](WebSettings & settings) {
settings.weblog_buffer = count;
return StateUpdateResult::CHANGED;
},
"local");
EMSESP::webSettingsService.update([&](WebSettings & settings) {
settings.weblog_buffer = count;
return StateUpdateResult::CHANGED;
});
}
bool WebLogService::compact() const {
@@ -101,12 +97,10 @@ bool WebLogService::compact() const {
void WebLogService::compact(bool compact) {
compact_ = compact;
EMSESP::webSettingsService.update(
[&](WebSettings & settings) {
settings.weblog_compact = compact;
return StateUpdateResult::CHANGED;
},
"local");
EMSESP::webSettingsService.update([&](WebSettings & settings) {
settings.weblog_compact = compact;
return StateUpdateResult::CHANGED;
});
}
WebLogService::QueuedLogMessage::QueuedLogMessage(unsigned long id, std::shared_ptr<uuid::log::Message> && content)

View File

@@ -432,25 +432,23 @@ void WebSchedulerService::loop() {
// hard coded tests
#if defined(EMSESP_TEST)
void WebSchedulerService::test() {
update(
[&](WebScheduler & webScheduler) {
webScheduler.scheduleItems.clear();
// test 1
auto si = ScheduleItem();
si.active = true;
si.flags = 1;
si.time = "12:00";
si.cmd = "system/fetch";
si.value = "10";
si.name = "test_scheduler";
si.elapsed_min = 0;
si.retry_cnt = 0xFF; // no startup retries
update([&](WebScheduler & webScheduler) {
webScheduler.scheduleItems.clear();
// test 1
auto si = ScheduleItem();
si.active = true;
si.flags = 1;
si.time = "12:00";
si.cmd = "system/fetch";
si.value = "10";
si.name = "test_scheduler";
si.elapsed_min = 0;
si.retry_cnt = 0xFF; // no startup retries
webScheduler.scheduleItems.push_back(si);
webScheduler.scheduleItems.push_back(si);
return StateUpdateResult::CHANGED; // persist the changes
},
"local");
return StateUpdateResult::CHANGED; // persist the changes
});
}
#endif

View File

@@ -32,7 +32,7 @@ WebSettingsService::WebSettingsService(AsyncWebServer * server, FS * fs, Securit
HTTP_GET,
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) {