From b05217b3566e17cd10eb52c714aa53fc6d52dd91 Mon Sep 17 00:00:00 2001 From: rafael Date: Sun, 23 Jun 2024 23:04:47 +0200 Subject: [PATCH 1/6] add wifi_webrequest example --- examples/rp/Cargo.toml | 9 +- examples/rp/src/bin/wifi_webrequest.rs | 197 +++++++++++++++++++++++++ 2 files changed, 204 insertions(+), 2 deletions(-) create mode 100644 examples/rp/src/bin/wifi_webrequest.rs diff --git a/examples/rp/Cargo.toml b/examples/rp/Cargo.toml index bb91969bc..041506a50 100644 --- a/examples/rp/Cargo.toml +++ b/examples/rp/Cargo.toml @@ -8,11 +8,11 @@ license = "MIT OR Apache-2.0" [dependencies] embassy-embedded-hal = { version = "0.1.0", path = "../../embassy-embedded-hal", features = ["defmt"] } embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } -embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } +embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["task-arena-size-98304", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } embassy-time = { version = "0.3.1", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] } embassy-rp = { version = "0.1.0", path = "../../embassy-rp", features = ["defmt", "unstable-pac", "time-driver", "critical-section-impl"] } embassy-usb = { version = "0.2.0", path = "../../embassy-usb", features = ["defmt"] } -embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "tcp", "udp", "raw", "dhcpv4", "medium-ethernet"] } +embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "tcp", "udp", "raw", "dhcpv4", "medium-ethernet", "dns"] } embassy-net-wiznet = { version = "0.1.0", path = "../../embassy-net-wiznet", features = ["defmt"] } embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } embassy-usb-logger = { version = "0.2.0", path = "../../embassy-usb-logger" } @@ -24,6 +24,11 @@ defmt-rtt = "0.4" fixed = "1.23.1" fixed-macro = "1.2" +# for web request example +reqwless = { version = "0.12.0", features = ["defmt"] } +serde = { version = "1.0.203", default-features = false, features = ["derive"] } +serde-json-core = "0.5.1" + #cortex-m = { version = "0.7.6", features = ["critical-section-single-core"] } cortex-m = { version = "0.7.6", features = ["inline-asm"] } cortex-m-rt = "0.7.0" diff --git a/examples/rp/src/bin/wifi_webrequest.rs b/examples/rp/src/bin/wifi_webrequest.rs new file mode 100644 index 000000000..350e11bf1 --- /dev/null +++ b/examples/rp/src/bin/wifi_webrequest.rs @@ -0,0 +1,197 @@ +//! This example uses the RP Pico W board Wifi chip (cyw43). +//! Connects to Wifi network and makes a web request to get the current time. + +#![no_std] +#![no_main] +#![allow(async_fn_in_trait)] + +use core::str::from_utf8; + +use serde::Deserialize; +use serde_json_core; + +use cyw43_pio::PioSpi; +use defmt::*; +use embassy_executor::Spawner; +use embassy_net::{Config, Stack, StackResources}; +use embassy_net::tcp::client::{TcpClientState, TcpClient}; +use embassy_net::dns::DnsSocket; +use embassy_rp::bind_interrupts; +use embassy_rp::gpio::{Level, Output}; +use embassy_rp::peripherals::{DMA_CH0, PIO0}; +use embassy_rp::pio::{InterruptHandler, Pio}; +use embassy_time::{Duration, Timer}; +use static_cell::StaticCell; +use reqwless::client::{HttpClient, TlsConfig, TlsVerify}; +use reqwless::request::Method; +use {defmt_rtt as _, panic_probe as _}; + +bind_interrupts!(struct Irqs { + PIO0_IRQ_0 => InterruptHandler; +}); + +const WIFI_NETWORK: &str = "ssid"; // change to your network SSID +const WIFI_PASSWORD: &str = "pwd"; // change to your network password + +#[embassy_executor::task] +async fn wifi_task(runner: cyw43::Runner<'static, Output<'static>, PioSpi<'static, PIO0, 0, DMA_CH0>>) -> ! { + runner.run().await +} + +#[embassy_executor::task] +async fn net_task(stack: &'static Stack>) -> ! { + stack.run().await +} + +#[embassy_executor::main] +async fn main(spawner: Spawner) { + info!("Hello World!"); + + let p = embassy_rp::init(Default::default()); + + let fw = include_bytes!("../../../../cyw43-firmware/43439A0.bin"); + let clm = include_bytes!("../../../../cyw43-firmware/43439A0_clm.bin"); + // To make flashing faster for development, you may want to flash the firmwares independently + // at hardcoded addresses, instead of baking them into the program with `include_bytes!`: + // probe-rs download 43439A0.bin --binary-format bin --chip RP2040 --base-address 0x10100000 + // probe-rs download 43439A0_clm.bin --binary-format bin --chip RP2040 --base-address 0x10140000 + // let fw = unsafe { core::slice::from_raw_parts(0x10100000 as *const u8, 230321) }; + // let clm = unsafe { core::slice::from_raw_parts(0x10140000 as *const u8, 4752) }; + + let pwr = Output::new(p.PIN_23, Level::Low); + let cs = Output::new(p.PIN_25, Level::High); + let mut pio = Pio::new(p.PIO0, Irqs); + let spi = PioSpi::new(&mut pio.common, pio.sm0, pio.irq0, cs, p.PIN_24, p.PIN_29, p.DMA_CH0); + + static STATE: StaticCell = StaticCell::new(); + let state = STATE.init(cyw43::State::new()); + let (net_device, mut control, runner) = cyw43::new(state, pwr, spi, fw).await; + unwrap!(spawner.spawn(wifi_task(runner))); + + control.init(clm).await; + control + .set_power_management(cyw43::PowerManagementMode::PowerSave) + .await; + + let config = Config::dhcpv4(Default::default()); + //let config = embassy_net::Config::ipv4_static(embassy_net::StaticConfigV4 { + // address: Ipv4Cidr::new(Ipv4Address::new(192, 168, 69, 2), 24), + // dns_servers: Vec::new(), + // gateway: Some(Ipv4Address::new(192, 168, 69, 1)), + //}); + + // Generate random seed + let seed = 0x0123_4567_89ab_cdef; // chosen by fair dice roll. guarenteed to be random. + + // Init network stack + static STACK: StaticCell>> = StaticCell::new(); + static RESOURCES: StaticCell> = StaticCell::new(); + let stack = &*STACK.init(Stack::new( + net_device, + config, + RESOURCES.init(StackResources::<5>::new()), + seed, + )); + + unwrap!(spawner.spawn(net_task(stack))); + + loop { + //control.join_open(WIFI_NETWORK).await; + match control.join_wpa2(WIFI_NETWORK, WIFI_PASSWORD).await { + Ok(_) => break, + Err(err) => { + info!("join failed with status={}", err.status); + } + } + } + + // Wait for DHCP, not necessary when using static IP + info!("waiting for DHCP..."); + while !stack.is_config_up() { + Timer::after_millis(100).await; + } + info!("DHCP is now up!"); + + info!("waiting for link up..."); + while !stack.is_link_up() { + Timer::after_millis(500).await; + } + info!("Link is up!"); + + info!("waiting for stack to be up..."); + stack.wait_config_up().await; + info!("Stack is up!"); + + // And now we can use it! + + + loop { + + let mut rx_buffer = [0; 8192]; + let mut tls_read_buffer = [0; 16640]; + let mut tls_write_buffer = [0; 16640]; + + let client_state = TcpClientState::<1, 1024, 1024>::new(); + let tcp_client = TcpClient::new(stack, &client_state); + let dns_client = DnsSocket::new(stack); + let tls_config = TlsConfig::new( + seed, + &mut tls_read_buffer, + &mut tls_write_buffer, + TlsVerify::None, + ); + + let mut http_client = HttpClient::new_with_tls(&tcp_client, &dns_client, tls_config); + let url = "https://worldtimeapi.org/api/timezone/Europe/Berlin"; + // let mut http_client = HttpClient::new(&tcp_client, &dns_client); // for non-TLS requests + // let url = "http://worldtimeapi.org/api/timezone/Europe/Berlin"; + + info!("connecting to {}", &url); + + let mut request = match http_client.request(Method::GET, &url).await { + Ok(req) => req, + Err(e) => { + error!("Failed to make HTTP request: {:?}", e); + return; // handle the error + } + }; + + let response = match request.send(&mut rx_buffer).await { + Ok(resp) => resp, + Err(_e) => { + error!("Failed to send HTTP request"); + return // handle the error; + } + }; + + let body = match from_utf8(response.body().read_to_end().await.unwrap()) { + Ok(b) => b, + Err(_e) => { + error!("Failed to read response body"); + return // handle the error + } + }; + info!("Response body: {:?}", &body); + + // parse the response body and update the RTC + + #[derive(Deserialize)] + struct ApiResponse<'a> { + datetime: &'a str, + // other fields as needed + } + + let bytes = body.as_bytes(); + match serde_json_core::de::from_slice::(bytes) { + Ok((output, _used)) => { + info!("Datetime: {:?}", output.datetime); + } + Err(_e) => { + error!("Failed to parse response body"); + return; // handle the error + } + } + + Timer::after(Duration::from_secs(5)).await; + } +} From 32e9867b4e23042fcbc4ec252c60b0af55cc59d7 Mon Sep 17 00:00:00 2001 From: rafael Date: Mon, 24 Jun 2024 20:51:31 +0200 Subject: [PATCH 2/6] need to bring down binary size or flashing will corrupt the device --- examples/rp/Cargo.toml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/examples/rp/Cargo.toml b/examples/rp/Cargo.toml index 041506a50..0610be0a0 100644 --- a/examples/rp/Cargo.toml +++ b/examples/rp/Cargo.toml @@ -25,7 +25,7 @@ fixed = "1.23.1" fixed-macro = "1.2" # for web request example -reqwless = { version = "0.12.0", features = ["defmt"] } +reqwless = { git = "https://github.com/drogue-iot/reqwless", features = ["defmt",]} serde = { version = "1.0.203", default-features = false, features = ["derive"] } serde-json-core = "0.5.1" @@ -58,3 +58,7 @@ embedded-sdmmc = "0.7.0" [profile.release] debug = 2 + +[profile.dev] +lto = true +opt-level = "z" From 67e7532b4aa61fef52762861084a1a05944db4ea Mon Sep 17 00:00:00 2001 From: rafael Date: Mon, 24 Jun 2024 21:16:56 +0200 Subject: [PATCH 3/6] rustfmt --- examples/rp/src/bin/wifi_webrequest.rs | 25 +++++++++---------------- 1 file changed, 9 insertions(+), 16 deletions(-) diff --git a/examples/rp/src/bin/wifi_webrequest.rs b/examples/rp/src/bin/wifi_webrequest.rs index 350e11bf1..ae3b1e26c 100644 --- a/examples/rp/src/bin/wifi_webrequest.rs +++ b/examples/rp/src/bin/wifi_webrequest.rs @@ -13,17 +13,17 @@ use serde_json_core; use cyw43_pio::PioSpi; use defmt::*; use embassy_executor::Spawner; -use embassy_net::{Config, Stack, StackResources}; -use embassy_net::tcp::client::{TcpClientState, TcpClient}; use embassy_net::dns::DnsSocket; +use embassy_net::tcp::client::{TcpClient, TcpClientState}; +use embassy_net::{Config, Stack, StackResources}; use embassy_rp::bind_interrupts; use embassy_rp::gpio::{Level, Output}; use embassy_rp::peripherals::{DMA_CH0, PIO0}; use embassy_rp::pio::{InterruptHandler, Pio}; use embassy_time::{Duration, Timer}; -use static_cell::StaticCell; use reqwless::client::{HttpClient, TlsConfig, TlsVerify}; use reqwless::request::Method; +use static_cell::StaticCell; use {defmt_rtt as _, panic_probe as _}; bind_interrupts!(struct Irqs { @@ -124,9 +124,7 @@ async fn main(spawner: Spawner) { // And now we can use it! - loop { - let mut rx_buffer = [0; 8192]; let mut tls_read_buffer = [0; 16640]; let mut tls_write_buffer = [0; 16640]; @@ -134,17 +132,12 @@ async fn main(spawner: Spawner) { let client_state = TcpClientState::<1, 1024, 1024>::new(); let tcp_client = TcpClient::new(stack, &client_state); let dns_client = DnsSocket::new(stack); - let tls_config = TlsConfig::new( - seed, - &mut tls_read_buffer, - &mut tls_write_buffer, - TlsVerify::None, - ); - + let tls_config = TlsConfig::new(seed, &mut tls_read_buffer, &mut tls_write_buffer, TlsVerify::None); + let mut http_client = HttpClient::new_with_tls(&tcp_client, &dns_client, tls_config); let url = "https://worldtimeapi.org/api/timezone/Europe/Berlin"; // let mut http_client = HttpClient::new(&tcp_client, &dns_client); // for non-TLS requests - // let url = "http://worldtimeapi.org/api/timezone/Europe/Berlin"; + // let url = "http://worldtimeapi.org/api/timezone/Europe/Berlin"; info!("connecting to {}", &url); @@ -160,7 +153,7 @@ async fn main(spawner: Spawner) { Ok(resp) => resp, Err(_e) => { error!("Failed to send HTTP request"); - return // handle the error; + return; // handle the error; } }; @@ -168,13 +161,13 @@ async fn main(spawner: Spawner) { Ok(b) => b, Err(_e) => { error!("Failed to read response body"); - return // handle the error + return; // handle the error } }; info!("Response body: {:?}", &body); // parse the response body and update the RTC - + #[derive(Deserialize)] struct ApiResponse<'a> { datetime: &'a str, From d05817f89d1d5c0e663cda1710d2eaed4cc8fa53 Mon Sep 17 00:00:00 2001 From: rafael Date: Mon, 24 Jun 2024 21:33:42 +0200 Subject: [PATCH 4/6] rustfmt again --- examples/rp/src/bin/wifi_webrequest.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/examples/rp/src/bin/wifi_webrequest.rs b/examples/rp/src/bin/wifi_webrequest.rs index ae3b1e26c..65b1af055 100644 --- a/examples/rp/src/bin/wifi_webrequest.rs +++ b/examples/rp/src/bin/wifi_webrequest.rs @@ -7,9 +7,6 @@ use core::str::from_utf8; -use serde::Deserialize; -use serde_json_core; - use cyw43_pio::PioSpi; use defmt::*; use embassy_executor::Spawner; @@ -23,8 +20,9 @@ use embassy_rp::pio::{InterruptHandler, Pio}; use embassy_time::{Duration, Timer}; use reqwless::client::{HttpClient, TlsConfig, TlsVerify}; use reqwless::request::Method; +use serde::Deserialize; use static_cell::StaticCell; -use {defmt_rtt as _, panic_probe as _}; +use {defmt_rtt as _, panic_probe as _, serde_json_core}; bind_interrupts!(struct Irqs { PIO0_IRQ_0 => InterruptHandler; From 6dae3c02c02ae25cd2fdb46673948a1c90b14944 Mon Sep 17 00:00:00 2001 From: rafael Date: Mon, 24 Jun 2024 22:08:59 +0200 Subject: [PATCH 5/6] comment the comments --- examples/rp/src/bin/wifi_webrequest.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/examples/rp/src/bin/wifi_webrequest.rs b/examples/rp/src/bin/wifi_webrequest.rs index 65b1af055..50136da32 100644 --- a/examples/rp/src/bin/wifi_webrequest.rs +++ b/examples/rp/src/bin/wifi_webrequest.rs @@ -72,6 +72,7 @@ async fn main(spawner: Spawner) { .await; let config = Config::dhcpv4(Default::default()); + // Use static IP configuration instead of DHCP //let config = embassy_net::Config::ipv4_static(embassy_net::StaticConfigV4 { // address: Ipv4Cidr::new(Ipv4Address::new(192, 168, 69, 2), 24), // dns_servers: Vec::new(), @@ -94,7 +95,7 @@ async fn main(spawner: Spawner) { unwrap!(spawner.spawn(net_task(stack))); loop { - //control.join_open(WIFI_NETWORK).await; + //match control.join_open(WIFI_NETWORK).await { // for open networks match control.join_wpa2(WIFI_NETWORK, WIFI_PASSWORD).await { Ok(_) => break, Err(err) => { @@ -134,7 +135,8 @@ async fn main(spawner: Spawner) { let mut http_client = HttpClient::new_with_tls(&tcp_client, &dns_client, tls_config); let url = "https://worldtimeapi.org/api/timezone/Europe/Berlin"; - // let mut http_client = HttpClient::new(&tcp_client, &dns_client); // for non-TLS requests + // for non-TLS requests, use this instead: + // let mut http_client = HttpClient::new(&tcp_client, &dns_client); // let url = "http://worldtimeapi.org/api/timezone/Europe/Berlin"; info!("connecting to {}", &url); From b927c22ac0af570674315da9a8b77d3e7a7e10ea Mon Sep 17 00:00:00 2001 From: rafael Date: Mon, 24 Jun 2024 22:12:18 +0200 Subject: [PATCH 6/6] rustfmt --- examples/rp/src/bin/wifi_webrequest.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/rp/src/bin/wifi_webrequest.rs b/examples/rp/src/bin/wifi_webrequest.rs index 50136da32..e0c91df53 100644 --- a/examples/rp/src/bin/wifi_webrequest.rs +++ b/examples/rp/src/bin/wifi_webrequest.rs @@ -95,7 +95,7 @@ async fn main(spawner: Spawner) { unwrap!(spawner.spawn(net_task(stack))); loop { - //match control.join_open(WIFI_NETWORK).await { // for open networks + //match control.join_open(WIFI_NETWORK).await { // for open networks match control.join_wpa2(WIFI_NETWORK, WIFI_PASSWORD).await { Ok(_) => break, Err(err) => { @@ -136,7 +136,7 @@ async fn main(spawner: Spawner) { let mut http_client = HttpClient::new_with_tls(&tcp_client, &dns_client, tls_config); let url = "https://worldtimeapi.org/api/timezone/Europe/Berlin"; // for non-TLS requests, use this instead: - // let mut http_client = HttpClient::new(&tcp_client, &dns_client); + // let mut http_client = HttpClient::new(&tcp_client, &dns_client); // let url = "http://worldtimeapi.org/api/timezone/Europe/Berlin"; info!("connecting to {}", &url);