2020-03-31 07:16:58 +08:00
|
|
|
use core::{
|
|
|
|
cell::RefCell,
|
|
|
|
task::Waker,
|
|
|
|
};
|
2020-04-01 04:34:32 +08:00
|
|
|
use alloc::vec::Vec;
|
2020-03-31 07:16:58 +08:00
|
|
|
use smoltcp::{
|
|
|
|
iface::EthernetInterface,
|
|
|
|
phy::Device,
|
2020-04-01 04:34:32 +08:00
|
|
|
socket::SocketSet,
|
2020-03-31 07:16:58 +08:00
|
|
|
time::Instant,
|
|
|
|
};
|
|
|
|
use crate::task;
|
|
|
|
|
|
|
|
mod tcp_stream;
|
|
|
|
pub use tcp_stream::TcpStream;
|
|
|
|
|
|
|
|
static mut SOCKETS: Option<Sockets> = None;
|
|
|
|
|
|
|
|
pub struct Sockets {
|
|
|
|
sockets: RefCell<SocketSet<'static, 'static, 'static>>,
|
|
|
|
wakers: RefCell<Vec<Waker>>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Sockets {
|
|
|
|
pub fn init(max_sockets: usize) {
|
|
|
|
let mut sockets_storage = Vec::with_capacity(max_sockets);
|
|
|
|
for _ in 0..max_sockets {
|
|
|
|
sockets_storage.push(None);
|
|
|
|
}
|
|
|
|
let sockets = RefCell::new(SocketSet::new(sockets_storage));
|
|
|
|
|
|
|
|
let wakers = RefCell::new(Vec::new());
|
|
|
|
|
|
|
|
let instance = Sockets {
|
|
|
|
sockets,
|
|
|
|
wakers,
|
|
|
|
};
|
2020-04-03 06:18:04 +08:00
|
|
|
// println!("sockets initialized");
|
2020-03-31 07:16:58 +08:00
|
|
|
unsafe { SOCKETS = Some(instance); }
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Block and run executor indefinitely while polling the smoltcp
|
|
|
|
/// iface
|
2020-04-03 06:18:04 +08:00
|
|
|
pub fn run<'b, 'c, 'e, D: for<'d> Device<'d>>(
|
|
|
|
iface: &mut EthernetInterface<'b, 'c, 'e, D>,
|
|
|
|
mut get_time: impl FnMut() -> Instant,
|
|
|
|
) {
|
2020-03-31 07:16:58 +08:00
|
|
|
task::block_on(async {
|
|
|
|
loop {
|
2020-04-03 06:18:04 +08:00
|
|
|
let instant = get_time();
|
|
|
|
Self::instance().poll(iface, instant);
|
2020-03-31 07:16:58 +08:00
|
|
|
task::r#yield().await;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
pub(crate) fn instance() -> &'static Self {
|
|
|
|
unsafe { SOCKETS.as_ref().expect("Sockets") }
|
|
|
|
}
|
|
|
|
|
2020-04-03 06:18:04 +08:00
|
|
|
fn poll<'b, 'c, 'e, D: for<'d> Device<'d>>(
|
|
|
|
&self,
|
|
|
|
iface: &mut EthernetInterface<'b, 'c, 'e, D>,
|
|
|
|
instant: Instant
|
|
|
|
) {
|
2020-03-31 07:16:58 +08:00
|
|
|
let processed = {
|
|
|
|
let mut sockets = self.sockets.borrow_mut();
|
2020-04-01 04:34:32 +08:00
|
|
|
match iface.poll(&mut sockets, instant) {
|
2020-03-31 07:16:58 +08:00
|
|
|
Ok(processed) => processed,
|
|
|
|
Err(_) => true,
|
|
|
|
}
|
|
|
|
};
|
|
|
|
if processed {
|
|
|
|
let mut wakers = self.wakers.borrow_mut();
|
|
|
|
for waker in wakers.drain(..) {
|
|
|
|
waker.wake();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// TODO: this was called through eg. TcpStream, another poll()
|
|
|
|
/// might want to send packets before sleeping for an interrupt.
|
|
|
|
pub(crate) fn register_waker(waker: Waker) {
|
|
|
|
Self::instance().wakers.borrow_mut()
|
|
|
|
.push(waker);
|
|
|
|
}
|
|
|
|
}
|