aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJames Munns <[email protected]>2024-06-25 09:35:36 +0000
committerGitHub <[email protected]>2024-06-25 09:35:36 +0000
commitdfdbcb400c3615698aa3bc0885faac376c3ff7bd (patch)
tree7eac2c31bf4b89d661320f42b5aa24adaa6902bb
parentab3cc7226a5107111287899297f1f67ff9e1ee82 (diff)
parentb927c22ac0af570674315da9a8b77d3e7a7e10ea (diff)
Merge pull request #3115 from 1-rafael-1/add-http-request-example-to-rp
Add http request example to rp
-rw-r--r--examples/rp/Cargo.toml13
-rw-r--r--examples/rp/src/bin/wifi_webrequest.rs190
2 files changed, 201 insertions, 2 deletions
diff --git a/examples/rp/Cargo.toml b/examples/rp/Cargo.toml
index bb91969bc..0610be0a0 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 = { git = "https://github.com/drogue-iot/reqwless", 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"
@@ -53,3 +58,7 @@ embedded-sdmmc = "0.7.0"
53 58
54[profile.release] 59[profile.release]
55debug = 2 60debug = 2
61
62[profile.dev]
63lto = true
64opt-level = "z"
diff --git a/examples/rp/src/bin/wifi_webrequest.rs b/examples/rp/src/bin/wifi_webrequest.rs
new file mode 100644
index 000000000..e0c91df53
--- /dev/null
+++ b/examples/rp/src/bin/wifi_webrequest.rs
@@ -0,0 +1,190 @@
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 cyw43_pio::PioSpi;
11use defmt::*;
12use embassy_executor::Spawner;
13use embassy_net::dns::DnsSocket;
14use embassy_net::tcp::client::{TcpClient, TcpClientState};
15use embassy_net::{Config, Stack, StackResources};
16use embassy_rp::bind_interrupts;
17use embassy_rp::gpio::{Level, Output};
18use embassy_rp::peripherals::{DMA_CH0, PIO0};
19use embassy_rp::pio::{InterruptHandler, Pio};
20use embassy_time::{Duration, Timer};
21use reqwless::client::{HttpClient, TlsConfig, TlsVerify};
22use reqwless::request::Method;
23use serde::Deserialize;
24use static_cell::StaticCell;
25use {defmt_rtt as _, panic_probe as _, serde_json_core};
26
27bind_interrupts!(struct Irqs {
28 PIO0_IRQ_0 => InterruptHandler<PIO0>;
29});
30
31const WIFI_NETWORK: &str = "ssid"; // change to your network SSID
32const WIFI_PASSWORD: &str = "pwd"; // change to your network password
33
34#[embassy_executor::task]
35async fn wifi_task(runner: cyw43::Runner<'static, Output<'static>, PioSpi<'static, PIO0, 0, DMA_CH0>>) -> ! {
36 runner.run().await
37}
38
39#[embassy_executor::task]
40async fn net_task(stack: &'static Stack<cyw43::NetDriver<'static>>) -> ! {
41 stack.run().await
42}
43
44#[embassy_executor::main]
45async fn main(spawner: Spawner) {
46 info!("Hello World!");
47
48 let p = embassy_rp::init(Default::default());
49
50 let fw = include_bytes!("../../../../cyw43-firmware/43439A0.bin");
51 let clm = include_bytes!("../../../../cyw43-firmware/43439A0_clm.bin");
52 // To make flashing faster for development, you may want to flash the firmwares independently
53 // at hardcoded addresses, instead of baking them into the program with `include_bytes!`:
54 // probe-rs download 43439A0.bin --binary-format bin --chip RP2040 --base-address 0x10100000
55 // probe-rs download 43439A0_clm.bin --binary-format bin --chip RP2040 --base-address 0x10140000
56 // let fw = unsafe { core::slice::from_raw_parts(0x10100000 as *const u8, 230321) };
57 // let clm = unsafe { core::slice::from_raw_parts(0x10140000 as *const u8, 4752) };
58
59 let pwr = Output::new(p.PIN_23, Level::Low);
60 let cs = Output::new(p.PIN_25, Level::High);
61 let mut pio = Pio::new(p.PIO0, Irqs);
62 let spi = PioSpi::new(&mut pio.common, pio.sm0, pio.irq0, cs, p.PIN_24, p.PIN_29, p.DMA_CH0);
63
64 static STATE: StaticCell<cyw43::State> = StaticCell::new();
65 let state = STATE.init(cyw43::State::new());
66 let (net_device, mut control, runner) = cyw43::new(state, pwr, spi, fw).await;
67 unwrap!(spawner.spawn(wifi_task(runner)));
68
69 control.init(clm).await;
70 control
71 .set_power_management(cyw43::PowerManagementMode::PowerSave)
72 .await;
73
74 let config = Config::dhcpv4(Default::default());
75 // Use static IP configuration instead of DHCP
76 //let config = embassy_net::Config::ipv4_static(embassy_net::StaticConfigV4 {
77 // address: Ipv4Cidr::new(Ipv4Address::new(192, 168, 69, 2), 24),
78 // dns_servers: Vec::new(),
79 // gateway: Some(Ipv4Address::new(192, 168, 69, 1)),
80 //});
81
82 // Generate random seed
83 let seed = 0x0123_4567_89ab_cdef; // chosen by fair dice roll. guarenteed to be random.
84
85 // Init network stack
86 static STACK: StaticCell<Stack<cyw43::NetDriver<'static>>> = StaticCell::new();
87 static RESOURCES: StaticCell<StackResources<5>> = StaticCell::new();
88 let stack = &*STACK.init(Stack::new(
89 net_device,
90 config,
91 RESOURCES.init(StackResources::<5>::new()),
92 seed,
93 ));
94
95 unwrap!(spawner.spawn(net_task(stack)));
96
97 loop {
98 //match control.join_open(WIFI_NETWORK).await { // for open networks
99 match control.join_wpa2(WIFI_NETWORK, WIFI_PASSWORD).await {
100 Ok(_) => break,
101 Err(err) => {
102 info!("join failed with status={}", err.status);
103 }
104 }
105 }
106
107 // Wait for DHCP, not necessary when using static IP
108 info!("waiting for DHCP...");
109 while !stack.is_config_up() {
110 Timer::after_millis(100).await;
111 }
112 info!("DHCP is now up!");
113
114 info!("waiting for link up...");
115 while !stack.is_link_up() {
116 Timer::after_millis(500).await;
117 }
118 info!("Link is up!");
119
120 info!("waiting for stack to be up...");
121 stack.wait_config_up().await;
122 info!("Stack is up!");
123
124 // And now we can use it!
125
126 loop {
127 let mut rx_buffer = [0; 8192];
128 let mut tls_read_buffer = [0; 16640];
129 let mut tls_write_buffer = [0; 16640];
130
131 let client_state = TcpClientState::<1, 1024, 1024>::new();
132 let tcp_client = TcpClient::new(stack, &client_state);
133 let dns_client = DnsSocket::new(stack);
134 let tls_config = TlsConfig::new(seed, &mut tls_read_buffer, &mut tls_write_buffer, TlsVerify::None);
135
136 let mut http_client = HttpClient::new_with_tls(&tcp_client, &dns_client, tls_config);
137 let url = "https://worldtimeapi.org/api/timezone/Europe/Berlin";
138 // for non-TLS requests, use this instead:
139 // let mut http_client = HttpClient::new(&tcp_client, &dns_client);
140 // let url = "http://worldtimeapi.org/api/timezone/Europe/Berlin";
141
142 info!("connecting to {}", &url);
143
144 let mut request = match http_client.request(Method::GET, &url).await {
145 Ok(req) => req,
146 Err(e) => {
147 error!("Failed to make HTTP request: {:?}", e);
148 return; // handle the error
149 }
150 };
151
152 let response = match request.send(&mut rx_buffer).await {
153 Ok(resp) => resp,
154 Err(_e) => {
155 error!("Failed to send HTTP request");
156 return; // handle the error;
157 }
158 };
159
160 let body = match from_utf8(response.body().read_to_end().await.unwrap()) {
161 Ok(b) => b,
162 Err(_e) => {
163 error!("Failed to read response body");
164 return; // handle the error
165 }
166 };
167 info!("Response body: {:?}", &body);
168
169 // parse the response body and update the RTC
170
171 #[derive(Deserialize)]
172 struct ApiResponse<'a> {
173 datetime: &'a str,
174 // other fields as needed
175 }
176
177 let bytes = body.as_bytes();
178 match serde_json_core::de::from_slice::<ApiResponse>(bytes) {
179 Ok((output, _used)) => {
180 info!("Datetime: {:?}", output.datetime);
181 }
182 Err(_e) => {
183 error!("Failed to parse response body");
184 return; // handle the error
185 }
186 }
187
188 Timer::after(Duration::from_secs(5)).await;
189 }
190}