diff --git a/services/net/src/device.rs b/services/net/src/device.rs new file mode 100755 index 000000000..583dcb52f --- /dev/null +++ b/services/net/src/device.rs @@ -0,0 +1,105 @@ +use com::Com; +use com::api::NET_MTU; + +use smoltcp::Result; +use smoltcp::phy::{self, DeviceCapabilities, Device, Medium}; + +use smoltcp::iface::{InterfaceBuilder, NeighborCache, Routes}; +use smoltcp::socket::{IcmpEndpoint, IcmpPacketMetadata, IcmpSocket, IcmpSocketBuffer, SocketSet}; +use smoltcp::wire::{ + EthernetAddress, Icmpv4Packet, Icmpv4Repr, Icmpv6Packet, Icmpv6Repr, IpAddress, IpCidr, + Ipv4Address, Ipv6Address, +}; +use smoltcp::{ + time::{Duration, Instant}, +}; + +pub struct NetPhy { + rx_buffer: [u8; NET_MTU], + tx_buffer: [u8; NET_MTU], + com: Com, + rx_avail: Option, +} + +impl<'a> NetPhy { + pub fn new(xns: &xous_names::XousNames) -> NetPhy { + NetPhy { + rx_buffer: [0; NET_MTU], + tx_buffer: [0; NET_MTU], + com: Com::new(&xns).unwrap(), + rx_avail: None, + } + } + // returns None if there was a slot to put the availability into + // returns Some(len) if not + pub fn push_rx_avail(&mut self, len: u16) -> Option { + if self.rx_avail.is_none() { + self.rx_avail = Some(len); + None + } else { + Some(len) + } + } +} + +impl<'a> phy::Device<'a> for NetPhy { + type RxToken = NetPhyRxToken<'a>; + type TxToken = NetPhyTxToken<'a>; + + fn receive(&'a mut self) -> Option<(Self::RxToken, Self::TxToken)> { + Some((NetPhyRxToken{buf: &mut self.rx_buffer[..], com: & self.com, rx_avail: self.rx_avail.take()}, + NetPhyTxToken{buf: &mut self.tx_buffer[..], com: & self.com})) + } + + fn transmit(&'a mut self) -> Option { + Some(NetPhyTxToken{buf: &mut self.tx_buffer[..], com: &self.com}) + } + + fn capabilities(&self) -> DeviceCapabilities { + let mut caps = DeviceCapabilities::default(); + caps.max_transmission_unit = NET_MTU; + caps.max_burst_size = Some(1); + caps.medium = Medium::Ethernet; + caps + } +} + +pub struct NetPhyRxToken<'a> { + buf: &'a mut [u8], + com: &'a Com, + rx_avail: Option, +} + +impl<'a, 'c> phy::RxToken for NetPhyRxToken<'a> { + fn consume(mut self, _timestamp: Instant, f: F) -> Result + where F: FnOnce(&mut [u8]) -> Result + { + if let Some(rx_len) = self.rx_avail { + self.com.wlan_fetch_packet(&mut self.buf[..rx_len as usize]).unwrap(); + } + // else, the buf is not updated -- and it would be empty, yielding no availability + + let result = f(&mut self.buf); + log::info!("rx called"); + result + } +} + +pub struct NetPhyTxToken<'a> { + buf: &'a mut [u8], + com: &'a Com, +} + +impl<'a> phy::TxToken for NetPhyTxToken<'a> { + fn consume(self, _timestamp: Instant, len: usize, f: F) -> Result + where F: FnOnce(&mut [u8]) -> Result + { + let result = f(&mut self.buf[..len]); + log::info!("tx called {}", len); + + if result.is_ok() { + self.com.wlan_send_packet(self.buf).map_err(|_| smoltcp::Error::Dropped)?; + } + result + } +} \ No newline at end of file