From 773dba3f12d6178dbae1a752f64cf3c9eb09a6c9 Mon Sep 17 00:00:00 2001 From: ivmarkov Date: Thu, 2 Jan 2025 18:35:21 +0000 Subject: [PATCH 01/13] Update esp-hal, esp-wifi, esp-idf and edge-net dependencies --- .cargo/config.toml | 4 --- Cargo.toml | 52 +++++++++++++-------------- esp-mbedtls-sys/Cargo.toml | 8 ++--- esp-mbedtls/Cargo.toml | 6 ++-- esp-mbedtls/src/edge_nal.rs | 17 +++++++++ examples/async_client.rs | 65 +++++++++++++++++----------------- examples/async_client_mTLS.rs | 65 +++++++++++++++++----------------- examples/async_server.rs | 66 +++++++++++++++++------------------ examples/async_server_mTLS.rs | 63 ++++++++++++++++----------------- examples/crypto_self_test.rs | 4 +-- examples/edge_server.rs | 66 +++++++++++++++-------------------- examples/sync_client.rs | 33 ++++++++++-------- examples/sync_client_mTLS.rs | 35 ++++++++++--------- examples/sync_server.rs | 50 ++++++++++++-------------- examples/sync_server_mTLS.rs | 51 ++++++++++++--------------- 15 files changed, 292 insertions(+), 293 deletions(-) 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/Cargo.toml b/Cargo.toml index 01a0cf1..867b9e0 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,15 @@ 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 } [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 +114,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 = [ @@ -142,18 +152,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..f80b723 100644 --- a/esp-mbedtls/src/edge_nal.rs +++ b/esp-mbedtls/src/edge_nal.rs @@ -151,6 +151,23 @@ 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/examples/async_client.rs b/examples/async_client.rs index 8721473..6c2b94b 100644 --- a/examples/async_client.rs +++ b/examples/async_client.rs @@ -9,7 +9,7 @@ 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 +22,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 +52,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 +82,17 @@ 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, ); + let runner = mk_static!(Runner<'_, WifiDevice<'static, WifiStaDevice>>, runner); + 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 +113,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 +122,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 +162,7 @@ async fn main(spawner: Spawner) -> ! { .await; if let Err(e) = r { println!("write error: {:?}", e); + #[allow(clippy::empty_loop)] loop {} } @@ -179,21 +182,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 +204,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 +220,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(runner: &'static mut Runner<'static, WifiDevice<'static, WifiStaDevice>>) { + runner.run().await } diff --git a/examples/async_client_mTLS.rs b/examples/async_client_mTLS.rs index 2f0da30..df9de5b 100644 --- a/examples/async_client_mTLS.rs +++ b/examples/async_client_mTLS.rs @@ -10,7 +10,7 @@ use embassy_executor::Spawner; 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_time::{Duration, Timer}; use esp_backtrace as _; @@ -22,7 +22,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 +52,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 +82,17 @@ 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, ); + let runner = mk_static!(Runner<'_, WifiDevice<'static, WifiStaDevice>>, runner); + 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 +113,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 +122,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 {} } @@ -166,6 +168,7 @@ async fn main(spawner: Spawner) -> ! { .await; if let Err(e) = r { println!("write error: {:?}", e); + #[allow(clippy::empty_loop)] loop {} } @@ -184,21 +187,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 +209,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 +225,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(runner: &'static mut Runner<'static, WifiDevice<'static, WifiStaDevice>>) { + runner.run().await } diff --git a/examples/async_server.rs b/examples/async_server.rs index eab03eb..718d1d0 100644 --- a/examples/async_server.rs +++ b/examples/async_server.rs @@ -12,7 +12,7 @@ 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 +26,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 +56,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 +86,17 @@ 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, ); + let runner = mk_static!(Runner<'_, WifiDevice<'static, WifiStaDevice>>, runner); + 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 +127,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 +170,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 +221,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 +233,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 +248,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 +264,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(runner: &'static mut Runner<'static, WifiDevice<'static, WifiStaDevice>>) { + runner.run().await } diff --git a/examples/async_server_mTLS.rs b/examples/async_server_mTLS.rs index 7652aa7..8587c7b 100644 --- a/examples/async_server_mTLS.rs +++ b/examples/async_server_mTLS.rs @@ -29,10 +29,11 @@ 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 +43,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 +73,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 +103,17 @@ 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, ); + let runner = mk_static!(Runner<'_, WifiDevice<'static, WifiStaDevice>>, runner); + 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 +144,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 +255,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 +270,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 +286,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(runner: &'static mut Runner<'static, WifiDevice<'static, WifiStaDevice>>) { + runner.run().await } diff --git a/examples/crypto_self_test.rs b/examples/crypto_self_test.rs index 89f0277..88dfee8 100644 --- a/examples/crypto_self_test.rs +++ b/examples/crypto_self_test.rs @@ -12,7 +12,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 +43,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 +135,6 @@ fn main() -> ! { println!("Done"); + #[allow(clippy::empty_loop)] loop {} } diff --git a/examples/edge_server.rs b/examples/edge_server.rs index bbb7200..2c82388 100644 --- a/examples/edge_server.rs +++ b/examples/edge_server.rs @@ -22,7 +22,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 +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 @@ -57,9 +57,6 @@ const SERVER_SOCKETS: usize = 1; #[cfg(not(feature = "esp32"))] const SERVER_SOCKETS: usize = 2; -/// Total number of sockets used for the application -const SOCKET_COUNT: usize = 1 + 1 + SERVER_SOCKETS; // DHCP + DNS + Server - const RX_SIZE: usize = 4096; const TX_SIZE: usize = 2048; @@ -80,17 +77,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")] { @@ -108,21 +107,17 @@ 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<3>, StackResources::<3>::new()), + seed, ); + let runner = mk_static!(Runner<'_, WifiDevice<'static, WifiStaDevice>>, runner); + spawner.spawn(connection(controller)).ok(); - spawner.spawn(net_task(&stack)).ok(); + spawner.spawn(net_task(runner)).ok(); loop { if stack.is_link_up() { @@ -236,15 +231,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 +246,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 +262,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(runner: &'static mut Runner<'static, WifiDevice<'static, WifiStaDevice>>) { + runner.run().await } diff --git a/examples/sync_client.rs b/examples/sync_client.rs index a637404..d7c1681 100644 --- a/examples/sync_client.rs +++ b/examples/sync_client.rs @@ -6,6 +6,8 @@ #[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 +16,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 +39,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 +75,7 @@ fn main() -> ! { } Err(err) => { println!("{:?}", err); + #[allow(clippy::empty_loop)] loop {} } } @@ -138,7 +142,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 +153,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..0c92bcf 100644 --- a/examples/sync_client_mTLS.rs +++ b/examples/sync_client_mTLS.rs @@ -1,11 +1,12 @@ //! Example for a client connection using certificate authentication (mTLS) #![no_std] #![no_main] -#![allow(non_snake_case)] #[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 +15,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 +28,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 +38,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 +74,7 @@ fn main() -> ! { } Err(err) => { println!("{:?}", err); + #[allow(clippy::empty_loop)] loop {} } } @@ -145,7 +147,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 +158,6 @@ fn main() -> ! { } println!("Done"); + #[allow(clippy::empty_loop)] loop {} } diff --git a/examples/sync_server.rs b/examples/sync_server.rs index e6dd11b..e50ef2c 100644 --- a/examples/sync_server.rs +++ b/examples/sync_server.rs @@ -9,6 +9,8 @@ #[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 +19,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 +29,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 +39,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 +75,7 @@ fn main() -> ! { } Err(err) => { println!("{:?}", err); + #[allow(clippy::empty_loop)] loop {} } } @@ -147,22 +147,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..574d003 100644 --- a/examples/sync_server_mTLS.rs +++ b/examples/sync_server_mTLS.rs @@ -21,11 +21,12 @@ //! ``` #![no_std] #![no_main] -#![allow(non_snake_case)] #[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 +35,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 +45,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 +55,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 +91,7 @@ fn main() -> ! { } Err(err) => { println!("{:?}", err); + #[allow(clippy::empty_loop)] loop {} } } @@ -168,22 +167,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; From 6f360a491ec1b3c732d927e91c3404e865c9f2d3 Mon Sep 17 00:00:00 2001 From: ivmarkov Date: Sun, 5 Jan 2025 09:27:15 +0000 Subject: [PATCH 02/13] Polyfill the missing memchr impl in latest esp-hal --- esp-mbedtls/Cargo.toml | 3 ++- esp-mbedtls/src/esp_hal.rs | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/esp-mbedtls/Cargo.toml b/esp-mbedtls/Cargo.toml index 2e52d47..ed20ee5 100644 --- a/esp-mbedtls/Cargo.toml +++ b/esp-mbedtls/Cargo.toml @@ -23,12 +23,13 @@ cfg-if = "1.0.0" 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"] } +tinyrlibc = { version = "0.5", optional = true, default-features = false } [features] default = ["edge-nal"] async = ["dep:embedded-io-async"] esp32 = ["esp-hal/esp32", "esp-wifi/esp32", "esp-mbedtls-sys/esp32", "crypto-bigint"] -esp32c3 = ["esp-hal/esp32c3", "esp-wifi/esp32c3", "esp-mbedtls-sys/esp32c3", "crypto-bigint"] +esp32c3 = ["esp-hal/esp32c3", "esp-wifi/esp32c3", "esp-mbedtls-sys/esp32c3", "crypto-bigint", "tinyrlibc/memchr"] esp32s2 = ["esp-hal/esp32s2", "esp-wifi/esp32s2", "esp-mbedtls-sys/esp32s2", "crypto-bigint"] esp32s3 = ["esp-hal/esp32s3", "esp-wifi/esp32s3", "esp-mbedtls-sys/esp32s3", "crypto-bigint"] diff --git a/esp-mbedtls/src/esp_hal.rs b/esp-mbedtls/src/esp_hal.rs index c688fa5..fd86394 100644 --- a/esp-mbedtls/src/esp_hal.rs +++ b/esp-mbedtls/src/esp_hal.rs @@ -66,3 +66,17 @@ impl Drop for Tls<'_> { critical_section::with(|cs| SHARED_SHA.borrow_ref_mut(cs).take()); } } + +// See https://github.com/esp-rs/esp-mbedtls/pull/62#issuecomment-2560830139 +// TODO: In future - and for all baremetal platforms - we should be having a definition like the one below +// for **all** libc functions used by `mbedtls` +// +// And then each baremetal platform can decide to opt-in and use the definition(s) +// from `tinyrlibc` or opt-out and provide their own implementation(s) +#[cfg(feature = "esp32c3")] +#[used] +static _MEMCHR: unsafe extern "C" fn( + *const core::ffi::c_void, + core::ffi::c_int, + usize, +) -> *const core::ffi::c_void = tinyrlibc::memchr; From dea21dcf48fbd70febc9a829ec8c8179ce11ef56 Mon Sep 17 00:00:00 2001 From: ivmarkov Date: Sun, 5 Jan 2025 13:06:22 +0000 Subject: [PATCH 03/13] fmt; increase sockets count for esp32s3 --- examples/edge_server.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/examples/edge_server.rs b/examples/edge_server.rs index 2c82388..243b725 100644 --- a/examples/edge_server.rs +++ b/examples/edge_server.rs @@ -110,7 +110,7 @@ async fn main(spawner: Spawner) -> ! { let (stack, runner) = embassy_net::new( wifi_interface, config, - mk_static!(StackResources<3>, StackResources::<3>::new()), + mk_static!(StackResources<4>, StackResources::<4>::new()), seed, ); @@ -195,7 +195,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, From 0dbe3a38a31684168f068982208488ffdc1c9d64 Mon Sep 17 00:00:00 2001 From: ivmarkov Date: Sun, 5 Jan 2025 13:06:39 +0000 Subject: [PATCH 04/13] Switch to 2024-12-01 nightly --- .github/workflows/ci.yml | 2 +- justfile | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) 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/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: From a82f5501f1c4ba2ba9edac4d00b12cf1cea3ac16 Mon Sep 17 00:00:00 2001 From: ivmarkov Date: Sun, 5 Jan 2025 13:22:30 +0000 Subject: [PATCH 05/13] fmt --- esp-mbedtls/src/edge_nal.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/esp-mbedtls/src/edge_nal.rs b/esp-mbedtls/src/edge_nal.rs index f80b723..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 @@ -155,11 +161,13 @@ 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 + type Read<'a> + = Self where Self: 'a; - type Write<'a> = Self + type Write<'a> + = Self where Self: 'a; From 75b3b0f3420d1babb82b429f1581be9a3c894890 Mon Sep 17 00:00:00 2001 From: ivmarkov Date: Sun, 5 Jan 2025 19:21:59 +0000 Subject: [PATCH 06/13] Something (esp-hal?) needs more heap now --- examples/edge_server.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/edge_server.rs b/examples/edge_server.rs index 243b725..df321b5 100644 --- a/examples/edge_server.rs +++ b/examples/edge_server.rs @@ -73,7 +73,7 @@ async fn main(spawner: Spawner) -> ! { config }); - esp_alloc::heap_allocator!(110 * 1024); + esp_alloc::heap_allocator!(130 * 1024); let timg0 = TimerGroup::new(peripherals.TIMG0); From 8a9e7b09a85fe91c4f0e4f4cf8b74a28eddbb448 Mon Sep 17 00:00:00 2001 From: ivmarkov Date: Sun, 5 Jan 2025 19:48:11 +0000 Subject: [PATCH 07/13] Fix a potential issue when writing; increase memory for the edge_server example --- esp-mbedtls/src/lib.rs | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/esp-mbedtls/src/lib.rs b/esp-mbedtls/src/lib.rs index fd8e358..03bc6a8 100644 --- a/esp-mbedtls/src/lib.rs +++ b/esp-mbedtls/src/lib.rs @@ -1176,16 +1176,19 @@ pub mod asynch { F: FnMut(*mut mbedtls_ssl_context) -> i32, { loop { + 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 +1212,8 @@ pub mod asynch { .map_err(|e| TlsError::Io(e.kind()))?; if len > 0 { self.read_byte = Some(buf[0]); + } else { + Err(TlsError::Eof)?; } } @@ -1230,6 +1235,8 @@ pub mod asynch { .map_err(|e| TlsError::Io(e.kind()))?; if len > 0 { self.write_byte.take(); + } else { + Err(TlsError::Eof)?; } } @@ -1395,7 +1402,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; } From de288bef2b2e168fc85528e5c4194e03afc02e76 Mon Sep 17 00:00:00 2001 From: ivmarkov Date: Wed, 8 Jan 2025 20:46:11 +0000 Subject: [PATCH 08/13] Address code review feedback --- esp-mbedtls/src/lib.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/esp-mbedtls/src/lib.rs b/esp-mbedtls/src/lib.rs index 03bc6a8..9521efd 100644 --- a/esp-mbedtls/src/lib.rs +++ b/esp-mbedtls/src/lib.rs @@ -1176,6 +1176,13 @@ 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 function) + // 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 = @@ -1213,6 +1220,9 @@ pub mod asynch { 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)?; } } @@ -1236,6 +1246,9 @@ pub mod asynch { 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)?; } } From 7a0341153dec08d6f9492b50b782f03a9429f986 Mon Sep 17 00:00:00 2001 From: ivmarkov Date: Wed, 8 Jan 2025 21:03:10 +0000 Subject: [PATCH 09/13] Much cleaner way to polyfill missing libc functions --- Cargo.toml | 3 +++ esp-mbedtls/Cargo.toml | 3 +-- esp-mbedtls/src/esp_hal.rs | 14 -------------- examples/async_client.rs | 9 +++++++++ examples/async_client_mTLS.rs | 12 +++++++++++- examples/async_server.rs | 9 +++++++++ examples/async_server_mTLS.rs | 9 +++++++++ examples/crypto_self_test.rs | 9 +++++++++ examples/edge_server.rs | 9 +++++++++ examples/sync_client.rs | 9 +++++++++ examples/sync_client_mTLS.rs | 9 +++++++++ examples/sync_server.rs | 9 +++++++++ examples/sync_server_mTLS.rs | 9 +++++++++ 13 files changed, 96 insertions(+), 17 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 867b9e0..2769707 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -83,6 +83,8 @@ 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.50", features = ["binstart"] } @@ -133,6 +135,7 @@ esp32c3 = [ "esp-println?/esp32c3", "esp-wifi?/esp32c3", "esp-mbedtls/esp32c3", + "tinyrlibc/memchr", ] esp32s2 = [ "esp-hal?/esp32s2", diff --git a/esp-mbedtls/Cargo.toml b/esp-mbedtls/Cargo.toml index ed20ee5..2e52d47 100644 --- a/esp-mbedtls/Cargo.toml +++ b/esp-mbedtls/Cargo.toml @@ -23,13 +23,12 @@ cfg-if = "1.0.0" 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"] } -tinyrlibc = { version = "0.5", optional = true, default-features = false } [features] default = ["edge-nal"] async = ["dep:embedded-io-async"] esp32 = ["esp-hal/esp32", "esp-wifi/esp32", "esp-mbedtls-sys/esp32", "crypto-bigint"] -esp32c3 = ["esp-hal/esp32c3", "esp-wifi/esp32c3", "esp-mbedtls-sys/esp32c3", "crypto-bigint", "tinyrlibc/memchr"] +esp32c3 = ["esp-hal/esp32c3", "esp-wifi/esp32c3", "esp-mbedtls-sys/esp32c3", "crypto-bigint"] esp32s2 = ["esp-hal/esp32s2", "esp-wifi/esp32s2", "esp-mbedtls-sys/esp32s2", "crypto-bigint"] esp32s3 = ["esp-hal/esp32s3", "esp-wifi/esp32s3", "esp-mbedtls-sys/esp32s3", "crypto-bigint"] diff --git a/esp-mbedtls/src/esp_hal.rs b/esp-mbedtls/src/esp_hal.rs index fd86394..c688fa5 100644 --- a/esp-mbedtls/src/esp_hal.rs +++ b/esp-mbedtls/src/esp_hal.rs @@ -66,17 +66,3 @@ impl Drop for Tls<'_> { critical_section::with(|cs| SHARED_SHA.borrow_ref_mut(cs).take()); } } - -// See https://github.com/esp-rs/esp-mbedtls/pull/62#issuecomment-2560830139 -// TODO: In future - and for all baremetal platforms - we should be having a definition like the one below -// for **all** libc functions used by `mbedtls` -// -// And then each baremetal platform can decide to opt-in and use the definition(s) -// from `tinyrlibc` or opt-out and provide their own implementation(s) -#[cfg(feature = "esp32c3")] -#[used] -static _MEMCHR: unsafe extern "C" fn( - *const core::ffi::c_void, - core::ffi::c_int, - usize, -) -> *const core::ffi::c_void = tinyrlibc::memchr; diff --git a/examples/async_client.rs b/examples/async_client.rs index 6c2b94b..5e08cbf 100644 --- a/examples/async_client.rs +++ b/examples/async_client.rs @@ -5,6 +5,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 _; + #[doc(hidden)] pub use esp_hal as hal; diff --git a/examples/async_client_mTLS.rs b/examples/async_client_mTLS.rs index df9de5b..754fbb3 100644 --- a/examples/async_client_mTLS.rs +++ b/examples/async_client_mTLS.rs @@ -5,10 +5,20 @@ #![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, Runner, StackResources}; diff --git a/examples/async_server.rs b/examples/async_server.rs index 718d1d0..5d390b7 100644 --- a/examples/async_server.rs +++ b/examples/async_server.rs @@ -8,6 +8,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 _; + #[doc(hidden)] pub use esp_hal as hal; diff --git a/examples/async_server_mTLS.rs b/examples/async_server_mTLS.rs index 8587c7b..2000cda 100644 --- a/examples/async_server_mTLS.rs +++ b/examples/async_server_mTLS.rs @@ -25,6 +25,15 @@ #![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; diff --git a/examples/crypto_self_test.rs b/examples/crypto_self_test.rs index 88dfee8..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; diff --git a/examples/edge_server.rs b/examples/edge_server.rs index df321b5..f0cab6e 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)] diff --git a/examples/sync_client.rs b/examples/sync_client.rs index d7c1681..374de57 100644 --- a/examples/sync_client.rs +++ b/examples/sync_client.rs @@ -3,6 +3,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; diff --git a/examples/sync_client_mTLS.rs b/examples/sync_client_mTLS.rs index 0c92bcf..8928884 100644 --- a/examples/sync_client_mTLS.rs +++ b/examples/sync_client_mTLS.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; diff --git a/examples/sync_server.rs b/examples/sync_server.rs index e50ef2c..916748d 100644 --- a/examples/sync_server.rs +++ b/examples/sync_server.rs @@ -6,6 +6,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; diff --git a/examples/sync_server_mTLS.rs b/examples/sync_server_mTLS.rs index 574d003..db52fe3 100644 --- a/examples/sync_server_mTLS.rs +++ b/examples/sync_server_mTLS.rs @@ -22,6 +22,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; From 16e539c543465c2e9eec23dff56914fb3bfa4b53 Mon Sep 17 00:00:00 2001 From: ivmarkov Date: Wed, 8 Jan 2025 21:18:55 +0000 Subject: [PATCH 10/13] Properly calculate necessary sockets --- examples/edge_server.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/examples/edge_server.rs b/examples/edge_server.rs index f0cab6e..bb988bf 100644 --- a/examples/edge_server.rs +++ b/examples/edge_server.rs @@ -66,6 +66,9 @@ const SERVER_SOCKETS: usize = 1; #[cfg(not(feature = "esp32"))] const SERVER_SOCKETS: usize = 2; +/// Total number of sockets used for the application +const SOCKET_COUNT: usize = 1 + 1 + SERVER_SOCKETS; // DHCP + DNS + Server + const RX_SIZE: usize = 4096; const TX_SIZE: usize = 2048; @@ -119,7 +122,10 @@ async fn main(spawner: Spawner) -> ! { let (stack, runner) = embassy_net::new( wifi_interface, config, - mk_static!(StackResources<4>, StackResources::<4>::new()), + mk_static!( + StackResources, + StackResources::::new() + ), seed, ); From f05c052a8077b2ba2315bd3118731d8088378cda Mon Sep 17 00:00:00 2001 From: ivmarkov Date: Wed, 8 Jan 2025 21:23:11 +0000 Subject: [PATCH 11/13] Remove unnecessary call to mk_static --- examples/async_client.rs | 4 +--- examples/async_client_mTLS.rs | 4 +--- examples/async_server.rs | 4 +--- examples/async_server_mTLS.rs | 4 +--- examples/edge_server.rs | 4 +--- 5 files changed, 5 insertions(+), 15 deletions(-) diff --git a/examples/async_client.rs b/examples/async_client.rs index 5e08cbf..2deec9a 100644 --- a/examples/async_client.rs +++ b/examples/async_client.rs @@ -98,8 +98,6 @@ async fn main(spawner: Spawner) -> ! { seed, ); - let runner = mk_static!(Runner<'_, WifiDevice<'static, WifiStaDevice>>, runner); - spawner.spawn(connection(controller)).ok(); spawner.spawn(net_task(runner)).ok(); @@ -229,6 +227,6 @@ async fn connection(mut controller: WifiController<'static>) { } #[embassy_executor::task] -async fn net_task(runner: &'static mut Runner<'static, WifiDevice<'static, WifiStaDevice>>) { +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 754fbb3..f833487 100644 --- a/examples/async_client_mTLS.rs +++ b/examples/async_client_mTLS.rs @@ -99,8 +99,6 @@ async fn main(spawner: Spawner) -> ! { seed, ); - let runner = mk_static!(Runner<'_, WifiDevice<'static, WifiStaDevice>>, runner); - spawner.spawn(connection(controller)).ok(); spawner.spawn(net_task(runner)).ok(); @@ -235,6 +233,6 @@ async fn connection(mut controller: WifiController<'static>) { } #[embassy_executor::task] -async fn net_task(runner: &'static mut Runner<'static, WifiDevice<'static, WifiStaDevice>>) { +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 5d390b7..d2d237c 100644 --- a/examples/async_server.rs +++ b/examples/async_server.rs @@ -102,8 +102,6 @@ async fn main(spawner: Spawner) -> ! { seed, ); - let runner = mk_static!(Runner<'_, WifiDevice<'static, WifiStaDevice>>, runner); - spawner.spawn(connection(controller)).ok(); spawner.spawn(net_task(runner)).ok(); @@ -273,6 +271,6 @@ async fn connection(mut controller: WifiController<'static>) { } #[embassy_executor::task] -async fn net_task(runner: &'static mut Runner<'static, WifiDevice<'static, WifiStaDevice>>) { +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 2000cda..9e46f5c 100644 --- a/examples/async_server_mTLS.rs +++ b/examples/async_server_mTLS.rs @@ -119,8 +119,6 @@ async fn main(spawner: Spawner) -> ! { seed, ); - let runner = mk_static!(Runner<'_, WifiDevice<'static, WifiStaDevice>>, runner); - spawner.spawn(connection(controller)).ok(); spawner.spawn(net_task(runner)).ok(); @@ -295,6 +293,6 @@ async fn connection(mut controller: WifiController<'static>) { } #[embassy_executor::task] -async fn net_task(runner: &'static mut Runner<'static, WifiDevice<'static, WifiStaDevice>>) { +async fn net_task(mut runner: Runner<'static, WifiDevice<'static, WifiStaDevice>>) { runner.run().await } diff --git a/examples/edge_server.rs b/examples/edge_server.rs index bb988bf..f1f709f 100644 --- a/examples/edge_server.rs +++ b/examples/edge_server.rs @@ -129,8 +129,6 @@ async fn main(spawner: Spawner) -> ! { seed, ); - let runner = mk_static!(Runner<'_, WifiDevice<'static, WifiStaDevice>>, runner); - spawner.spawn(connection(controller)).ok(); spawner.spawn(net_task(runner)).ok(); @@ -280,6 +278,6 @@ async fn connection(mut controller: WifiController<'static>) { } #[embassy_executor::task] -async fn net_task(runner: &'static mut Runner<'static, WifiDevice<'static, WifiStaDevice>>) { +async fn net_task(mut runner: Runner<'static, WifiDevice<'static, WifiStaDevice>>) { runner.run().await } From 6638783c5958686ac8414b0c4dbb8753a30ec8da Mon Sep 17 00:00:00 2001 From: ivmarkov Date: Wed, 8 Jan 2025 21:33:38 +0000 Subject: [PATCH 12/13] Address a small typo --- esp-mbedtls/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/esp-mbedtls/src/lib.rs b/esp-mbedtls/src/lib.rs index 9521efd..4198db3 100644 --- a/esp-mbedtls/src/lib.rs +++ b/esp-mbedtls/src/lib.rs @@ -1181,7 +1181,7 @@ pub mod asynch { // 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 function) + // _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?; From d6e5041ad585a930485b0352a38793255b2cf6d6 Mon Sep 17 00:00:00 2001 From: ivmarkov Date: Thu, 9 Jan 2025 07:05:14 +0000 Subject: [PATCH 13/13] Fix sha calc for sha-384 and sha-224; restore regular logging lvl for the async_client_mTLS example --- esp-mbedtls/src/esp_hal/sha/sha256.rs | 3 ++- esp-mbedtls/src/esp_hal/sha/sha512.rs | 3 ++- examples/async_client_mTLS.rs | 4 ++-- 3 files changed, 6 insertions(+), 4 deletions(-) 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/examples/async_client_mTLS.rs b/examples/async_client_mTLS.rs index f833487..fc6e9ca 100644 --- a/examples/async_client_mTLS.rs +++ b/examples/async_client_mTLS.rs @@ -50,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(); @@ -150,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,