diff --git a/esphome/components/wifi/__init__.py b/esphome/components/wifi/__init__.py index 76155763fb..c7632a0c6b 100644 --- a/esphome/components/wifi/__init__.py +++ b/esphome/components/wifi/__init__.py @@ -378,18 +378,19 @@ async def to_code(config): # Track if any network uses Enterprise authentication has_eap = False - # Build all WiFiAP objects + # Initialize FixedVector with the count of networks networks = config.get(CONF_NETWORKS, []) if networks: - wifi_aps = [] + cg.add(var.init_sta(len(networks))) + + def add_sta(ap, network): + ip_config = network.get(CONF_MANUAL_IP, config.get(CONF_MANUAL_IP)) + cg.add(var.add_sta(wifi_network(network, ap, ip_config))) + for network in networks: if CONF_EAP in network: has_eap = True - ip_config = network.get(CONF_MANUAL_IP, config.get(CONF_MANUAL_IP)) - wifi_aps.append(wifi_network(network, WiFiAP(), ip_config)) - - # Set all WiFi networks at once - cg.add(var.set_stas(wifi_aps)) + cg.with_local_variable(network[CONF_ID], WiFiAP(), add_sta, network) if CONF_AP in config: conf = config[CONF_AP] diff --git a/esphome/components/wifi/wifi_component.cpp b/esphome/components/wifi/wifi_component.cpp index a7b66114c8..b278e5a386 100644 --- a/esphome/components/wifi/wifi_component.cpp +++ b/esphome/components/wifi/wifi_component.cpp @@ -330,8 +330,13 @@ float WiFiComponent::get_loop_priority() const { return 10.0f; // before other loop components } -void WiFiComponent::set_stas(const std::initializer_list &aps) { this->sta_ = aps; } -void WiFiComponent::set_sta(const WiFiAP &ap) { this->set_stas({ap}); } +void WiFiComponent::init_sta(size_t count) { this->sta_.init(count); } +void WiFiComponent::add_sta(const WiFiAP &ap) { this->sta_.push_back(ap); } +void WiFiComponent::set_sta(const WiFiAP &ap) { + this->clear_sta(); + this->init_sta(1); + this->add_sta(ap); +} void WiFiComponent::clear_sta() { this->sta_.clear(); } void WiFiComponent::save_wifi_sta(const std::string &ssid, const std::string &password) { SavedWifiSettings save{}; // zero-initialized - all bytes set to \0, guaranteeing null termination diff --git a/esphome/components/wifi/wifi_component.h b/esphome/components/wifi/wifi_component.h index 0bcfd7445a..42f78dbfac 100644 --- a/esphome/components/wifi/wifi_component.h +++ b/esphome/components/wifi/wifi_component.h @@ -219,7 +219,8 @@ class WiFiComponent : public Component { void set_sta(const WiFiAP &ap); WiFiAP get_sta() { return this->selected_ap_; } - void set_stas(const std::initializer_list &aps); + void init_sta(size_t count); + void add_sta(const WiFiAP &ap); void clear_sta(); #ifdef USE_WIFI_AP