diff --git a/.cargo/config.toml b/.cargo/config.toml index e162b88..fa4eda1 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -18,7 +18,6 @@ runner = "espflash flash --monitor --baud 921600" rustflags = [ "-C", "link-arg=-Tlinkall.x", "-C", "link-arg=-nostartfiles", - "-C", "link-arg=-Trom_functions.x", ] [target.riscv32imc-unknown-none-elf] @@ -26,7 +25,6 @@ runner = "espflash flash --monitor --baud 921600" rustflags = [ "-C", "link-arg=-Tlinkall.x", - "-C", "link-arg=-Trom_functions.x", # Required to obtain backtraces (e.g. when using the "esp-backtrace" crate.) # NOTE: May negatively impact performance of produced code @@ -39,7 +37,6 @@ runner = "espflash flash --monitor --baud 921600" rustflags = [ #"-C", "linker=rust-lld", "-C", "link-arg=-Tlinkall.x", - "-C", "link-arg=-Trom_functions.x", ] [target.xtensa-esp32s3-none-elf] @@ -48,7 +45,6 @@ runner = "espflash flash --monitor --baud 921600" rustflags = [ "-C", "link-arg=-Tlinkall.x", "-C", "link-arg=-nostartfiles", - "-C", "link-arg=-Trom_functions.x", ] [target.'cfg(target_os = "espidf")'] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9c64a2e..9679066 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,7 +28,7 @@ jobs: - uses: dtolnay/rust-toolchain@v1 with: target: riscv32imc-unknown-none-elf - toolchain: nightly-2024-07-22 + toolchain: nightly-2024-12-01 components: rust-src,rustfmt - uses: esp-rs/xtensa-toolchain@v1.5 with: diff --git a/Cargo.toml b/Cargo.toml index 01a0cf1..2769707 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,30 +24,40 @@ opt-level = "z" opt-level = 3 [dependencies] -esp-hal = { version = "0.21.0", optional = true } +esp-hal = { version = "0.22.0", optional = true } esp-backtrace = { version = "0.14.0", optional = true, features = [ "panic-handler", "println", "exception-handler", ] } esp-println = { version = "0.12.0", optional = true, features = ["log"] } -esp-hal-embassy = { version = "0.4.0", optional = true } +esp-hal-embassy = { version = "0.5.0", optional = true } embassy-time = { version = "0.3.0", optional = true } -embassy-executor = { version = "=0.6.0", package = "embassy-executor", features = [ +embassy-executor = { version = "0.6", package = "embassy-executor", features = [ "nightly", "integrated-timers", ], optional = true } -embassy-net = { version = "0.4.0", features = [ +embassy-net = { version = "0.5.0", features = [ "tcp", "udp", "dhcpv4", "medium-ethernet", ], optional = true } -esp-wifi = { version = "0.10.1", optional = true, features = ["phy-enable-usb", "wifi-default", "sys-logs"] } -smoltcp = { version = "0.11.0", optional = true, default-features = false, features = [ - "proto-igmp", +esp-wifi = { version = "0.11.0", optional = true, features = ["sys-logs", "utils", "wifi"] } +blocking-network-stack = { git = "https://github.com/bjoernQ/blocking-network-stack", rev = "1c581661d78e0cf0f17b936297179b993fb149d7" } +smoltcp11 = { package = "smoltcp", version = "0.11.0", optional = true, default-features = false, features = [ + "proto-ipv4", + "socket-tcp", + "socket-icmp", + "socket-udp", + "medium-ethernet", + "proto-dhcpv4", + "socket-raw", + "socket-dhcpv4", +] } +smoltcp = { version = "0.12.0", optional = true, default-features = false, features = [ "proto-ipv4", "socket-tcp", "socket-icmp", @@ -66,15 +76,17 @@ static_cell = { version = "2.1", features = ["nightly"] } esp-mbedtls = { path = "./esp-mbedtls" } -edge-http = { version = "0.3.0", optional = true } -edge-nal = { version = "0.3.0", optional = true } -edge-nal-embassy = { version = "0.3.0", optional = true } +edge-http = { version = "0.4.0", optional = true } +edge-nal = { version = "0.4.0", optional = true } +edge-nal-embassy = { version = "0.4.0", optional = true } cfg-if = "1.0.0" esp-alloc = { version = "0.5.0", optional = true} enumset = { version = "1", default-features = false } +tinyrlibc = { version = "0.5", optional = true, default-features = false } + [target.'cfg(target_os = "espidf")'.dependencies] -esp-idf-svc = { version = "0.49.1", features = ["binstart"] } +esp-idf-svc = { version = "0.50", features = ["binstart"] } [[example]] name = "crypto_self_test" @@ -104,8 +116,8 @@ name = "edge_server" required-features = ["examples-async", "edge-http"] [features] -examples = ["esp-hal", "esp-backtrace", "esp-println", "esp-wifi", "smoltcp", "esp-alloc"] -examples-async = ["examples", "esp-hal-embassy", "embassy-time", "embassy-executor", "embassy-net", "edge-http", "edge-nal", "edge-nal-embassy", "esp-wifi/async", "esp-wifi/embassy-net", "esp-mbedtls/async", "esp-mbedtls/edge-nal"] +examples = ["esp-hal", "esp-backtrace", "esp-println", "esp-wifi", "smoltcp", "smoltcp11", "esp-alloc"] +examples-async = ["examples", "esp-hal-embassy", "embassy-time", "embassy-executor", "embassy-net", "edge-http", "edge-nal", "edge-nal-embassy", "esp-mbedtls/async", "esp-mbedtls/edge-nal"] examples-std = ["critical-section/std"] esp32 = [ @@ -123,6 +135,7 @@ esp32c3 = [ "esp-println?/esp32c3", "esp-wifi?/esp32c3", "esp-mbedtls/esp32c3", + "tinyrlibc/memchr", ] esp32s2 = [ "esp-hal?/esp32s2", @@ -142,18 +155,4 @@ esp32s3 = [ ] [build-dependencies] -embuild = { version = "0.32", features = ["espidf"] } - -# Patch until new release -[patch.crates-io] -edge-http = { git = "https://github.com/ivmarkov/edge-net" } -edge-nal = { git = "https://github.com/ivmarkov/edge-net" } -edge-nal-embassy = { git = "https://github.com/ivmarkov/edge-net" } -esp-idf-svc = { git = "https://github.com/esp-rs/esp-idf-svc" } -esp-idf-hal = { git = "https://github.com/esp-rs/esp-idf-hal" } -esp-idf-sys = { git = "https://github.com/esp-rs/esp-idf-sys" } - -# Patch before 0.6.0 got yanked -embassy-executor = { git = "https://github.com/embassy-rs/embassy", rev = "886580179ff250e15b0fad6448e8ebed6cdabf2b" } -embassy-time-driver = { git = "https://github.com/embassy-rs/embassy", rev = "886580179ff250e15b0fad6448e8ebed6cdabf2b" } -embassy-time-queue-driver = { git = "https://github.com/embassy-rs/embassy", rev = "886580179ff250e15b0fad6448e8ebed6cdabf2b" } \ No newline at end of file +embuild = { version = "0.33", features = ["espidf"] } diff --git a/esp-mbedtls-sys/Cargo.toml b/esp-mbedtls-sys/Cargo.toml index 5ba76c0..0c4a89c 100644 --- a/esp-mbedtls-sys/Cargo.toml +++ b/esp-mbedtls-sys/Cargo.toml @@ -8,22 +8,22 @@ rust-version = "1.82" [build-dependencies] anyhow = "1.0.68" -bindgen = "0.68.1" +bindgen = "0.71.1" env_logger = "0.10.0" log = "0.4.17" cmake = "0.1.52" fs_extra = "1.3.0" -embuild = "0.32" +embuild = "0.33" [dependencies] # For malloc/free # TODO: Replace with `esp-alloc` once `esp-alloc` starts to provide `malloc` and `free` in future # ... or switch to our own `mbedtls_malloc/free` -esp-wifi = { version = "0.10.1", default-features = false, optional = true } +esp-wifi = { version = "0.11.0", default-features = false, optional = true } # ESP-IDF: The mbedtls lib distributed with ESP-IDF is used [target.'cfg(target_os = "espidf")'.dependencies] -esp-idf-sys = { version = "0.35", default-features = false } +esp-idf-sys = { version = "0.36", default-features = false } # All other platforms: mbedtls libs and bindings are created on the fly diff --git a/esp-mbedtls/Cargo.toml b/esp-mbedtls/Cargo.toml index 7c81255..2e52d47 100644 --- a/esp-mbedtls/Cargo.toml +++ b/esp-mbedtls/Cargo.toml @@ -14,13 +14,13 @@ log = { version = "0.4.17", default-features = false } enumset = { version = "1", default-features = false } embedded-io = { version = "0.6.1" } embedded-io-async = { version = "0.6.0", optional = true } -esp-hal = { version = "0.21.0", optional = true } +esp-hal = { version = "0.22.0", optional = true } # For malloc/free # TODO: Replace with `esp-alloc` once `esp-alloc` starts to provide `malloc` and `free` in future # ... or switch to our own `mbedtls_malloc/free` -esp-wifi = { version = "0.10.1", default-features = false, optional = true } +esp-wifi = { version = "0.11.0", default-features = false, optional = true } cfg-if = "1.0.0" -edge-nal = { version = "0.3.0", optional = true } +edge-nal = { version = "0.4.0", optional = true } critical-section = "1.1.3" crypto-bigint = { version = "0.5.3", optional = true, default-features = false, features = ["extra-sizes"] } diff --git a/esp-mbedtls/src/edge_nal.rs b/esp-mbedtls/src/edge_nal.rs index 5e6540a..0da1c28 100644 --- a/esp-mbedtls/src/edge_nal.rs +++ b/esp-mbedtls/src/edge_nal.rs @@ -46,7 +46,10 @@ where T: edge_nal::TcpAccept, { type Error = TlsError; - type Socket<'a> = Session<'a, T::Socket<'a>> where Self: 'a; + type Socket<'a> + = Session<'a, T::Socket<'a>> + where + Self: 'a; async fn accept( &self, @@ -115,7 +118,10 @@ where { type Error = TlsError; - type Socket<'a> = Session<'a, T::Socket<'a>> where Self: 'a; + type Socket<'a> + = Session<'a, T::Socket<'a>> + where + Self: 'a; async fn connect(&self, remote: SocketAddr) -> Result, Self::Error> { let socket = self @@ -151,6 +157,25 @@ where } } +impl edge_nal::TcpSplit for Session<'_, T> +where + T: edge_nal::TcpSplit + embedded_io_async::Read + embedded_io_async::Write + edge_nal::Readable, +{ + type Read<'a> + = Self + where + Self: 'a; + + type Write<'a> + = Self + where + Self: 'a; + + fn split(&mut self) -> (Self::Read<'_>, Self::Write<'_>) { + panic!("Splitting a TLS session is not supported yet"); + } +} + impl edge_nal::TcpShutdown for Session<'_, T> where T: embedded_io_async::Read + embedded_io_async::Write + edge_nal::TcpShutdown, diff --git a/esp-mbedtls/src/esp_hal/sha/sha256.rs b/esp-mbedtls/src/esp_hal/sha/sha256.rs index 023641e..797a8f7 100644 --- a/esp-mbedtls/src/esp_hal/sha/sha256.rs +++ b/esp-mbedtls/src/esp_hal/sha/sha256.rs @@ -114,6 +114,7 @@ pub unsafe extern "C" fn mbedtls_sha256_finish( ); nb::block!(hasher.finish(&mut data)).unwrap(); nb::block!(hasher.save((*ctx).sha224_hasher.as_mut().unwrap())).unwrap(); + core::ptr::copy_nonoverlapping(data.as_ptr(), output, 28); } else { let mut hasher = ShaDigest::restore( sha.as_mut().unwrap(), @@ -121,8 +122,8 @@ pub unsafe extern "C" fn mbedtls_sha256_finish( ); nb::block!(hasher.finish(&mut data)).unwrap(); nb::block!(hasher.save((*ctx).sha256_hasher.as_mut().unwrap())).unwrap(); + core::ptr::copy_nonoverlapping(data.as_ptr(), output, 32); } }); - core::ptr::copy_nonoverlapping(data.as_ptr(), output, data.len()); 0 } diff --git a/esp-mbedtls/src/esp_hal/sha/sha512.rs b/esp-mbedtls/src/esp_hal/sha/sha512.rs index e1cc4c9..dd270ab 100644 --- a/esp-mbedtls/src/esp_hal/sha/sha512.rs +++ b/esp-mbedtls/src/esp_hal/sha/sha512.rs @@ -114,6 +114,7 @@ pub unsafe extern "C" fn mbedtls_sha512_finish( ); nb::block!(hasher.finish(&mut data)).unwrap(); nb::block!(hasher.save((*ctx).sha384_hasher.as_mut().unwrap())).unwrap(); + core::ptr::copy_nonoverlapping(data.as_ptr(), output, 48); } else { let mut hasher = ShaDigest::restore( sha.as_mut().unwrap(), @@ -121,8 +122,8 @@ pub unsafe extern "C" fn mbedtls_sha512_finish( ); nb::block!(hasher.finish(&mut data)).unwrap(); nb::block!(hasher.save((*ctx).sha512_hasher.as_mut().unwrap())).unwrap(); + core::ptr::copy_nonoverlapping(data.as_ptr(), output, 64); } }); - core::ptr::copy_nonoverlapping(data.as_ptr(), output, data.len()); 0 } diff --git a/esp-mbedtls/src/lib.rs b/esp-mbedtls/src/lib.rs index fd8e358..4198db3 100644 --- a/esp-mbedtls/src/lib.rs +++ b/esp-mbedtls/src/lib.rs @@ -1176,16 +1176,26 @@ pub mod asynch { F: FnMut(*mut mbedtls_ssl_context) -> i32, { loop { + // If there is an outstanding byte, we really need to push it down the wire first + // before we call `poll_fn` below. Otherwise, the bytes generated by `poll_fn` and emplaced + // in the socket write buffer would be send _before_ our outstanding byte + // + // It is another topic that this usually should not happen, as we are calling `flush_write` also + // _after_ the `poll_fn` call, but in the rare case where the user cancels this function (drops the future) + // and then re-tries the call, the outstanding byte will not be written so it needs to be re-tried here. + self.flush_write().await?; + let outcome = core::future::poll_fn(|cx| PollCtx::poll(self, cx, |ssl| f(ssl))).await?; - self.flush_write().await?; - match outcome { - PollOutcome::Success(res) => break Ok(res), + PollOutcome::Success(res) => { + self.flush_write().await?; + break Ok(res); + } PollOutcome::Retry => continue, PollOutcome::WantRead => self.wait_read().await?, - PollOutcome::WantWrite => self.flush_write().await?, + PollOutcome::WantWrite => continue, PollOutcome::Eof => { self.state = SessionState::Eof; break Ok(0); @@ -1209,6 +1219,11 @@ pub mod asynch { .map_err(|e| TlsError::Io(e.kind()))?; if len > 0 { self.read_byte = Some(buf[0]); + } else { + // len = 0 means the other party abruptly closed the socket + // For now, return an error as this is not the nice `MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY` + // case, but re-consider this in future + Err(TlsError::Eof)?; } } @@ -1230,6 +1245,11 @@ pub mod asynch { .map_err(|e| TlsError::Io(e.kind()))?; if len > 0 { self.write_byte.take(); + } else { + // len = 0 means the other party abruptly closed the socket + // For now, return an error as this is not the nice `MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY` + // case, but re-consider this in future + Err(TlsError::Eof)?; } } @@ -1395,7 +1415,7 @@ pub mod asynch { ::log::debug!("Send {}B", buf.len()); if buf.is_empty() { - // MbedTLS does not want us to read anything + // MbedTLS does not want us to write anything return 0; } diff --git a/examples/async_client.rs b/examples/async_client.rs index 8721473..2deec9a 100644 --- a/examples/async_client.rs +++ b/examples/async_client.rs @@ -5,11 +5,20 @@ #![feature(type_alias_impl_trait)] #![feature(impl_trait_in_assoc_type)] +// See https://github.com/esp-rs/esp-mbedtls/pull/62#issuecomment-2560830139 +// +// This is by the way a generic way to polyfill the libc functions used by `mbedtls`: +// - If your (baremetal) platform does not provide one or more of these, just +// add a dependency on `tinyrlibc` in your binary crate with features for all missing functions +// and then put such a `use` statement in your main file +#[cfg(feature = "esp32c3")] +use tinyrlibc as _; + #[doc(hidden)] pub use esp_hal as hal; use embassy_net::tcp::TcpSocket; -use embassy_net::{Config, Ipv4Address, Stack, StackResources}; +use embassy_net::{Config, Ipv4Address, Runner, StackResources}; use embassy_executor::Spawner; use embassy_time::{Duration, Timer}; @@ -22,7 +31,7 @@ use esp_wifi::wifi::{ ClientConfiguration, Configuration, WifiController, WifiDevice, WifiEvent, WifiStaDevice, WifiState, }; -use esp_wifi::{init, EspWifiInitFor}; +use esp_wifi::{init, EspWifiController}; use hal::{prelude::*, rng::Rng, timer::timg::TimerGroup}; // Patch until https://github.com/embassy-rs/static-cell/issues/16 is fixed @@ -52,17 +61,19 @@ async fn main(spawner: Spawner) -> ! { let timg0 = TimerGroup::new(peripherals.TIMG0); - let init = init( - EspWifiInitFor::Wifi, - timg0.timer0, - Rng::new(peripherals.RNG), - peripherals.RADIO_CLK, - ) - .unwrap(); + let init = &*mk_static!( + EspWifiController<'_>, + init( + timg0.timer0, + Rng::new(peripherals.RNG), + peripherals.RADIO_CLK, + ) + .unwrap() + ); let wifi = peripherals.WIFI; let (wifi_interface, controller) = - esp_wifi::wifi::new_with_mode(&init, wifi, WifiStaDevice).unwrap(); + esp_wifi::wifi::new_with_mode(init, wifi, WifiStaDevice).unwrap(); cfg_if::cfg_if! { if #[cfg(feature = "esp32")] { @@ -80,18 +91,15 @@ async fn main(spawner: Spawner) -> ! { let seed = 1234; // very random, very secure seed // Init network stack - let stack = &*mk_static!( - Stack>, - Stack::new( - wifi_interface, - config, - mk_static!(StackResources<3>, StackResources::<3>::new()), - seed - ) + let (stack, runner) = embassy_net::new( + wifi_interface, + config, + mk_static!(StackResources<3>, StackResources::<3>::new()), + seed, ); spawner.spawn(connection(controller)).ok(); - spawner.spawn(net_task(&stack)).ok(); + spawner.spawn(net_task(runner)).ok(); let mut rx_buffer = [0; 4096]; let mut tx_buffer = [0; 4096]; @@ -112,7 +120,7 @@ async fn main(spawner: Spawner) -> ! { Timer::after(Duration::from_millis(500)).await; } - let mut socket = TcpSocket::new(&stack, &mut rx_buffer, &mut tx_buffer); + let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer); socket.set_timeout(Some(Duration::from_secs(10))); @@ -121,6 +129,7 @@ async fn main(spawner: Spawner) -> ! { let r = socket.connect(remote_endpoint).await; if let Err(e) = r { println!("connect error: {:?}", e); + #[allow(clippy::empty_loop)] loop {} } @@ -160,6 +169,7 @@ async fn main(spawner: Spawner) -> ! { .await; if let Err(e) = r { println!("write error: {:?}", e); + #[allow(clippy::empty_loop)] loop {} } @@ -179,21 +189,19 @@ async fn main(spawner: Spawner) -> ! { println!(); println!("Done"); + #[allow(clippy::empty_loop)] loop {} } #[embassy_executor::task] async fn connection(mut controller: WifiController<'static>) { println!("start connection task"); - println!("Device capabilities: {:?}", controller.get_capabilities()); + println!("Device capabilities: {:?}", controller.capabilities()); loop { - match esp_wifi::wifi::get_wifi_state() { - WifiState::StaConnected => { - // wait until we're no longer connected - controller.wait_for_event(WifiEvent::StaDisconnected).await; - Timer::after(Duration::from_millis(5000)).await - } - _ => {} + if matches!(esp_wifi::wifi::wifi_state(), WifiState::StaConnected) { + // wait until we're no longer connected + controller.wait_for_event(WifiEvent::StaDisconnected).await; + Timer::after(Duration::from_millis(5000)).await } if !matches!(controller.is_started(), Ok(true)) { let client_config = Configuration::Client(ClientConfiguration { @@ -203,12 +211,12 @@ async fn connection(mut controller: WifiController<'static>) { }); controller.set_configuration(&client_config).unwrap(); println!("Starting wifi"); - controller.start().await.unwrap(); + controller.start_async().await.unwrap(); println!("Wifi started!"); } println!("About to connect..."); - match controller.connect().await { + match controller.connect_async().await { Ok(_) => println!("Wifi connected!"), Err(e) => { println!("Failed to connect to wifi: {e:?}"); @@ -219,6 +227,6 @@ async fn connection(mut controller: WifiController<'static>) { } #[embassy_executor::task] -async fn net_task(stack: &'static Stack>) { - stack.run().await +async fn net_task(mut runner: Runner<'static, WifiDevice<'static, WifiStaDevice>>) { + runner.run().await } diff --git a/examples/async_client_mTLS.rs b/examples/async_client_mTLS.rs index 2f0da30..fc6e9ca 100644 --- a/examples/async_client_mTLS.rs +++ b/examples/async_client_mTLS.rs @@ -5,12 +5,22 @@ #![feature(impl_trait_in_assoc_type)] #![allow(non_snake_case)] -use embassy_executor::Spawner; +// See https://github.com/esp-rs/esp-mbedtls/pull/62#issuecomment-2560830139 +// +// This is by the way a generic way to polyfill the libc functions used by `mbedtls`: +// - If your (baremetal) platform does not provide one or more of these, just +// add a dependency on `tinyrlibc` in your binary crate with features for all missing functions +// and then put such a `use` statement in your main file +#[cfg(feature = "esp32c3")] +use tinyrlibc as _; + #[doc(hidden)] pub use esp_hal as hal; +use embassy_executor::Spawner; + use embassy_net::tcp::TcpSocket; -use embassy_net::{Config, Ipv4Address, Stack, StackResources}; +use embassy_net::{Config, Ipv4Address, Runner, StackResources}; use embassy_time::{Duration, Timer}; use esp_backtrace as _; @@ -22,7 +32,7 @@ use esp_wifi::wifi::{ ClientConfiguration, Configuration, WifiController, WifiDevice, WifiEvent, WifiStaDevice, WifiState, }; -use esp_wifi::{init, EspWifiInitFor}; +use esp_wifi::{init, EspWifiController}; use hal::{prelude::*, rng::Rng, timer::timg::TimerGroup}; // Patch until https://github.com/embassy-rs/static-cell/issues/16 is fixed @@ -40,7 +50,7 @@ const PASSWORD: &str = env!("PASSWORD"); #[esp_hal_embassy::main] async fn main(spawner: Spawner) -> ! { - init_logger(log::LevelFilter::Debug); + init_logger(log::LevelFilter::Info); let peripherals = esp_hal::init({ let mut config = esp_hal::Config::default(); @@ -52,17 +62,19 @@ async fn main(spawner: Spawner) -> ! { let timg0 = TimerGroup::new(peripherals.TIMG0); - let init = init( - EspWifiInitFor::Wifi, - timg0.timer0, - Rng::new(peripherals.RNG), - peripherals.RADIO_CLK, - ) - .unwrap(); + let init = &*mk_static!( + EspWifiController<'_>, + init( + timg0.timer0, + Rng::new(peripherals.RNG), + peripherals.RADIO_CLK, + ) + .unwrap() + ); let wifi = peripherals.WIFI; let (wifi_interface, controller) = - esp_wifi::wifi::new_with_mode(&init, wifi, WifiStaDevice).unwrap(); + esp_wifi::wifi::new_with_mode(init, wifi, WifiStaDevice).unwrap(); cfg_if::cfg_if! { if #[cfg(feature = "esp32")] { @@ -80,18 +92,15 @@ async fn main(spawner: Spawner) -> ! { let seed = 1234; // very random, very secure seed // Init network stack - let stack = &*mk_static!( - Stack>, - Stack::new( - wifi_interface, - config, - mk_static!(StackResources<3>, StackResources::<3>::new()), - seed - ) + let (stack, runner) = embassy_net::new( + wifi_interface, + config, + mk_static!(StackResources<3>, StackResources::<3>::new()), + seed, ); spawner.spawn(connection(controller)).ok(); - spawner.spawn(net_task(&stack)).ok(); + spawner.spawn(net_task(runner)).ok(); let mut rx_buffer = [0; 4096]; let mut tx_buffer = [0; 4096]; @@ -112,7 +121,7 @@ async fn main(spawner: Spawner) -> ! { Timer::after(Duration::from_millis(500)).await; } - let mut socket = TcpSocket::new(&stack, &mut rx_buffer, &mut tx_buffer); + let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer); socket.set_timeout(Some(Duration::from_secs(10))); @@ -121,6 +130,7 @@ async fn main(spawner: Spawner) -> ! { let r = socket.connect(remote_endpoint).await; if let Err(e) = r { println!("connect error: {:?}", e); + #[allow(clippy::empty_loop)] loop {} } @@ -140,7 +150,7 @@ async fn main(spawner: Spawner) -> ! { .unwrap() .with_hardware_rsa(peripherals.RSA); - tls.set_debug(5); + tls.set_debug(0); let mut session = Session::new( &mut socket, @@ -166,6 +176,7 @@ async fn main(spawner: Spawner) -> ! { .await; if let Err(e) = r { println!("write error: {:?}", e); + #[allow(clippy::empty_loop)] loop {} } @@ -184,21 +195,19 @@ async fn main(spawner: Spawner) -> ! { } println!("Done"); + #[allow(clippy::empty_loop)] loop {} } #[embassy_executor::task] async fn connection(mut controller: WifiController<'static>) { println!("start connection task"); - println!("Device capabilities: {:?}", controller.get_capabilities()); + println!("Device capabilities: {:?}", controller.capabilities()); loop { - match esp_wifi::wifi::get_wifi_state() { - WifiState::StaConnected => { - // wait until we're no longer connected - controller.wait_for_event(WifiEvent::StaDisconnected).await; - Timer::after(Duration::from_millis(5000)).await - } - _ => {} + if matches!(esp_wifi::wifi::wifi_state(), WifiState::StaConnected) { + // wait until we're no longer connected + controller.wait_for_event(WifiEvent::StaDisconnected).await; + Timer::after(Duration::from_millis(5000)).await } if !matches!(controller.is_started(), Ok(true)) { let client_config = Configuration::Client(ClientConfiguration { @@ -208,12 +217,12 @@ async fn connection(mut controller: WifiController<'static>) { }); controller.set_configuration(&client_config).unwrap(); println!("Starting wifi"); - controller.start().await.unwrap(); + controller.start_async().await.unwrap(); println!("Wifi started!"); } println!("About to connect..."); - match controller.connect().await { + match controller.connect_async().await { Ok(_) => println!("Wifi connected!"), Err(e) => { println!("Failed to connect to wifi: {e:?}"); @@ -224,6 +233,6 @@ async fn connection(mut controller: WifiController<'static>) { } #[embassy_executor::task] -async fn net_task(stack: &'static Stack>) { - stack.run().await +async fn net_task(mut runner: Runner<'static, WifiDevice<'static, WifiStaDevice>>) { + runner.run().await } diff --git a/examples/async_server.rs b/examples/async_server.rs index eab03eb..d2d237c 100644 --- a/examples/async_server.rs +++ b/examples/async_server.rs @@ -8,11 +8,20 @@ #![feature(type_alias_impl_trait)] #![feature(impl_trait_in_assoc_type)] +// See https://github.com/esp-rs/esp-mbedtls/pull/62#issuecomment-2560830139 +// +// This is by the way a generic way to polyfill the libc functions used by `mbedtls`: +// - If your (baremetal) platform does not provide one or more of these, just +// add a dependency on `tinyrlibc` in your binary crate with features for all missing functions +// and then put such a `use` statement in your main file +#[cfg(feature = "esp32c3")] +use tinyrlibc as _; + #[doc(hidden)] pub use esp_hal as hal; use embassy_net::tcp::TcpSocket; -use embassy_net::{Config, IpListenEndpoint, Stack, StackResources}; +use embassy_net::{Config, IpListenEndpoint, Runner, StackResources}; use embassy_executor::Spawner; use embassy_time::{Duration, Timer}; @@ -26,7 +35,7 @@ use esp_wifi::wifi::{ ClientConfiguration, Configuration, WifiController, WifiDevice, WifiEvent, WifiStaDevice, WifiState, }; -use esp_wifi::{init, EspWifiInitFor}; +use esp_wifi::{init, EspWifiController}; use hal::{prelude::*, rng::Rng, timer::timg::TimerGroup}; // Patch until https://github.com/embassy-rs/static-cell/issues/16 is fixed @@ -56,17 +65,19 @@ async fn main(spawner: Spawner) -> ! { let timg0 = TimerGroup::new(peripherals.TIMG0); - let init = init( - EspWifiInitFor::Wifi, - timg0.timer0, - Rng::new(peripherals.RNG), - peripherals.RADIO_CLK, - ) - .unwrap(); + let init = &*mk_static!( + EspWifiController<'_>, + init( + timg0.timer0, + Rng::new(peripherals.RNG), + peripherals.RADIO_CLK, + ) + .unwrap() + ); let wifi = peripherals.WIFI; let (wifi_interface, controller) = - esp_wifi::wifi::new_with_mode(&init, wifi, WifiStaDevice).unwrap(); + esp_wifi::wifi::new_with_mode(init, wifi, WifiStaDevice).unwrap(); cfg_if::cfg_if! { if #[cfg(feature = "esp32")] { @@ -84,18 +95,15 @@ async fn main(spawner: Spawner) -> ! { let seed = 1234; // very random, very secure seed // Init network stack - let stack = &*mk_static!( - Stack>, - Stack::new( - wifi_interface, - config, - mk_static!(StackResources<3>, StackResources::<3>::new()), - seed - ) + let (stack, runner) = embassy_net::new( + wifi_interface, + config, + mk_static!(StackResources<3>, StackResources::<3>::new()), + seed, ); spawner.spawn(connection(controller)).ok(); - spawner.spawn(net_task(&stack)).ok(); + spawner.spawn(net_task(runner)).ok(); let mut tls = Tls::new(peripherals.SHA) .unwrap() @@ -126,7 +134,7 @@ async fn main(spawner: Spawner) -> ! { Timer::after(Duration::from_millis(500)).await; } - let mut socket = TcpSocket::new(&stack, &mut rx_buffer, &mut tx_buffer); + let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer); socket.set_timeout(Some(Duration::from_secs(10))); loop { println!("Waiting for connection..."); @@ -169,7 +177,7 @@ async fn main(spawner: Spawner) -> ! { println!("Start tls connect"); match session.connect().await { - Ok(_) => { + Ok(()) => { log::info!("Got session"); loop { match session.read(&mut buffer).await { @@ -220,8 +228,8 @@ async fn main(spawner: Spawner) -> ! { panic!("{:?}", error); } } - println!("Closing socket"); drop(session); + println!("Closing socket"); socket.close(); Timer::after(Duration::from_millis(1000)).await; @@ -232,15 +240,12 @@ async fn main(spawner: Spawner) -> ! { #[embassy_executor::task] async fn connection(mut controller: WifiController<'static>) { println!("start connection task"); - println!("Device capabilities: {:?}", controller.get_capabilities()); + println!("Device capabilities: {:?}", controller.capabilities()); loop { - match esp_wifi::wifi::get_wifi_state() { - WifiState::StaConnected => { - // wait until we're no longer connected - controller.wait_for_event(WifiEvent::StaDisconnected).await; - Timer::after(Duration::from_millis(5000)).await - } - _ => {} + if matches!(esp_wifi::wifi::wifi_state(), WifiState::StaConnected) { + // wait until we're no longer connected + controller.wait_for_event(WifiEvent::StaDisconnected).await; + Timer::after(Duration::from_millis(5000)).await } if !matches!(controller.is_started(), Ok(true)) { let client_config = Configuration::Client(ClientConfiguration { @@ -250,12 +255,12 @@ async fn connection(mut controller: WifiController<'static>) { }); controller.set_configuration(&client_config).unwrap(); println!("Starting wifi"); - controller.start().await.unwrap(); + controller.start_async().await.unwrap(); println!("Wifi started!"); } println!("About to connect..."); - match controller.connect().await { + match controller.connect_async().await { Ok(_) => println!("Wifi connected!"), Err(e) => { println!("Failed to connect to wifi: {e:?}"); @@ -266,6 +271,6 @@ async fn connection(mut controller: WifiController<'static>) { } #[embassy_executor::task] -async fn net_task(stack: &'static Stack>) { - stack.run().await +async fn net_task(mut runner: Runner<'static, WifiDevice<'static, WifiStaDevice>>) { + runner.run().await } diff --git a/examples/async_server_mTLS.rs b/examples/async_server_mTLS.rs index 7652aa7..9e46f5c 100644 --- a/examples/async_server_mTLS.rs +++ b/examples/async_server_mTLS.rs @@ -25,14 +25,24 @@ #![feature(impl_trait_in_assoc_type)] #![allow(non_snake_case)] +// See https://github.com/esp-rs/esp-mbedtls/pull/62#issuecomment-2560830139 +// +// This is by the way a generic way to polyfill the libc functions used by `mbedtls`: +// - If your (baremetal) platform does not provide one or more of these, just +// add a dependency on `tinyrlibc` in your binary crate with features for all missing functions +// and then put such a `use` statement in your main file +#[cfg(feature = "esp32c3")] +use tinyrlibc as _; + #[doc(hidden)] pub use esp_hal as hal; use embassy_net::tcp::TcpSocket; -use embassy_net::{Config, IpListenEndpoint, Stack, StackResources}; +use embassy_net::{Config, IpListenEndpoint, Runner, StackResources}; use embassy_executor::Spawner; use embassy_time::{Duration, Timer}; +use esp_alloc as _; use esp_backtrace as _; use esp_mbedtls::{asynch::Session, Certificates, Mode, TlsVersion}; use esp_mbedtls::{Tls, TlsError, X509}; @@ -42,7 +52,7 @@ use esp_wifi::wifi::{ ClientConfiguration, Configuration, WifiController, WifiDevice, WifiEvent, WifiStaDevice, WifiState, }; -use esp_wifi::{init, EspWifiInitFor}; +use esp_wifi::{init, EspWifiController}; use hal::{prelude::*, rng::Rng, timer::timg::TimerGroup}; // Patch until https://github.com/embassy-rs/static-cell/issues/16 is fixed @@ -72,17 +82,19 @@ async fn main(spawner: Spawner) -> ! { let timg0 = TimerGroup::new(peripherals.TIMG0); - let init = init( - EspWifiInitFor::Wifi, - timg0.timer0, - Rng::new(peripherals.RNG), - peripherals.RADIO_CLK, - ) - .unwrap(); + let init = &*mk_static!( + EspWifiController<'_>, + init( + timg0.timer0, + Rng::new(peripherals.RNG), + peripherals.RADIO_CLK, + ) + .unwrap() + ); let wifi = peripherals.WIFI; let (wifi_interface, controller) = - esp_wifi::wifi::new_with_mode(&init, wifi, WifiStaDevice).unwrap(); + esp_wifi::wifi::new_with_mode(init, wifi, WifiStaDevice).unwrap(); cfg_if::cfg_if! { if #[cfg(feature = "esp32")] { @@ -100,18 +112,15 @@ async fn main(spawner: Spawner) -> ! { let seed = 1234; // very random, very secure seed // Init network stack - let stack = &*mk_static!( - Stack>, - Stack::new( - wifi_interface, - config, - mk_static!(StackResources<3>, StackResources::<3>::new()), - seed - ) + let (stack, runner) = embassy_net::new( + wifi_interface, + config, + mk_static!(StackResources<3>, StackResources::<3>::new()), + seed, ); spawner.spawn(connection(controller)).ok(); - spawner.spawn(net_task(&stack)).ok(); + spawner.spawn(net_task(runner)).ok(); let mut tls = Tls::new(peripherals.SHA) .unwrap() @@ -142,7 +151,7 @@ async fn main(spawner: Spawner) -> ! { Timer::after(Duration::from_millis(500)).await; } - let mut socket = TcpSocket::new(&stack, &mut rx_buffer, &mut tx_buffer); + let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer); socket.set_timeout(Some(Duration::from_secs(10))); loop { println!("Waiting for connection..."); @@ -253,15 +262,12 @@ async fn main(spawner: Spawner) -> ! { #[embassy_executor::task] async fn connection(mut controller: WifiController<'static>) { println!("start connection task"); - println!("Device capabilities: {:?}", controller.get_capabilities()); + println!("Device capabilities: {:?}", controller.capabilities()); loop { - match esp_wifi::wifi::get_wifi_state() { - WifiState::StaConnected => { - // wait until we're no longer connected - controller.wait_for_event(WifiEvent::StaDisconnected).await; - Timer::after(Duration::from_millis(5000)).await - } - _ => {} + if matches!(esp_wifi::wifi::wifi_state(), WifiState::StaConnected) { + // wait until we're no longer connected + controller.wait_for_event(WifiEvent::StaDisconnected).await; + Timer::after(Duration::from_millis(5000)).await } if !matches!(controller.is_started(), Ok(true)) { let client_config = Configuration::Client(ClientConfiguration { @@ -271,12 +277,12 @@ async fn connection(mut controller: WifiController<'static>) { }); controller.set_configuration(&client_config).unwrap(); println!("Starting wifi"); - controller.start().await.unwrap(); + controller.start_async().await.unwrap(); println!("Wifi started!"); } println!("About to connect..."); - match controller.connect().await { + match controller.connect_async().await { Ok(_) => println!("Wifi connected!"), Err(e) => { println!("Failed to connect to wifi: {e:?}"); @@ -287,6 +293,6 @@ async fn connection(mut controller: WifiController<'static>) { } #[embassy_executor::task] -async fn net_task(stack: &'static Stack>) { - stack.run().await +async fn net_task(mut runner: Runner<'static, WifiDevice<'static, WifiStaDevice>>) { + runner.run().await } diff --git a/examples/crypto_self_test.rs b/examples/crypto_self_test.rs index 89f0277..f74ce76 100644 --- a/examples/crypto_self_test.rs +++ b/examples/crypto_self_test.rs @@ -2,6 +2,15 @@ #![no_std] #![no_main] +// See https://github.com/esp-rs/esp-mbedtls/pull/62#issuecomment-2560830139 +// +// This is by the way a generic way to polyfill the libc functions used by `mbedtls`: +// - If your (baremetal) platform does not provide one or more of these, just +// add a dependency on `tinyrlibc` in your binary crate with features for all missing functions +// and then put such a `use` statement in your main file +#[cfg(feature = "esp32c3")] +use tinyrlibc as _; + #[doc(hidden)] pub use esp_hal as hal; @@ -12,7 +21,7 @@ use esp_println::{logger::init_logger, println}; /// Only used for ROM functions #[allow(unused_imports)] -use esp_wifi::{init, EspWifiInitFor}; +use esp_wifi::init; use hal::{prelude::*, rng::Rng, timer::timg::TimerGroup}; pub fn cycles() -> u64 { @@ -43,7 +52,6 @@ fn main() -> ! { let timg0 = TimerGroup::new(peripherals.TIMG0); let _init = init( - EspWifiInitFor::Wifi, timg0.timer0, Rng::new(peripherals.RNG), peripherals.RADIO_CLK, @@ -136,5 +144,6 @@ fn main() -> ! { println!("Done"); + #[allow(clippy::empty_loop)] loop {} } diff --git a/examples/edge_server.rs b/examples/edge_server.rs index bbb7200..f1f709f 100644 --- a/examples/edge_server.rs +++ b/examples/edge_server.rs @@ -10,6 +10,15 @@ #![feature(type_alias_impl_trait)] #![feature(impl_trait_in_assoc_type)] +// See https://github.com/esp-rs/esp-mbedtls/pull/62#issuecomment-2560830139 +// +// This is by the way a generic way to polyfill the libc functions used by `mbedtls`: +// - If your (baremetal) platform does not provide one or more of these, just +// add a dependency on `tinyrlibc` in your binary crate with features for all missing functions +// and then put such a `use` statement in your main file +#[cfg(feature = "esp32c3")] +use tinyrlibc as _; + use core::net::{IpAddr, Ipv4Addr, SocketAddr}; #[doc(hidden)] @@ -22,7 +31,7 @@ use edge_nal_embassy::{Tcp, TcpBuffers}; use embedded_io_async::{Read, Write}; -use embassy_net::{Config, Stack, StackResources}; +use embassy_net::{Config, Runner, StackResources}; use embassy_executor::Spawner; use embassy_time::{Duration, Timer}; @@ -35,7 +44,7 @@ use esp_wifi::wifi::{ ClientConfiguration, Configuration, WifiController, WifiDevice, WifiEvent, WifiStaDevice, WifiState, }; -use esp_wifi::{init, EspWifiInitFor}; +use esp_wifi::{init, EspWifiController}; use hal::{prelude::*, rng::Rng, timer::timg::TimerGroup}; // Patch until https://github.com/embassy-rs/static-cell/issues/16 is fixed @@ -76,21 +85,23 @@ async fn main(spawner: Spawner) -> ! { config }); - esp_alloc::heap_allocator!(110 * 1024); + esp_alloc::heap_allocator!(130 * 1024); let timg0 = TimerGroup::new(peripherals.TIMG0); - let init = init( - EspWifiInitFor::Wifi, - timg0.timer0, - Rng::new(peripherals.RNG), - peripherals.RADIO_CLK, - ) - .unwrap(); + let init = &*mk_static!( + EspWifiController<'_>, + init( + timg0.timer0, + Rng::new(peripherals.RNG), + peripherals.RADIO_CLK, + ) + .unwrap() + ); let wifi = peripherals.WIFI; let (wifi_interface, controller) = - esp_wifi::wifi::new_with_mode(&init, wifi, WifiStaDevice).unwrap(); + esp_wifi::wifi::new_with_mode(init, wifi, WifiStaDevice).unwrap(); cfg_if::cfg_if! { if #[cfg(feature = "esp32")] { @@ -108,21 +119,18 @@ async fn main(spawner: Spawner) -> ! { let seed = 1234; // very random, very secure seed // Init network stack - let stack = &*mk_static!( - Stack>, - Stack::new( - wifi_interface, - config, - mk_static!( - StackResources, - StackResources::::new() - ), - seed - ) + let (stack, runner) = embassy_net::new( + wifi_interface, + config, + mk_static!( + StackResources, + StackResources::::new() + ), + seed, ); spawner.spawn(connection(controller)).ok(); - spawner.spawn(net_task(&stack)).ok(); + spawner.spawn(net_task(runner)).ok(); loop { if stack.is_link_up() { @@ -200,7 +208,10 @@ async fn main(spawner: Spawner) -> ! { struct HttpHandler; impl Handler for HttpHandler { - type Error = Error where E: core::fmt::Debug; + type Error + = Error + where + E: core::fmt::Debug; async fn handle( &self, @@ -236,15 +247,12 @@ impl Handler for HttpHandler { #[embassy_executor::task] async fn connection(mut controller: WifiController<'static>) { println!("start connection task"); - println!("Device capabilities: {:?}", controller.get_capabilities()); + println!("Device capabilities: {:?}", controller.capabilities()); loop { - match esp_wifi::wifi::get_wifi_state() { - WifiState::StaConnected => { - // wait until we're no longer connected - controller.wait_for_event(WifiEvent::StaDisconnected).await; - Timer::after(Duration::from_millis(5000)).await - } - _ => {} + if matches!(esp_wifi::wifi::wifi_state(), WifiState::StaConnected) { + // wait until we're no longer connected + controller.wait_for_event(WifiEvent::StaDisconnected).await; + Timer::after(Duration::from_millis(5000)).await } if !matches!(controller.is_started(), Ok(true)) { let client_config = Configuration::Client(ClientConfiguration { @@ -254,12 +262,12 @@ async fn connection(mut controller: WifiController<'static>) { }); controller.set_configuration(&client_config).unwrap(); println!("Starting wifi"); - controller.start().await.unwrap(); + controller.start_async().await.unwrap(); println!("Wifi started!"); } println!("About to connect..."); - match controller.connect().await { + match controller.connect_async().await { Ok(_) => println!("Wifi connected!"), Err(e) => { println!("Failed to connect to wifi: {e:?}"); @@ -270,6 +278,6 @@ async fn connection(mut controller: WifiController<'static>) { } #[embassy_executor::task] -async fn net_task(stack: &'static Stack>) { - stack.run().await +async fn net_task(mut runner: Runner<'static, WifiDevice<'static, WifiStaDevice>>) { + runner.run().await } diff --git a/examples/sync_client.rs b/examples/sync_client.rs index a637404..374de57 100644 --- a/examples/sync_client.rs +++ b/examples/sync_client.rs @@ -3,9 +3,20 @@ #![no_std] #![no_main] +// See https://github.com/esp-rs/esp-mbedtls/pull/62#issuecomment-2560830139 +// +// This is by the way a generic way to polyfill the libc functions used by `mbedtls`: +// - If your (baremetal) platform does not provide one or more of these, just +// add a dependency on `tinyrlibc` in your binary crate with features for all missing functions +// and then put such a `use` statement in your main file +#[cfg(feature = "esp32c3")] +use tinyrlibc as _; + #[doc(hidden)] pub use esp_hal as hal; +use blocking_network_stack::Stack; + use esp_alloc as _; use esp_backtrace as _; use esp_mbedtls::{Certificates, Session}; @@ -14,11 +25,12 @@ use esp_println::{logger::init_logger, print, println}; use esp_wifi::{ init, wifi::{utils::create_network_interface, ClientConfiguration, Configuration, WifiStaDevice}, - wifi_interface::WifiStack, - EspWifiInitFor, }; use hal::{prelude::*, rng::Rng, time, timer::timg::TimerGroup}; -use smoltcp::{iface::SocketStorage, wire::IpAddress}; +use smoltcp11::{ + iface::{SocketSet, SocketStorage}, + wire::IpAddress, +}; const SSID: &str = env!("SSID"); const PASSWORD: &str = env!("PASSWORD"); @@ -36,20 +48,20 @@ fn main() -> ! { let timg0 = TimerGroup::new(peripherals.TIMG0); - let init = init( - EspWifiInitFor::Wifi, - timg0.timer0, - Rng::new(peripherals.RNG), - peripherals.RADIO_CLK, - ) - .unwrap(); + let mut rng = Rng::new(peripherals.RNG); + + let init = init(timg0.timer0, rng, peripherals.RADIO_CLK).unwrap(); let wifi = peripherals.WIFI; + + let (iface, device, mut controller) = + create_network_interface(&init, wifi, WifiStaDevice).unwrap(); + let mut socket_set_entries: [SocketStorage; 3] = Default::default(); - let (iface, device, mut controller, sockets) = - create_network_interface(&init, wifi, WifiStaDevice, &mut socket_set_entries).unwrap(); + let sockets = SocketSet::new(&mut socket_set_entries[..]); + let now = || time::now().duration_since_epoch().to_millis(); - let wifi_stack = WifiStack::new(iface, device, sockets, now); + let wifi_stack = Stack::new(iface, device, sockets, now, rng.random()); println!("Call wifi_connect"); let client_config = Configuration::Client(ClientConfiguration { @@ -72,6 +84,7 @@ fn main() -> ! { } Err(err) => { println!("{:?}", err); + #[allow(clippy::empty_loop)] loop {} } } @@ -138,7 +151,7 @@ fn main() -> ! { match session.read(&mut buffer) { Ok(len) => { print!("{}", unsafe { - core::str::from_utf8_unchecked(&buffer[..len as usize]) + core::str::from_utf8_unchecked(&buffer[..len]) }); } Err(_) => { @@ -149,5 +162,6 @@ fn main() -> ! { } println!("Done"); + #[allow(clippy::empty_loop)] loop {} } diff --git a/examples/sync_client_mTLS.rs b/examples/sync_client_mTLS.rs index db3b2b5..8928884 100644 --- a/examples/sync_client_mTLS.rs +++ b/examples/sync_client_mTLS.rs @@ -1,11 +1,21 @@ //! Example for a client connection using certificate authentication (mTLS) #![no_std] #![no_main] -#![allow(non_snake_case)] + +// See https://github.com/esp-rs/esp-mbedtls/pull/62#issuecomment-2560830139 +// +// This is by the way a generic way to polyfill the libc functions used by `mbedtls`: +// - If your (baremetal) platform does not provide one or more of these, just +// add a dependency on `tinyrlibc` in your binary crate with features for all missing functions +// and then put such a `use` statement in your main file +#[cfg(feature = "esp32c3")] +use tinyrlibc as _; #[doc(hidden)] pub use esp_hal as hal; +use blocking_network_stack::Stack; + use esp_alloc as _; use esp_backtrace as _; use esp_mbedtls::{Certificates, Session}; @@ -14,11 +24,12 @@ use esp_println::{logger::init_logger, print, println}; use esp_wifi::{ init, wifi::{utils::create_network_interface, ClientConfiguration, Configuration, WifiStaDevice}, - wifi_interface::WifiStack, - EspWifiInitFor, }; use hal::{prelude::*, rng::Rng, time, timer::timg::TimerGroup}; -use smoltcp::{iface::SocketStorage, wire::IpAddress}; +use smoltcp11::{ + iface::{SocketSet, SocketStorage}, + wire::IpAddress, +}; const SSID: &str = env!("SSID"); const PASSWORD: &str = env!("PASSWORD"); @@ -26,7 +37,6 @@ const PASSWORD: &str = env!("PASSWORD"); #[entry] fn main() -> ! { init_logger(log::LevelFilter::Info); - let peripherals = esp_hal::init({ let mut config = esp_hal::Config::default(); config.cpu_clock = CpuClock::max(); @@ -37,20 +47,20 @@ fn main() -> ! { let timg0 = TimerGroup::new(peripherals.TIMG0); - let init = init( - EspWifiInitFor::Wifi, - timg0.timer0, - Rng::new(peripherals.RNG), - peripherals.RADIO_CLK, - ) - .unwrap(); + let mut rng = Rng::new(peripherals.RNG); + + let init = init(timg0.timer0, rng, peripherals.RADIO_CLK).unwrap(); let wifi = peripherals.WIFI; + + let (iface, device, mut controller) = + create_network_interface(&init, wifi, WifiStaDevice).unwrap(); + let mut socket_set_entries: [SocketStorage; 3] = Default::default(); - let (iface, device, mut controller, sockets) = - create_network_interface(&init, wifi, WifiStaDevice, &mut socket_set_entries).unwrap(); + let sockets = SocketSet::new(&mut socket_set_entries[..]); + let now = || time::now().duration_since_epoch().to_millis(); - let wifi_stack = WifiStack::new(iface, device, sockets, now); + let wifi_stack = Stack::new(iface, device, sockets, now, rng.random()); println!("Call wifi_connect"); let client_config = Configuration::Client(ClientConfiguration { @@ -73,6 +83,7 @@ fn main() -> ! { } Err(err) => { println!("{:?}", err); + #[allow(clippy::empty_loop)] loop {} } } @@ -145,7 +156,7 @@ fn main() -> ! { match session.read(&mut buffer) { Ok(len) => { print!("{}", unsafe { - core::str::from_utf8_unchecked(&buffer[..len as usize]) + core::str::from_utf8_unchecked(&buffer[..len]) }); } Err(_) => { @@ -156,5 +167,6 @@ fn main() -> ! { } println!("Done"); + #[allow(clippy::empty_loop)] loop {} } diff --git a/examples/sync_server.rs b/examples/sync_server.rs index e6dd11b..916748d 100644 --- a/examples/sync_server.rs +++ b/examples/sync_server.rs @@ -6,9 +6,20 @@ #![no_std] #![no_main] +// See https://github.com/esp-rs/esp-mbedtls/pull/62#issuecomment-2560830139 +// +// This is by the way a generic way to polyfill the libc functions used by `mbedtls`: +// - If your (baremetal) platform does not provide one or more of these, just +// add a dependency on `tinyrlibc` in your binary crate with features for all missing functions +// and then put such a `use` statement in your main file +#[cfg(feature = "esp32c3")] +use tinyrlibc as _; + #[doc(hidden)] pub use esp_hal as hal; +use blocking_network_stack::Stack; + use embedded_io::*; use esp_backtrace as _; use esp_mbedtls::{Certificates, Session}; @@ -17,11 +28,9 @@ use esp_println::{logger::init_logger, print, println}; use esp_wifi::{ init, wifi::{utils::create_network_interface, ClientConfiguration, Configuration, WifiStaDevice}, - wifi_interface::WifiStack, - EspWifiInitFor, }; use hal::{prelude::*, rng::Rng, time, timer::timg::TimerGroup}; -use smoltcp::iface::SocketStorage; +use smoltcp11::iface::{SocketSet, SocketStorage}; const SSID: &str = env!("SSID"); const PASSWORD: &str = env!("PASSWORD"); @@ -29,7 +38,6 @@ const PASSWORD: &str = env!("PASSWORD"); #[entry] fn main() -> ! { init_logger(log::LevelFilter::Info); - let peripherals = esp_hal::init({ let mut config = esp_hal::Config::default(); config.cpu_clock = CpuClock::max(); @@ -40,20 +48,20 @@ fn main() -> ! { let timg0 = TimerGroup::new(peripherals.TIMG0); - let init = init( - EspWifiInitFor::Wifi, - timg0.timer0, - Rng::new(peripherals.RNG), - peripherals.RADIO_CLK, - ) - .unwrap(); + let mut rng = Rng::new(peripherals.RNG); + + let init = init(timg0.timer0, rng, peripherals.RADIO_CLK).unwrap(); let wifi = peripherals.WIFI; + + let (iface, device, mut controller) = + create_network_interface(&init, wifi, WifiStaDevice).unwrap(); + let mut socket_set_entries: [SocketStorage; 3] = Default::default(); - let (iface, device, mut controller, sockets) = - create_network_interface(&init, wifi, WifiStaDevice, &mut socket_set_entries).unwrap(); + let sockets = SocketSet::new(&mut socket_set_entries[..]); + let now = || time::now().duration_since_epoch().to_millis(); - let wifi_stack = WifiStack::new(iface, device, sockets, now); + let wifi_stack = Stack::new(iface, device, sockets, now, rng.random()); println!("Call wifi_connect"); let client_config = Configuration::Client(ClientConfiguration { @@ -76,6 +84,7 @@ fn main() -> ! { } Err(err) => { println!("{:?}", err); + #[allow(clippy::empty_loop)] loop {} } } @@ -147,22 +156,18 @@ fn main() -> ! { match session.connect() { Ok(_) => { - loop { - if let Ok(len) = session.read(&mut buffer[pos..]) { - let to_print = - unsafe { core::str::from_utf8_unchecked(&buffer[..(pos + len)]) }; - - if to_print.contains("\r\n\r\n") { - print!("{}", to_print); - println!(); - break; - } - - pos += len; - } else { + while let Ok(len) = session.read(&mut buffer[pos..]) { + let to_print = + unsafe { core::str::from_utf8_unchecked(&buffer[..(pos + len)]) }; + + if to_print.contains("\r\n\r\n") { + print!("{}", to_print); + println!(); break; } + pos += len; + if now() > wait_end { println!("Timed out"); time_out = true; diff --git a/examples/sync_server_mTLS.rs b/examples/sync_server_mTLS.rs index 03ec14f..db52fe3 100644 --- a/examples/sync_server_mTLS.rs +++ b/examples/sync_server_mTLS.rs @@ -21,11 +21,21 @@ //! ``` #![no_std] #![no_main] -#![allow(non_snake_case)] + +// See https://github.com/esp-rs/esp-mbedtls/pull/62#issuecomment-2560830139 +// +// This is by the way a generic way to polyfill the libc functions used by `mbedtls`: +// - If your (baremetal) platform does not provide one or more of these, just +// add a dependency on `tinyrlibc` in your binary crate with features for all missing functions +// and then put such a `use` statement in your main file +#[cfg(feature = "esp32c3")] +use tinyrlibc as _; #[doc(hidden)] pub use esp_hal as hal; +use blocking_network_stack::Stack; + use embedded_io::*; use esp_backtrace as _; use esp_mbedtls::{Certificates, Session}; @@ -34,11 +44,9 @@ use esp_println::{logger::init_logger, print, println}; use esp_wifi::{ init, wifi::{utils::create_network_interface, ClientConfiguration, Configuration, WifiStaDevice}, - wifi_interface::WifiStack, - EspWifiInitFor, }; use hal::{prelude::*, rng::Rng, time, timer::timg::TimerGroup}; -use smoltcp::iface::SocketStorage; +use smoltcp11::iface::{SocketSet, SocketStorage}; const SSID: &str = env!("SSID"); const PASSWORD: &str = env!("PASSWORD"); @@ -46,7 +54,6 @@ const PASSWORD: &str = env!("PASSWORD"); #[entry] fn main() -> ! { init_logger(log::LevelFilter::Info); - let peripherals = esp_hal::init({ let mut config = esp_hal::Config::default(); config.cpu_clock = CpuClock::max(); @@ -57,20 +64,20 @@ fn main() -> ! { let timg0 = TimerGroup::new(peripherals.TIMG0); - let init = init( - EspWifiInitFor::Wifi, - timg0.timer0, - Rng::new(peripherals.RNG), - peripherals.RADIO_CLK, - ) - .unwrap(); + let mut rng = Rng::new(peripherals.RNG); + + let init = init(timg0.timer0, rng, peripherals.RADIO_CLK).unwrap(); let wifi = peripherals.WIFI; + + let (iface, device, mut controller) = + create_network_interface(&init, wifi, WifiStaDevice).unwrap(); + let mut socket_set_entries: [SocketStorage; 3] = Default::default(); - let (iface, device, mut controller, sockets) = - create_network_interface(&init, wifi, WifiStaDevice, &mut socket_set_entries).unwrap(); + let sockets = SocketSet::new(&mut socket_set_entries[..]); + let now = || time::now().duration_since_epoch().to_millis(); - let wifi_stack = WifiStack::new(iface, device, sockets, now); + let wifi_stack = Stack::new(iface, device, sockets, now, rng.random()); println!("Call wifi_connect"); let client_config = Configuration::Client(ClientConfiguration { @@ -93,6 +100,7 @@ fn main() -> ! { } Err(err) => { println!("{:?}", err); + #[allow(clippy::empty_loop)] loop {} } } @@ -168,22 +176,18 @@ fn main() -> ! { match session.connect() { Ok(_) => { - loop { - if let Ok(len) = session.read(&mut buffer[pos..]) { - let to_print = - unsafe { core::str::from_utf8_unchecked(&buffer[..(pos + len)]) }; - - if to_print.contains("\r\n\r\n") { - print!("{}", to_print); - println!(); - break; - } - - pos += len; - } else { + while let Ok(len) = session.read(&mut buffer[pos..]) { + let to_print = + unsafe { core::str::from_utf8_unchecked(&buffer[..(pos + len)]) }; + + if to_print.contains("\r\n\r\n") { + print!("{}", to_print); + println!(); break; } + pos += len; + if now() > wait_end { println!("Timed out"); time_out = true; diff --git a/justfile b/justfile index bec88b0..104ee0f 100644 --- a/justfile +++ b/justfile @@ -1,8 +1,8 @@ export SSID := "Dummy" export PASSWORD := "Dummy" -all: (check "esp32" "esp") (check "esp32s3" "esp") (check "esp32c3" "nightly-2024-07-22") - cd esp-mbedtls && cargo +nightly-2024-07-22 fmt --all -- --check +all: (check "esp32" "esp") (check "esp32s3" "esp") (check "esp32c3" "nightly-2024-12-01") + cd esp-mbedtls && cargo +nightly-2024-12-01 fmt --all -- --check [private] check arch toolchain: