//! # HTTP Client
use core::str;
use bsc::wifi::wifi;
use embedded_svc::{
http::{
client::{Client, Request, RequestWrite, Response},
Headers, Status,
},
io,
};
use esp32_c3_dkc02_bsc as bsc;
use esp_idf_svc::http::client::{EspHttpClient, EspHttpClientConfiguration};
use esp_idf_sys as _; // If using the `binstart` feature of `esp-idf-sys`, always keep this module imported
#[toml_cfg::toml_config]
pub struct Config {
#[default("Wokwi-GUEST")]
wifi_ssid: &'static str,
#[default("")]
wifi_psk: &'static str,
}
fn main() -> anyhow::Result<()> {
esp_idf_sys::link_patches();
println!("SSID:{} PASS:{}", CONFIG.wifi_ssid, CONFIG.wifi_psk);
let _wifi = wifi(CONFIG.wifi_ssid, CONFIG.wifi_psk)?;
// TODO your code here
println!("Fetching");
let content = get("https://v2.jokeapi.dev/joke/Programming".to_string())?;
println!("Response {:?}", content);
Ok(())
}
fn get(url: String) -> anyhow::Result<String> {
// 1. Create a new EspHttpClient. (Check documentation)
// 2. Open a GET request to `url`
// 3. Requests *may* send data to the server. Turn the request into a writer, specifying 0 bytes as write length
// (since we don't send anything - but have to do the writer step anyway)
//
// https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/protocols/esp_http_client.html
// If this were a POST request, you'd set a write length > 0 and then writer.do_write(&some_buf);
// let writer = request...;
// 4. Turn the writer into a response and check its status. Successful http status codes are in the 200..=299 range.
// let response = writer...;
// let status = ...;
// println!("response code: {}\n", status);
// 5. If the status is OK, read response data chunk by chunk into a buffer and print it until done.
// 6. Try converting the bytes into a Rust (UTF-8) string and print it.
let mut client = EspHttpClient::new(&EspHttpClientConfiguration {
crt_bundle_attach: Some(esp_idf_sys::esp_crt_bundle_attach),
..Default::default()
})?;
let mut response = client.get(&url)?.submit()?;
let mut body = [0_u8; 3048];
let (body, _) = io::read_max(response.reader(), &mut body)?;
Ok(String::from_utf8_lossy(body).into_owned())
}Loading
esp32-c3-rust-1
esp32-c3-rust-1