aboutsummaryrefslogtreecommitdiff
path: root/examples/rp
diff options
context:
space:
mode:
authorrafael <rafael>2024-06-23 23:04:47 +0200
committerrafael <rafael>2024-06-23 23:04:47 +0200
commitb05217b3566e17cd10eb52c714aa53fc6d52dd91 (patch)
tree4fafe3ec251df74b39c934b171ba78a7545c7746 /examples/rp
parentcfe8561550e10d145eb6ef14423a49f78d7ac38e (diff)
add wifi_webrequest example
Diffstat (limited to 'examples/rp')
-rw-r--r--examples/rp/Cargo.toml9
-rw-r--r--examples/rp/src/bin/wifi_webrequest.rs197
2 files changed, 204 insertions, 2 deletions
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"
8[dependencies] 8[dependencies]
9embassy-embedded-hal = { version = "0.1.0", path = "../../embassy-embedded-hal", features = ["defmt"] } 9embassy-embedded-hal = { version = "0.1.0", path = "../../embassy-embedded-hal", features = ["defmt"] }
10embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] } 10embassy-sync = { version = "0.6.0", path = "../../embassy-sync", features = ["defmt"] }
11embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["task-arena-size-32768", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] } 11embassy-executor = { version = "0.5.0", path = "../../embassy-executor", features = ["task-arena-size-98304", "arch-cortex-m", "executor-thread", "executor-interrupt", "defmt", "integrated-timers"] }
12embassy-time = { version = "0.3.1", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] } 12embassy-time = { version = "0.3.1", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] }
13embassy-rp = { version = "0.1.0", path = "../../embassy-rp", features = ["defmt", "unstable-pac", "time-driver", "critical-section-impl"] } 13embassy-rp = { version = "0.1.0", path = "../../embassy-rp", features = ["defmt", "unstable-pac", "time-driver", "critical-section-impl"] }
14embassy-usb = { version = "0.2.0", path = "../../embassy-usb", features = ["defmt"] } 14embassy-usb = { version = "0.2.0", path = "../../embassy-usb", features = ["defmt"] }
15embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "tcp", "udp", "raw", "dhcpv4", "medium-ethernet"] } 15embassy-net = { version = "0.4.0", path = "../../embassy-net", features = ["defmt", "tcp", "udp", "raw", "dhcpv4", "medium-ethernet", "dns"] }
16embassy-net-wiznet = { version = "0.1.0", path = "../../embassy-net-wiznet", features = ["defmt"] } 16embassy-net-wiznet = { version = "0.1.0", path = "../../embassy-net-wiznet", features = ["defmt"] }
17embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } 17embassy-futures = { version = "0.1.0", path = "../../embassy-futures" }
18embassy-usb-logger = { version = "0.2.0", path = "../../embassy-usb-logger" } 18embassy-usb-logger = { version = "0.2.0", path = "../../embassy-usb-logger" }
@@ -24,6 +24,11 @@ defmt-rtt = "0.4"
24fixed = "1.23.1" 24fixed = "1.23.1"
25fixed-macro = "1.2" 25fixed-macro = "1.2"
26 26
27# for web request example
28reqwless = { version = "0.12.0", features = ["defmt"] }
29serde = { version = "1.0.203", default-features = false, features = ["derive"] }
30serde-json-core = "0.5.1"
31
27#cortex-m = { version = "0.7.6", features = ["critical-section-single-core"] } 32#cortex-m = { version = "0.7.6", features = ["critical-section-single-core"] }
28cortex-m = { version = "0.7.6", features = ["inline-asm"] } 33cortex-m = { version = "0.7.6", features = ["inline-asm"] }
29cortex-m-rt = "0.7.0" 34cortex-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 @@
1//! This example uses the RP Pico W board Wifi chip (cyw43).
2//! Connects to Wifi network and makes a web request to get the current time.
3
4#![no_std]
5#![no_main]
6#![allow(async_fn_in_trait)]
7
8use core::str::from_utf8;
9
10use serde::Deserialize;
11use serde_json_core;
12
13use cyw43_pio::PioSpi;
14use defmt::*;
15use embassy_executor::Spawner;
16use embassy_net::{Config, Stack, StackResources};
17use embassy_net::tcp::client::{TcpClientState, TcpClient};
18use embassy_net::dns::DnsSocket;
19use embassy_rp::bind_interrupts;
20use embassy_rp::gpio::{Level, Output};
21use embassy_rp::peripherals::{DMA_CH0, PIO0};
22use embassy_rp::pio::{InterruptHandler, Pio};
23use embassy_time::{Duration, Timer};
24use static_cell::StaticCell;
25use reqwless::client::{HttpClient, TlsConfig, TlsVerify};
26use reqwless::request::Method;
27use {defmt_rtt as _, panic_probe as _};
28
29bind_interrupts!(struct Irqs {
30 PIO0_IRQ_0 => InterruptHandler<PIO0>;
31});
32
33const WIFI_NETWORK: &str = "ssid"; // change to your network SSID
34const WIFI_PASSWORD: &str = "pwd"; // change to your network password
35
36#[embassy_executor::task]
37async fn wifi_task(runner: cyw43::Runner<'static, Output<'static>, PioSpi<'static, PIO0, 0, DMA_CH0>>) -> ! {
38 runner.run().await
39}
40
41#[embassy_executor::task]
42async fn net_task(stack: &'static Stack<cyw43::NetDriver<'static>>) -> ! {
43 stack.run().await
44}
45
46#[embassy_executor::main]
47async fn main(spawner: Spawner) {
48 info!("Hello World!");
49
50 let p = embassy_rp::init(Default::default());
51
52 let fw = include_bytes!("../../../../cyw43-firmware/43439A0.bin");
53 let clm = include_bytes!("../../../../cyw43-firmware/43439A0_clm.bin");
54 // To make flashing faster for development, you may want to flash the firmwares independently
55 // at hardcoded addresses, instead of baking them into the program with `include_bytes!`:
56 // probe-rs download 43439A0.bin --binary-format bin --chip RP2040 --base-address 0x10100000
57 // probe-rs download 43439A0_clm.bin --binary-format bin --chip RP2040 --base-address 0x10140000
58 // let fw = unsafe { core::slice::from_raw_parts(0x10100000 as *const u8, 230321) };
59 // let clm = unsafe { core::slice::from_raw_parts(0x10140000 as *const u8, 4752) };
60
61 let pwr = Output::new(p.PIN_23, Level::Low);
62 let cs = Output::new(p.PIN_25, Level::High);
63 let mut pio = Pio::new(p.PIO0, Irqs);
64 let spi = PioSpi::new(&mut pio.common, pio.sm0, pio.irq0, cs, p.PIN_24, p.PIN_29, p.DMA_CH0);
65
66 static STATE: StaticCell<cyw43::State> = StaticCell::new();
67 let state = STATE.init(cyw43::State::new());
68 let (net_device, mut control, runner) = cyw43::new(state, pwr, spi, fw).await;
69 unwrap!(spawner.spawn(wifi_task(runner)));
70
71 control.init(clm).await;
72 control
73 .set_power_management(cyw43::PowerManagementMode::PowerSave)
74 .await;
75
76 let config = Config::dhcpv4(Default::default());
77 //let config = embassy_net::Config::ipv4_static(embassy_net::StaticConfigV4 {
78 // address: Ipv4Cidr::new(Ipv4Address::new(192, 168, 69, 2), 24),
79 // dns_servers: Vec::new(),
80 // gateway: Some(Ipv4Address::new(192, 168, 69, 1)),
81 //});
82
83 // Generate random seed
84 let seed = 0x0123_4567_89ab_cdef; // chosen by fair dice roll. guarenteed to be random.
85
86 // Init network stack
87 static STACK: StaticCell<Stack<cyw43::NetDriver<'static>>> = StaticCell::new();
88 static RESOURCES: StaticCell<StackResources<5>> = StaticCell::new();
89 let stack = &*STACK.init(Stack::new(
90 net_device,
91 config,
92 RESOURCES.init(StackResources::<5>::new()),
93 seed,
94 ));
95
96 unwrap!(spawner.spawn(net_task(stack)));
97
98 loop {
99 //control.join_open(WIFI_NETWORK).await;
100 match control.join_wpa2(WIFI_NETWORK, WIFI_PASSWORD).await {
101 Ok(_) => break,
102 Err(err) => {
103 info!("join failed with status={}", err.status);
104 }
105 }
106 }
107
108 // Wait for DHCP, not necessary when using static IP
109 info!("waiting for DHCP...");
110 while !stack.is_config_up() {
111 Timer::after_millis(100).await;
112 }
113 info!("DHCP is now up!");
114
115 info!("waiting for link up...");
116 while !stack.is_link_up() {
117 Timer::after_millis(500).await;
118 }
119 info!("Link is up!");
120
121 info!("waiting for stack to be up...");
122 stack.wait_config_up().await;
123 info!("Stack is up!");
124
125 // And now we can use it!
126
127
128 loop {
129
130 let mut rx_buffer = [0; 8192];
131 let mut tls_read_buffer = [0; 16640];
132 let mut tls_write_buffer = [0; 16640];
133
134 let client_state = TcpClientState::<1, 1024, 1024>::new();
135 let tcp_client = TcpClient::new(stack, &client_state);
136 let dns_client = DnsSocket::new(stack);
137 let tls_config = TlsConfig::new(
138 seed,
139 &mut tls_read_buffer,
140 &mut tls_write_buffer,
141 TlsVerify::None,
142 );
143
144 let mut http_client = HttpClient::new_with_tls(&tcp_client, &dns_client, tls_config);
145 let url = "https://worldtimeapi.org/api/timezone/Europe/Berlin";
146 // let mut http_client = HttpClient::new(&tcp_client, &dns_client); // for non-TLS requests
147 // let url = "http://worldtimeapi.org/api/timezone/Europe/Berlin";
148
149 info!("connecting to {}", &url);
150
151 let mut request = match http_client.request(Method::GET, &url).await {
152 Ok(req) => req,
153 Err(e) => {
154 error!("Failed to make HTTP request: {:?}", e);
155 return; // handle the error
156 }
157 };
158
159 let response = match request.send(&mut rx_buffer).await {
160 Ok(resp) => resp,
161 Err(_e) => {
162 error!("Failed to send HTTP request");
163 return // handle the error;
164 }
165 };
166
167 let body = match from_utf8(response.body().read_to_end().await.unwrap()) {
168 Ok(b) => b,
169 Err(_e) => {
170 error!("Failed to read response body");
171 return // handle the error
172 }
173 };
174 info!("Response body: {:?}", &body);
175
176 // parse the response body and update the RTC
177
178 #[derive(Deserialize)]
179 struct ApiResponse<'a> {
180 datetime: &'a str,
181 // other fields as needed
182 }
183
184 let bytes = body.as_bytes();
185 match serde_json_core::de::from_slice::<ApiResponse>(bytes) {
186 Ok((output, _used)) => {
187 info!("Datetime: {:?}", output.datetime);
188 }
189 Err(_e) => {
190 error!("Failed to parse response body");
191 return; // handle the error
192 }
193 }
194
195 Timer::after(Duration::from_secs(5)).await;
196 }
197}