From 0d6b79d714cee6b0f00d88d9d6934e9a6151cdb7 Mon Sep 17 00:00:00 2001 From: Rapsssito Date: Wed, 21 Aug 2024 19:05:55 +0200 Subject: [PATCH] Add wifi.save_ap_settings action --- esphome/components/wifi/__init__.py | 14 ++++++++++++++ esphome/components/wifi/wifi_component.h | 12 ++++++++++++ tests/components/wifi/common.yaml | 3 +++ 3 files changed, 29 insertions(+) diff --git a/esphome/components/wifi/__init__.py b/esphome/components/wifi/__init__.py index ea03cc16d1..a364e9861c 100644 --- a/esphome/components/wifi/__init__.py +++ b/esphome/components/wifi/__init__.py @@ -63,6 +63,7 @@ WiFiConnectedCondition = wifi_ns.class_("WiFiConnectedCondition", Condition) WiFiEnabledCondition = wifi_ns.class_("WiFiEnabledCondition", Condition) WiFiEnableAction = wifi_ns.class_("WiFiEnableAction", automation.Action) WiFiDisableAction = wifi_ns.class_("WiFiDisableAction", automation.Action) +WiFiSaveAPSettingsAction = wifi_ns.class_("WiFiSaveAPSettingsAction", automation.Action) def validate_password(value): @@ -483,3 +484,16 @@ async def wifi_enable_to_code(config, action_id, template_arg, args): @automation.register_action("wifi.disable", WiFiDisableAction, cv.Schema({})) async def wifi_disable_to_code(config, action_id, template_arg, args): return cg.new_Pvariable(action_id, template_arg) + + +@automation.register_action("wifi.save_ap_settings", WiFiSaveAPSettingsAction, cv.Schema({ + cv.Required(CONF_SSID): cv.templatable(cv.ssid), + cv.Required(CONF_PASSWORD): cv.templatable(validate_password), +})) +async def wifi_save_settings_to_code(config, action_id, template_arg, args): + var = cg.new_Pvariable(action_id, template_arg) + ssid = await cg.templatable(config[CONF_SSID], args, cg.std_string) + password = await cg.templatable(config[CONF_PASSWORD], args, cg.std_string) + cg.add(var.set_ssid(ssid)) + cg.add(var.set_password(password)) + return var diff --git a/esphome/components/wifi/wifi_component.h b/esphome/components/wifi/wifi_component.h index dde0d1d5a5..7dffcfe9a7 100644 --- a/esphome/components/wifi/wifi_component.h +++ b/esphome/components/wifi/wifi_component.h @@ -441,6 +441,18 @@ template class WiFiDisableAction : public Action { void play(Ts... x) override { global_wifi_component->disable(); } }; +template class WiFiSaveAPSettingsAction : public Action { + public: + TEMPLATABLE_VALUE(std::string, ssid) + TEMPLATABLE_VALUE(std::string, password) + + void play(Ts... x) override { + global_wifi_component->save_wifi_sta( + this->ssid_.value(x...), this->password_.value(x...) + ); + } +}; + } // namespace wifi } // namespace esphome #endif diff --git a/tests/components/wifi/common.yaml b/tests/components/wifi/common.yaml index 003f6347be..8dfd72981f 100644 --- a/tests/components/wifi/common.yaml +++ b/tests/components/wifi/common.yaml @@ -3,6 +3,9 @@ esphome: then: - wifi.disable - wifi.enable + - wifi.save_ap_settings: + - ssid: MySSID + - password: password1 wifi: ssid: MySSID