-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathembassy_dhcp.rs
188 lines (162 loc) · 5.77 KB
/
embassy_dhcp.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#![no_std]
#![no_main]
#![feature(type_alias_impl_trait)]
use embassy_executor::_export::StaticCell;
use embassy_net::tcp::TcpSocket;
use embassy_net::{Config, Ipv4Address, Stack, StackResources};
use examples_util::hal;
use embassy_executor::Executor;
use embassy_time::{Duration, Timer};
use embedded_svc::wifi::{ClientConfiguration, Configuration, Wifi};
use esp_backtrace as _;
use esp_println::logger::init_logger;
use esp_println::println;
use esp_wifi::wifi::{WifiController, WifiDevice, WifiEvent, WifiMode, WifiState};
use esp_wifi::{initialize, EspWifiInitFor};
use hal::clock::{ClockControl, CpuClock};
use hal::Rng;
use hal::{embassy, peripherals::Peripherals, prelude::*, timer::TimerGroup, Rtc};
#[cfg(any(feature = "esp32c3", feature = "esp32c2", feature = "esp32c6"))]
use hal::system::SystemExt;
const SSID: &str = env!("SSID");
const PASSWORD: &str = env!("PASSWORD");
macro_rules! singleton {
($val:expr) => {{
type T = impl Sized;
static STATIC_CELL: StaticCell<T> = StaticCell::new();
let (x,) = STATIC_CELL.init(($val,));
x
}};
}
static EXECUTOR: StaticCell<Executor> = StaticCell::new();
#[entry]
fn main() -> ! {
init_logger(log::LevelFilter::Info);
let peripherals = Peripherals::take();
let system = examples_util::system!(peripherals);
let mut peripheral_clock_control = system.peripheral_clock_control;
let clocks = examples_util::clocks!(system);
examples_util::rtc!(peripherals);
let timer = examples_util::timer!(peripherals, clocks, peripheral_clock_control);
let init = initialize(
EspWifiInitFor::Wifi,
timer,
Rng::new(peripherals.RNG),
system.radio_clock_control,
&clocks,
)
.unwrap();
let wifi = examples_util::get_wifi!(peripherals);
let (wifi_interface, controller) = esp_wifi::wifi::new_with_mode(&init, wifi, WifiMode::Sta);
let timer_group0 = TimerGroup::new(peripherals.TIMG0, &clocks, &mut peripheral_clock_control);
embassy::init(&clocks, timer_group0.timer0);
let config = Config::dhcpv4(Default::default());
let seed = 1234; // very random, very secure seed
// Init network stack
let stack = &*singleton!(Stack::new(
wifi_interface,
config,
singleton!(StackResources::<3>::new()),
seed
));
let executor = EXECUTOR.init(Executor::new());
executor.run(|spawner| {
spawner.spawn(connection(controller)).ok();
spawner.spawn(net_task(&stack)).ok();
spawner.spawn(task(&stack)).ok();
})
}
#[embassy_executor::task]
async fn connection(mut controller: WifiController<'static>) {
println!("start connection task");
println!("Device capabilities: {:?}", controller.get_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!(controller.is_started(), Ok(true)) {
let client_config = Configuration::Client(ClientConfiguration {
ssid: SSID.into(),
password: PASSWORD.into(),
..Default::default()
});
controller.set_configuration(&client_config).unwrap();
println!("Starting wifi");
controller.start().await.unwrap();
println!("Wifi started!");
}
println!("About to connect...");
match controller.connect().await {
Ok(_) => println!("Wifi connected!"),
Err(e) => {
println!("Failed to connect to wifi: {e:?}");
Timer::after(Duration::from_millis(5000)).await
}
}
}
}
#[embassy_executor::task]
async fn net_task(stack: &'static Stack<WifiDevice<'static>>) {
stack.run().await
}
#[embassy_executor::task]
async fn task(stack: &'static Stack<WifiDevice<'static>>) {
let mut rx_buffer = [0; 4096];
let mut tx_buffer = [0; 4096];
loop {
if stack.is_link_up() {
break;
}
Timer::after(Duration::from_millis(500)).await;
}
println!("Waiting to get IP address...");
loop {
if let Some(config) = stack.config_v4() {
println!("Got IP: {}", config.address);
break;
}
Timer::after(Duration::from_millis(500)).await;
}
loop {
Timer::after(Duration::from_millis(1_000)).await;
let mut socket = TcpSocket::new(&stack, &mut rx_buffer, &mut tx_buffer);
socket.set_timeout(Some(embassy_time::Duration::from_secs(10)));
let remote_endpoint = (Ipv4Address::new(142, 250, 185, 115), 80);
println!("connecting...");
let r = socket.connect(remote_endpoint).await;
if let Err(e) = r {
println!("connect error: {:?}", e);
continue;
}
println!("connected!");
let mut buf = [0; 1024];
loop {
use embedded_io::asynch::Write;
let r = socket
.write_all(b"GET / HTTP/1.0\r\nHost: www.mobile-j.de\r\n\r\n")
.await;
if let Err(e) = r {
println!("write error: {:?}", e);
break;
}
let n = match socket.read(&mut buf).await {
Ok(0) => {
println!("read EOF");
break;
}
Ok(n) => n,
Err(e) => {
println!("read error: {:?}", e);
break;
}
};
println!("{}", core::str::from_utf8(&buf[..n]).unwrap());
}
Timer::after(Duration::from_millis(3000)).await;
}
}