esp-idf-hal icon indicating copy to clipboard operation
esp-idf-hal copied to clipboard

Reconfigure WiFi with static IP after initialization

Open br0kenpixel opened this issue 9 months ago • 3 comments

My project stores a list of APs and tries to connect to the best one. I'd like to implement a feature that allows setting a static IP for some of those networks, while relying on DHCP for others.

When I first initialize EspWifi I'm not doing any static IP setup. However, I have a separate connect() method for connecting to a specific network. I'd like to "reconfigure" the STA interface with a static IP configuration.

This is essentially my WiFi initialization code:

let wifi = WifiDriver::new(modem, sys_loop, None)?;
esp!(unsafe { esp_wifi_set_storage(wifi_storage_t_WIFI_STORAGE_RAM) })?;

let mut wifi = EspWifi::wrap_all(wifi, EspNetif::new_with_conf(&ip_config)?)?;
wifi.set_configuration(&Configuration::Client(ClientConfiguration::default()))?;

wifi.start()?;
esp!(unsafe { esp_wifi_set_country_code(WIFI_COUNTRY_CODE.as_ptr().cast(), true) })?;

My connect() method is the following:

pub fn connect(&mut self, ssid: &str, psk: &str, auth: AuthMethod, static_ip_config: Option<NetifConfiguration>, timeout: Duration) -> OsResult<()> {
    if let Some(config) = static_ip_config {
        // ESP_ERR_INVALID_ARG
        self.driver.swap_netif_sta(EspNetif::new_with_conf(&config)?)?;
    }

    // ...
}

However, swap_netif_sta() returns ESP_ERR_INVALID_ARG. I tried calling EspWifi::stop() before swap_netif_sta(), but I get the same error. Is something like this even possible?

If I initialize EspWifi with static configuration, it works, but I can't do that because at that point I don't know which network I'll actually connect to. My app needs to perform a scan first and then do some filtering. This would require removing support for multiple APs and only relying on a single one.

br0kenpixel avatar Mar 30 '25 10:03 br0kenpixel