Skip to content

Commit

Permalink
Fix DHCP handling (esp-rs#173)
Browse files Browse the repository at this point in the history
* Don't use DHCP when using fixed IP

* Make it possible to connect to another AP
  • Loading branch information
bjoernQ committed May 23, 2024
1 parent 8f41101 commit 28a0aaa
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 3 deletions.
5 changes: 4 additions & 1 deletion esp-wifi/src/wifi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1195,7 +1195,10 @@ impl embedded_svc::wifi::Wifi for WifiController<'_> {
}

fn connect(&mut self) -> Result<(), Self::Error> {
esp_wifi_result!(unsafe { esp_wifi_connect() })
esp_wifi_result!(unsafe {
WIFI_STATE = -1;
esp_wifi_connect()
})
}

fn disconnect(&mut self) -> Result<(), Self::Error> {
Expand Down
7 changes: 5 additions & 2 deletions esp-wifi/src/wifi/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,11 @@ pub fn create_network_interface<'a, 'd>(

let mut socket_set = SocketSet::new(socket_set_entries);

let dhcp_socket = Dhcpv4Socket::new();
socket_set.add(dhcp_socket);
if !mode.is_ap() {
// only add DHCP client in STA mode
let dhcp_socket = Dhcpv4Socket::new();
socket_set.add(dhcp_socket);
}

(iface, device, controller, socket_set)
}
34 changes: 34 additions & 0 deletions esp-wifi/src/wifi_interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,25 @@ impl<'a> WifiStack<'a> {
}
}

pub fn reset(&self) {
log::debug!("Reset TCP stack");

if let Some(dhcp_handle) = self.dhcp_socket_handle {
self.with_mut(|_, _, sockets| {
let dhcp_socket = sockets.get_mut::<Dhcpv4Socket>(dhcp_handle);
log::debug!("Reset DHCP client");
dhcp_socket.reset();
});
}

self.with_mut(|interface, _, _| {
interface.routes_mut().remove_default_ipv4_route();
interface.update_ip_addrs(|addrs| {
addrs.clear();
});
});
}

/// Convenience function to poll the DHCP socket.
pub fn poll_dhcp(
&self,
Expand Down Expand Up @@ -239,6 +258,21 @@ impl<'a> ipv4::Interface for WifiStack<'a> {
}

fn set_iface_configuration(&mut self, conf: &ipv4::Configuration) -> Result<(), Self::Error> {
if let Some(dhcp_handle) = self.dhcp_socket_handle {
let dhcp_socket = self.sockets.get_mut().get_mut::<Dhcpv4Socket>(dhcp_handle);
log::info!("Reset DHCP client");
dhcp_socket.reset();

// remove the DHCP client if we use a static IP
if matches!(
conf,
ipv4::Configuration::Client(ipv4::ClientConfiguration::Fixed(_))
) {
self.sockets.get_mut().remove(dhcp_handle);
self.dhcp_socket_handle = None;
}
}

*self.network_config.borrow_mut() = conf.clone();
Ok(())
}
Expand Down

0 comments on commit 28a0aaa

Please sign in to comment.