diff options
| -rw-r--r-- | embassy-net-driver-channel/src/lib.rs | 19 | ||||
| -rw-r--r-- | embassy-net-ppp/Cargo.toml | 28 | ||||
| -rw-r--r-- | embassy-net-ppp/README.md | 19 | ||||
| -rw-r--r-- | embassy-net-ppp/src/fmt.rs | 257 | ||||
| -rw-r--r-- | embassy-net-ppp/src/lib.rs | 180 | ||||
| -rw-r--r-- | embassy-net/Cargo.toml | 1 | ||||
| -rw-r--r-- | embassy-net/src/lib.rs | 5 | ||||
| -rw-r--r-- | examples/std/Cargo.toml | 4 | ||||
| -rw-r--r-- | examples/std/src/bin/net_ppp.rs | 218 |
9 files changed, 728 insertions, 3 deletions
diff --git a/embassy-net-driver-channel/src/lib.rs b/embassy-net-driver-channel/src/lib.rs index 076238ba0..f2aa6b254 100644 --- a/embassy-net-driver-channel/src/lib.rs +++ b/embassy-net-driver-channel/src/lib.rs | |||
| @@ -8,6 +8,7 @@ use core::cell::RefCell; | |||
| 8 | use core::mem::MaybeUninit; | 8 | use core::mem::MaybeUninit; |
| 9 | use core::task::{Context, Poll}; | 9 | use core::task::{Context, Poll}; |
| 10 | 10 | ||
| 11 | use driver::HardwareAddress; | ||
| 11 | pub use embassy_net_driver as driver; | 12 | pub use embassy_net_driver as driver; |
| 12 | use embassy_net_driver::{Capabilities, LinkState, Medium}; | 13 | use embassy_net_driver::{Capabilities, LinkState, Medium}; |
| 13 | use embassy_sync::blocking_mutex::raw::NoopRawMutex; | 14 | use embassy_sync::blocking_mutex::raw::NoopRawMutex; |
| @@ -73,6 +74,18 @@ impl<'d, const MTU: usize> Runner<'d, MTU> { | |||
| 73 | ) | 74 | ) |
| 74 | } | 75 | } |
| 75 | 76 | ||
| 77 | pub fn borrow_split(&mut self) -> (StateRunner<'_>, RxRunner<'_, MTU>, TxRunner<'_, MTU>) { | ||
| 78 | ( | ||
| 79 | StateRunner { shared: self.shared }, | ||
| 80 | RxRunner { | ||
| 81 | rx_chan: self.rx_chan.borrow(), | ||
| 82 | }, | ||
| 83 | TxRunner { | ||
| 84 | tx_chan: self.tx_chan.borrow(), | ||
| 85 | }, | ||
| 86 | ) | ||
| 87 | } | ||
| 88 | |||
| 76 | pub fn state_runner(&self) -> StateRunner<'d> { | 89 | pub fn state_runner(&self) -> StateRunner<'d> { |
| 77 | StateRunner { shared: self.shared } | 90 | StateRunner { shared: self.shared } |
| 78 | } | 91 | } |
| @@ -218,7 +231,11 @@ pub fn new<'d, const MTU: usize, const N_RX: usize, const N_TX: usize>( | |||
| 218 | ) -> (Runner<'d, MTU>, Device<'d, MTU>) { | 231 | ) -> (Runner<'d, MTU>, Device<'d, MTU>) { |
| 219 | let mut caps = Capabilities::default(); | 232 | let mut caps = Capabilities::default(); |
| 220 | caps.max_transmission_unit = MTU; | 233 | caps.max_transmission_unit = MTU; |
| 221 | caps.medium = Medium::Ethernet; | 234 | caps.medium = match &hardware_address { |
| 235 | HardwareAddress::Ethernet(_) => Medium::Ethernet, | ||
| 236 | HardwareAddress::Ieee802154(_) => Medium::Ieee802154, | ||
| 237 | HardwareAddress::Ip => Medium::Ip, | ||
| 238 | }; | ||
| 222 | 239 | ||
| 223 | // safety: this is a self-referential struct, however: | 240 | // safety: this is a self-referential struct, however: |
| 224 | // - it can't move while the `'d` borrow is active. | 241 | // - it can't move while the `'d` borrow is active. |
diff --git a/embassy-net-ppp/Cargo.toml b/embassy-net-ppp/Cargo.toml new file mode 100644 index 000000000..b2874c683 --- /dev/null +++ b/embassy-net-ppp/Cargo.toml | |||
| @@ -0,0 +1,28 @@ | |||
| 1 | [package] | ||
| 2 | name = "embassy-net-ppp" | ||
| 3 | version = "0.1.0" | ||
| 4 | description = "embassy-net driver for PPP over Serial" | ||
| 5 | keywords = ["embedded", "ppp", "embassy-net", "embedded-hal-async", "ethernet", "async"] | ||
| 6 | categories = ["embedded", "hardware-support", "no-std", "network-programming", "async"] | ||
| 7 | license = "MIT OR Apache-2.0" | ||
| 8 | edition = "2021" | ||
| 9 | |||
| 10 | [features] | ||
| 11 | defmt = ["dep:defmt", "ppproto/defmt"] | ||
| 12 | log = ["dep:log", "ppproto/log"] | ||
| 13 | |||
| 14 | [dependencies] | ||
| 15 | defmt = { version = "0.3", optional = true } | ||
| 16 | log = { version = "0.4.14", optional = true } | ||
| 17 | |||
| 18 | embedded-io-async = { version = "0.5.0" } | ||
| 19 | embassy-net-driver-channel = { version = "0.1.0", path = "../embassy-net-driver-channel" } | ||
| 20 | embassy-futures = { version = "0.1.0", path = "../embassy-futures" } | ||
| 21 | ppproto = { version = "0.1.1"} | ||
| 22 | embassy-sync = { version = "0.2.0", path = "../embassy-sync" } | ||
| 23 | |||
| 24 | [package.metadata.embassy_docs] | ||
| 25 | src_base = "https://github.com/embassy-rs/embassy/blob/embassy-net-ppp-v$VERSION/embassy-net-ppp/src/" | ||
| 26 | src_base_git = "https://github.com/embassy-rs/embassy/blob/$COMMIT/embassy-net-ppp/src/" | ||
| 27 | target = "thumbv7em-none-eabi" | ||
| 28 | features = ["defmt"] | ||
diff --git a/embassy-net-ppp/README.md b/embassy-net-ppp/README.md new file mode 100644 index 000000000..58d67395a --- /dev/null +++ b/embassy-net-ppp/README.md | |||
| @@ -0,0 +1,19 @@ | |||
| 1 | # `embassy-net-ppp` | ||
| 2 | |||
| 3 | [`embassy-net`](https://crates.io/crates/embassy-net) integration for PPP over Serial. | ||
| 4 | |||
| 5 | ## Interoperability | ||
| 6 | |||
| 7 | This crate can run on any executor. | ||
| 8 | |||
| 9 | It supports any serial port implementing [`embedded-io-async`](https://crates.io/crates/embedded-io-async). | ||
| 10 | |||
| 11 | ## License | ||
| 12 | |||
| 13 | This work is licensed under either of | ||
| 14 | |||
| 15 | - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or | ||
| 16 | http://www.apache.org/licenses/LICENSE-2.0) | ||
| 17 | - MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) | ||
| 18 | |||
| 19 | at your option. | ||
diff --git a/embassy-net-ppp/src/fmt.rs b/embassy-net-ppp/src/fmt.rs new file mode 100644 index 000000000..91984bde1 --- /dev/null +++ b/embassy-net-ppp/src/fmt.rs | |||
| @@ -0,0 +1,257 @@ | |||
| 1 | #![macro_use] | ||
| 2 | #![allow(unused_macros)] | ||
| 3 | |||
| 4 | use core::fmt::{Debug, Display, LowerHex}; | ||
| 5 | |||
| 6 | #[cfg(all(feature = "defmt", feature = "log"))] | ||
| 7 | compile_error!("You may not enable both `defmt` and `log` features."); | ||
| 8 | |||
| 9 | macro_rules! assert { | ||
| 10 | ($($x:tt)*) => { | ||
| 11 | { | ||
| 12 | #[cfg(not(feature = "defmt"))] | ||
| 13 | ::core::assert!($($x)*); | ||
| 14 | #[cfg(feature = "defmt")] | ||
| 15 | ::defmt::assert!($($x)*); | ||
| 16 | } | ||
| 17 | }; | ||
| 18 | } | ||
| 19 | |||
| 20 | macro_rules! assert_eq { | ||
| 21 | ($($x:tt)*) => { | ||
| 22 | { | ||
| 23 | #[cfg(not(feature = "defmt"))] | ||
| 24 | ::core::assert_eq!($($x)*); | ||
| 25 | #[cfg(feature = "defmt")] | ||
| 26 | ::defmt::assert_eq!($($x)*); | ||
| 27 | } | ||
| 28 | }; | ||
| 29 | } | ||
| 30 | |||
| 31 | macro_rules! assert_ne { | ||
| 32 | ($($x:tt)*) => { | ||
| 33 | { | ||
| 34 | #[cfg(not(feature = "defmt"))] | ||
| 35 | ::core::assert_ne!($($x)*); | ||
| 36 | #[cfg(feature = "defmt")] | ||
| 37 | ::defmt::assert_ne!($($x)*); | ||
| 38 | } | ||
| 39 | }; | ||
| 40 | } | ||
| 41 | |||
| 42 | macro_rules! debug_assert { | ||
| 43 | ($($x:tt)*) => { | ||
| 44 | { | ||
| 45 | #[cfg(not(feature = "defmt"))] | ||
| 46 | ::core::debug_assert!($($x)*); | ||
| 47 | #[cfg(feature = "defmt")] | ||
| 48 | ::defmt::debug_assert!($($x)*); | ||
| 49 | } | ||
| 50 | }; | ||
| 51 | } | ||
| 52 | |||
| 53 | macro_rules! debug_assert_eq { | ||
| 54 | ($($x:tt)*) => { | ||
| 55 | { | ||
| 56 | #[cfg(not(feature = "defmt"))] | ||
| 57 | ::core::debug_assert_eq!($($x)*); | ||
| 58 | #[cfg(feature = "defmt")] | ||
| 59 | ::defmt::debug_assert_eq!($($x)*); | ||
| 60 | } | ||
| 61 | }; | ||
| 62 | } | ||
| 63 | |||
| 64 | macro_rules! debug_assert_ne { | ||
| 65 | ($($x:tt)*) => { | ||
| 66 | { | ||
| 67 | #[cfg(not(feature = "defmt"))] | ||
| 68 | ::core::debug_assert_ne!($($x)*); | ||
| 69 | #[cfg(feature = "defmt")] | ||
| 70 | ::defmt::debug_assert_ne!($($x)*); | ||
| 71 | } | ||
| 72 | }; | ||
| 73 | } | ||
| 74 | |||
| 75 | macro_rules! todo { | ||
| 76 | ($($x:tt)*) => { | ||
| 77 | { | ||
| 78 | #[cfg(not(feature = "defmt"))] | ||
| 79 | ::core::todo!($($x)*); | ||
| 80 | #[cfg(feature = "defmt")] | ||
| 81 | ::defmt::todo!($($x)*); | ||
| 82 | } | ||
| 83 | }; | ||
| 84 | } | ||
| 85 | |||
| 86 | #[cfg(not(feature = "defmt"))] | ||
| 87 | macro_rules! unreachable { | ||
| 88 | ($($x:tt)*) => { | ||
| 89 | ::core::unreachable!($($x)*) | ||
| 90 | }; | ||
| 91 | } | ||
| 92 | |||
| 93 | #[cfg(feature = "defmt")] | ||
| 94 | macro_rules! unreachable { | ||
| 95 | ($($x:tt)*) => { | ||
| 96 | ::defmt::unreachable!($($x)*); | ||
| 97 | }; | ||
| 98 | } | ||
| 99 | |||
| 100 | macro_rules! panic { | ||
| 101 | ($($x:tt)*) => { | ||
| 102 | { | ||
| 103 | #[cfg(not(feature = "defmt"))] | ||
| 104 | ::core::panic!($($x)*); | ||
| 105 | #[cfg(feature = "defmt")] | ||
| 106 | ::defmt::panic!($($x)*); | ||
| 107 | } | ||
| 108 | }; | ||
| 109 | } | ||
| 110 | |||
| 111 | macro_rules! trace { | ||
| 112 | ($s:literal $(, $x:expr)* $(,)?) => { | ||
| 113 | { | ||
| 114 | #[cfg(feature = "log")] | ||
| 115 | ::log::trace!($s $(, $x)*); | ||
| 116 | #[cfg(feature = "defmt")] | ||
| 117 | ::defmt::trace!($s $(, $x)*); | ||
| 118 | #[cfg(not(any(feature = "log", feature="defmt")))] | ||
| 119 | let _ = ($( & $x ),*); | ||
| 120 | } | ||
| 121 | }; | ||
| 122 | } | ||
| 123 | |||
| 124 | macro_rules! debug { | ||
| 125 | ($s:literal $(, $x:expr)* $(,)?) => { | ||
| 126 | { | ||
| 127 | #[cfg(feature = "log")] | ||
| 128 | ::log::debug!($s $(, $x)*); | ||
| 129 | #[cfg(feature = "defmt")] | ||
| 130 | ::defmt::debug!($s $(, $x)*); | ||
| 131 | #[cfg(not(any(feature = "log", feature="defmt")))] | ||
| 132 | let _ = ($( & $x ),*); | ||
| 133 | } | ||
| 134 | }; | ||
| 135 | } | ||
| 136 | |||
| 137 | macro_rules! info { | ||
| 138 | ($s:literal $(, $x:expr)* $(,)?) => { | ||
| 139 | { | ||
| 140 | #[cfg(feature = "log")] | ||
| 141 | ::log::info!($s $(, $x)*); | ||
| 142 | #[cfg(feature = "defmt")] | ||
| 143 | ::defmt::info!($s $(, $x)*); | ||
| 144 | #[cfg(not(any(feature = "log", feature="defmt")))] | ||
| 145 | let _ = ($( & $x ),*); | ||
| 146 | } | ||
| 147 | }; | ||
| 148 | } | ||
| 149 | |||
| 150 | macro_rules! warn { | ||
| 151 | ($s:literal $(, $x:expr)* $(,)?) => { | ||
| 152 | { | ||
| 153 | #[cfg(feature = "log")] | ||
| 154 | ::log::warn!($s $(, $x)*); | ||
| 155 | #[cfg(feature = "defmt")] | ||
| 156 | ::defmt::warn!($s $(, $x)*); | ||
| 157 | #[cfg(not(any(feature = "log", feature="defmt")))] | ||
| 158 | let _ = ($( & $x ),*); | ||
| 159 | } | ||
| 160 | }; | ||
| 161 | } | ||
| 162 | |||
| 163 | macro_rules! error { | ||
| 164 | ($s:literal $(, $x:expr)* $(,)?) => { | ||
| 165 | { | ||
| 166 | #[cfg(feature = "log")] | ||
| 167 | ::log::error!($s $(, $x)*); | ||
| 168 | #[cfg(feature = "defmt")] | ||
| 169 | ::defmt::error!($s $(, $x)*); | ||
| 170 | #[cfg(not(any(feature = "log", feature="defmt")))] | ||
| 171 | let _ = ($( & $x ),*); | ||
| 172 | } | ||
| 173 | }; | ||
| 174 | } | ||
| 175 | |||
| 176 | #[cfg(feature = "defmt")] | ||
| 177 | macro_rules! unwrap { | ||
| 178 | ($($x:tt)*) => { | ||
| 179 | ::defmt::unwrap!($($x)*) | ||
| 180 | }; | ||
| 181 | } | ||
| 182 | |||
| 183 | #[cfg(not(feature = "defmt"))] | ||
| 184 | macro_rules! unwrap { | ||
| 185 | ($arg:expr) => { | ||
| 186 | match $crate::fmt::Try::into_result($arg) { | ||
| 187 | ::core::result::Result::Ok(t) => t, | ||
| 188 | ::core::result::Result::Err(e) => { | ||
| 189 | ::core::panic!("unwrap of `{}` failed: {:?}", ::core::stringify!($arg), e); | ||
| 190 | } | ||
| 191 | } | ||
| 192 | }; | ||
| 193 | ($arg:expr, $($msg:expr),+ $(,)? ) => { | ||
| 194 | match $crate::fmt::Try::into_result($arg) { | ||
| 195 | ::core::result::Result::Ok(t) => t, | ||
| 196 | ::core::result::Result::Err(e) => { | ||
| 197 | ::core::panic!("unwrap of `{}` failed: {}: {:?}", ::core::stringify!($arg), ::core::format_args!($($msg,)*), e); | ||
| 198 | } | ||
| 199 | } | ||
| 200 | } | ||
| 201 | } | ||
| 202 | |||
| 203 | #[derive(Debug, Copy, Clone, Eq, PartialEq)] | ||
| 204 | pub struct NoneError; | ||
| 205 | |||
| 206 | pub trait Try { | ||
| 207 | type Ok; | ||
| 208 | type Error; | ||
| 209 | fn into_result(self) -> Result<Self::Ok, Self::Error>; | ||
| 210 | } | ||
| 211 | |||
| 212 | impl<T> Try for Option<T> { | ||
| 213 | type Ok = T; | ||
| 214 | type Error = NoneError; | ||
| 215 | |||
| 216 | #[inline] | ||
| 217 | fn into_result(self) -> Result<T, NoneError> { | ||
| 218 | self.ok_or(NoneError) | ||
| 219 | } | ||
| 220 | } | ||
| 221 | |||
| 222 | impl<T, E> Try for Result<T, E> { | ||
| 223 | type Ok = T; | ||
| 224 | type Error = E; | ||
| 225 | |||
| 226 | #[inline] | ||
| 227 | fn into_result(self) -> Self { | ||
| 228 | self | ||
| 229 | } | ||
| 230 | } | ||
| 231 | |||
| 232 | pub struct Bytes<'a>(pub &'a [u8]); | ||
| 233 | |||
| 234 | impl<'a> Debug for Bytes<'a> { | ||
| 235 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { | ||
| 236 | write!(f, "{:#02x?}", self.0) | ||
| 237 | } | ||
| 238 | } | ||
| 239 | |||
| 240 | impl<'a> Display for Bytes<'a> { | ||
| 241 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { | ||
| 242 | write!(f, "{:#02x?}", self.0) | ||
| 243 | } | ||
| 244 | } | ||
| 245 | |||
| 246 | impl<'a> LowerHex for Bytes<'a> { | ||
| 247 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { | ||
| 248 | write!(f, "{:#02x?}", self.0) | ||
| 249 | } | ||
| 250 | } | ||
| 251 | |||
| 252 | #[cfg(feature = "defmt")] | ||
| 253 | impl<'a> defmt::Format for Bytes<'a> { | ||
| 254 | fn format(&self, fmt: defmt::Formatter) { | ||
| 255 | defmt::write!(fmt, "{:02x}", self.0) | ||
| 256 | } | ||
| 257 | } | ||
diff --git a/embassy-net-ppp/src/lib.rs b/embassy-net-ppp/src/lib.rs new file mode 100644 index 000000000..ca87fbaea --- /dev/null +++ b/embassy-net-ppp/src/lib.rs | |||
| @@ -0,0 +1,180 @@ | |||
| 1 | #![no_std] | ||
| 2 | #![warn(missing_docs)] | ||
| 3 | #![doc = include_str!("../README.md")] | ||
| 4 | |||
| 5 | // must be first | ||
| 6 | mod fmt; | ||
| 7 | |||
| 8 | use core::convert::Infallible; | ||
| 9 | use core::mem::MaybeUninit; | ||
| 10 | |||
| 11 | use embassy_futures::select::{select, Either}; | ||
| 12 | use embassy_net_driver_channel as ch; | ||
| 13 | use embassy_net_driver_channel::driver::LinkState; | ||
| 14 | use embedded_io_async::{BufRead, Write, WriteAllError}; | ||
| 15 | use ppproto::pppos::{BufferFullError, PPPoS, PPPoSAction}; | ||
| 16 | pub use ppproto::{Config, Ipv4Status}; | ||
| 17 | |||
| 18 | const MTU: usize = 1500; | ||
| 19 | |||
| 20 | /// Type alias for the embassy-net driver. | ||
| 21 | pub type Device<'d> = embassy_net_driver_channel::Device<'d, MTU>; | ||
| 22 | |||
| 23 | /// Internal state for the embassy-net integration. | ||
| 24 | pub struct State<const N_RX: usize, const N_TX: usize> { | ||
| 25 | ch_state: ch::State<MTU, N_RX, N_TX>, | ||
| 26 | } | ||
| 27 | |||
| 28 | impl<const N_RX: usize, const N_TX: usize> State<N_RX, N_TX> { | ||
| 29 | /// Create a new `State`. | ||
| 30 | pub const fn new() -> Self { | ||
| 31 | Self { | ||
| 32 | ch_state: ch::State::new(), | ||
| 33 | } | ||
| 34 | } | ||
| 35 | } | ||
| 36 | |||
| 37 | /// Background runner for the driver. | ||
| 38 | /// | ||
| 39 | /// You must call `.run()` in a background task for the driver to operate. | ||
| 40 | pub struct Runner<'d> { | ||
| 41 | ch: ch::Runner<'d, MTU>, | ||
| 42 | } | ||
| 43 | |||
| 44 | /// Error returned by [`Runner::run`]. | ||
| 45 | #[derive(Debug)] | ||
| 46 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] | ||
| 47 | pub enum RunError<E> { | ||
| 48 | /// Reading from the serial port failed. | ||
| 49 | Read(E), | ||
| 50 | /// Writing to the serial port failed. | ||
| 51 | Write(E), | ||
| 52 | /// Writing to the serial port wrote zero bytes, indicating it can't accept more data. | ||
| 53 | WriteZero, | ||
| 54 | /// Writing to the serial got EOF. | ||
| 55 | Eof, | ||
| 56 | } | ||
| 57 | |||
| 58 | impl<E> From<WriteAllError<E>> for RunError<E> { | ||
| 59 | fn from(value: WriteAllError<E>) -> Self { | ||
| 60 | match value { | ||
| 61 | WriteAllError::Other(e) => Self::Write(e), | ||
| 62 | WriteAllError::WriteZero => Self::WriteZero, | ||
| 63 | } | ||
| 64 | } | ||
| 65 | } | ||
| 66 | |||
| 67 | impl<'d> Runner<'d> { | ||
| 68 | /// You must call this in a background task for the driver to operate. | ||
| 69 | /// | ||
| 70 | /// If reading/writing to the underlying serial port fails, the link state | ||
| 71 | /// is set to Down and the error is returned. | ||
| 72 | /// | ||
| 73 | /// It is allowed to cancel this function's future (i.e. drop it). This will terminate | ||
| 74 | /// the PPP connection and set the link state to Down. | ||
| 75 | /// | ||
| 76 | /// After this function returns or is canceled, you can call it again to establish | ||
| 77 | /// a new PPP connection. | ||
| 78 | pub async fn run<RW: BufRead + Write>( | ||
| 79 | &mut self, | ||
| 80 | mut rw: RW, | ||
| 81 | config: ppproto::Config<'_>, | ||
| 82 | mut on_ipv4_up: impl FnMut(Ipv4Status), | ||
| 83 | ) -> Result<Infallible, RunError<RW::Error>> { | ||
| 84 | let mut ppp = PPPoS::new(config); | ||
| 85 | ppp.open().unwrap(); | ||
| 86 | |||
| 87 | let (state_chan, mut rx_chan, mut tx_chan) = self.ch.borrow_split(); | ||
| 88 | state_chan.set_link_state(LinkState::Down); | ||
| 89 | let _ondrop = OnDrop::new(|| state_chan.set_link_state(LinkState::Down)); | ||
| 90 | |||
| 91 | let mut rx_buf = [0; 2048]; | ||
| 92 | let mut tx_buf = [0; 2048]; | ||
| 93 | |||
| 94 | let mut needs_poll = true; | ||
| 95 | let mut was_up = false; | ||
| 96 | |||
| 97 | loop { | ||
| 98 | let rx_fut = async { | ||
| 99 | let buf = rx_chan.rx_buf().await; | ||
| 100 | let rx_data = match needs_poll { | ||
| 101 | true => &[][..], | ||
| 102 | false => match rw.fill_buf().await { | ||
| 103 | Ok(rx_data) if rx_data.len() == 0 => return Err(RunError::Eof), | ||
| 104 | Ok(rx_data) => rx_data, | ||
| 105 | Err(e) => return Err(RunError::Read(e)), | ||
| 106 | }, | ||
| 107 | }; | ||
| 108 | Ok((buf, rx_data)) | ||
| 109 | }; | ||
| 110 | let tx_fut = tx_chan.tx_buf(); | ||
| 111 | match select(rx_fut, tx_fut).await { | ||
| 112 | Either::First(r) => { | ||
| 113 | needs_poll = false; | ||
| 114 | |||
| 115 | let (buf, rx_data) = r?; | ||
| 116 | let n = ppp.consume(rx_data, &mut rx_buf); | ||
| 117 | rw.consume(n); | ||
| 118 | |||
| 119 | match ppp.poll(&mut tx_buf, &mut rx_buf) { | ||
| 120 | PPPoSAction::None => {} | ||
| 121 | PPPoSAction::Received(rg) => { | ||
| 122 | let pkt = &rx_buf[rg]; | ||
| 123 | buf[..pkt.len()].copy_from_slice(pkt); | ||
| 124 | rx_chan.rx_done(pkt.len()); | ||
| 125 | } | ||
| 126 | PPPoSAction::Transmit(n) => rw.write_all(&tx_buf[..n]).await?, | ||
| 127 | } | ||
| 128 | |||
| 129 | let status = ppp.status(); | ||
| 130 | match status.phase { | ||
| 131 | ppproto::Phase::Open => { | ||
| 132 | if !was_up { | ||
| 133 | on_ipv4_up(status.ipv4.unwrap()); | ||
| 134 | } | ||
| 135 | was_up = true; | ||
| 136 | state_chan.set_link_state(LinkState::Up); | ||
| 137 | } | ||
| 138 | _ => { | ||
| 139 | was_up = false; | ||
| 140 | state_chan.set_link_state(LinkState::Down); | ||
| 141 | } | ||
| 142 | } | ||
| 143 | } | ||
| 144 | Either::Second(pkt) => { | ||
| 145 | match ppp.send(pkt, &mut tx_buf) { | ||
| 146 | Ok(n) => rw.write_all(&tx_buf[..n]).await?, | ||
| 147 | Err(BufferFullError) => unreachable!(), | ||
| 148 | } | ||
| 149 | tx_chan.tx_done(); | ||
| 150 | } | ||
| 151 | } | ||
| 152 | } | ||
| 153 | } | ||
| 154 | } | ||
| 155 | |||
| 156 | /// Create a PPP embassy-net driver instance. | ||
| 157 | /// | ||
| 158 | /// This returns two structs: | ||
| 159 | /// - a `Device` that you must pass to the `embassy-net` stack. | ||
| 160 | /// - a `Runner`. You must call `.run()` on it in a background task. | ||
| 161 | pub fn new<'a, const N_RX: usize, const N_TX: usize>(state: &'a mut State<N_RX, N_TX>) -> (Device<'a>, Runner<'a>) { | ||
| 162 | let (runner, device) = ch::new(&mut state.ch_state, ch::driver::HardwareAddress::Ip); | ||
| 163 | (device, Runner { ch: runner }) | ||
| 164 | } | ||
| 165 | |||
| 166 | struct OnDrop<F: FnOnce()> { | ||
| 167 | f: MaybeUninit<F>, | ||
| 168 | } | ||
| 169 | |||
| 170 | impl<F: FnOnce()> OnDrop<F> { | ||
| 171 | fn new(f: F) -> Self { | ||
| 172 | Self { f: MaybeUninit::new(f) } | ||
| 173 | } | ||
| 174 | } | ||
| 175 | |||
| 176 | impl<F: FnOnce()> Drop for OnDrop<F> { | ||
| 177 | fn drop(&mut self) { | ||
| 178 | unsafe { self.f.as_ptr().read()() } | ||
| 179 | } | ||
| 180 | } | ||
diff --git a/embassy-net/Cargo.toml b/embassy-net/Cargo.toml index 0c551f204..0361f1db7 100644 --- a/embassy-net/Cargo.toml +++ b/embassy-net/Cargo.toml | |||
| @@ -9,6 +9,7 @@ categories = [ | |||
| 9 | "embedded", | 9 | "embedded", |
| 10 | "no-std", | 10 | "no-std", |
| 11 | "asynchronous", | 11 | "asynchronous", |
| 12 | "network-programming", | ||
| 12 | ] | 13 | ] |
| 13 | 14 | ||
| 14 | [package.metadata.embassy_docs] | 15 | [package.metadata.embassy_docs] |
diff --git a/embassy-net/src/lib.rs b/embassy-net/src/lib.rs index 9f8812894..3a385fad6 100644 --- a/embassy-net/src/lib.rs +++ b/embassy-net/src/lib.rs | |||
| @@ -249,7 +249,10 @@ fn to_smoltcp_hardware_address(addr: driver::HardwareAddress) -> HardwareAddress | |||
| 249 | driver::HardwareAddress::Ip => HardwareAddress::Ip, | 249 | driver::HardwareAddress::Ip => HardwareAddress::Ip, |
| 250 | 250 | ||
| 251 | #[allow(unreachable_patterns)] | 251 | #[allow(unreachable_patterns)] |
| 252 | _ => panic!("Unsupported address {:?}. Make sure to enable medium-ethernet or medium-ieee802154 in embassy-net's Cargo features.", addr), | 252 | _ => panic!( |
| 253 | "Unsupported medium {:?}. Make sure to enable the right medium feature in embassy-net's Cargo features.", | ||
| 254 | addr | ||
| 255 | ), | ||
| 253 | } | 256 | } |
| 254 | } | 257 | } |
| 255 | 258 | ||
diff --git a/examples/std/Cargo.toml b/examples/std/Cargo.toml index 0d4d5fa12..7b0d0bda2 100644 --- a/examples/std/Cargo.toml +++ b/examples/std/Cargo.toml | |||
| @@ -8,11 +8,13 @@ license = "MIT OR Apache-2.0" | |||
| 8 | embassy-sync = { version = "0.2.0", path = "../../embassy-sync", features = ["log"] } | 8 | embassy-sync = { version = "0.2.0", path = "../../embassy-sync", features = ["log"] } |
| 9 | embassy-executor = { version = "0.3.0", path = "../../embassy-executor", features = ["arch-std", "executor-thread", "log", "nightly", "integrated-timers"] } | 9 | embassy-executor = { version = "0.3.0", path = "../../embassy-executor", features = ["arch-std", "executor-thread", "log", "nightly", "integrated-timers"] } |
| 10 | embassy-time = { version = "0.1.2", path = "../../embassy-time", features = ["log", "std", "nightly"] } | 10 | embassy-time = { version = "0.1.2", path = "../../embassy-time", features = ["log", "std", "nightly"] } |
| 11 | embassy-net = { version = "0.1.0", path = "../../embassy-net", features=[ "std", "nightly", "log", "medium-ethernet", "tcp", "udp", "dns", "dhcpv4", "proto-ipv6"] } | 11 | embassy-net = { version = "0.1.0", path = "../../embassy-net", features=[ "std", "nightly", "log", "medium-ethernet", "medium-ip", "tcp", "udp", "dns", "dhcpv4", "proto-ipv6"] } |
| 12 | embassy-net-tuntap = { version = "0.1.0", path = "../../embassy-net-tuntap" } | 12 | embassy-net-tuntap = { version = "0.1.0", path = "../../embassy-net-tuntap" } |
| 13 | embassy-net-ppp = { version = "0.1.0", path = "../../embassy-net-ppp", features = ["log"]} | ||
| 13 | embedded-io-async = { version = "0.5.0" } | 14 | embedded-io-async = { version = "0.5.0" } |
| 14 | embedded-io-adapters = { version = "0.5.0", features = ["futures-03"] } | 15 | embedded-io-adapters = { version = "0.5.0", features = ["futures-03"] } |
| 15 | critical-section = { version = "1.1", features = ["std"] } | 16 | critical-section = { version = "1.1", features = ["std"] } |
| 17 | smoltcp = { version = "0.10.0", features = ["dns-max-server-count-4"] } | ||
| 16 | 18 | ||
| 17 | async-io = "1.6.0" | 19 | async-io = "1.6.0" |
| 18 | env_logger = "0.9.0" | 20 | env_logger = "0.9.0" |
diff --git a/examples/std/src/bin/net_ppp.rs b/examples/std/src/bin/net_ppp.rs new file mode 100644 index 000000000..9cf6e19df --- /dev/null +++ b/examples/std/src/bin/net_ppp.rs | |||
| @@ -0,0 +1,218 @@ | |||
| 1 | //! Testing against pppd: | ||
| 2 | //! | ||
| 3 | //! echo myuser $(hostname) mypass 192.168.7.10 >> /etc/ppp/pap-secrets | ||
| 4 | //! socat -v -x PTY,link=pty1,rawer PTY,link=pty2,rawer | ||
| 5 | //! sudo pppd $PWD/pty1 115200 192.168.7.1: ms-dns 8.8.4.4 ms-dns 8.8.8.8 nodetach debug local persist silent noproxyarp | ||
| 6 | //! RUST_LOG=trace cargo run --bin net_ppp -- --device pty2 | ||
| 7 | //! ping 192.168.7.10 | ||
| 8 | //! nc 192.168.7.10 1234 | ||
| 9 | |||
| 10 | #![feature(type_alias_impl_trait)] | ||
| 11 | #![feature(async_fn_in_trait, impl_trait_projections)] | ||
| 12 | |||
| 13 | #[path = "../serial_port.rs"] | ||
| 14 | mod serial_port; | ||
| 15 | |||
| 16 | use async_io::Async; | ||
| 17 | use clap::Parser; | ||
| 18 | use embassy_executor::{Executor, Spawner}; | ||
| 19 | use embassy_net::tcp::TcpSocket; | ||
| 20 | use embassy_net::{Config, ConfigV4, Ipv4Address, Ipv4Cidr, Stack, StackResources}; | ||
| 21 | use embassy_net_ppp::Runner; | ||
| 22 | use embedded_io_async::Write; | ||
| 23 | use futures::io::BufReader; | ||
| 24 | use heapless::Vec; | ||
| 25 | use log::*; | ||
| 26 | use nix::sys::termios; | ||
| 27 | use rand_core::{OsRng, RngCore}; | ||
| 28 | use static_cell::{make_static, StaticCell}; | ||
| 29 | |||
| 30 | use crate::serial_port::SerialPort; | ||
| 31 | |||
| 32 | #[derive(Parser)] | ||
| 33 | #[clap(version = "1.0")] | ||
| 34 | struct Opts { | ||
| 35 | /// Serial port device name | ||
| 36 | #[clap(short, long)] | ||
| 37 | device: String, | ||
| 38 | } | ||
| 39 | |||
| 40 | #[embassy_executor::task] | ||
| 41 | async fn net_task(stack: &'static Stack<embassy_net_ppp::Device<'static>>) -> ! { | ||
| 42 | stack.run().await | ||
| 43 | } | ||
| 44 | |||
| 45 | #[embassy_executor::task] | ||
| 46 | async fn ppp_task( | ||
| 47 | stack: &'static Stack<embassy_net_ppp::Device<'static>>, | ||
| 48 | mut runner: Runner<'static>, | ||
| 49 | port: SerialPort, | ||
| 50 | ) -> ! { | ||
| 51 | let port = Async::new(port).unwrap(); | ||
| 52 | let port = BufReader::new(port); | ||
| 53 | let port = adapter::FromFutures::new(port); | ||
| 54 | |||
| 55 | let config = embassy_net_ppp::Config { | ||
| 56 | username: b"myuser", | ||
| 57 | password: b"mypass", | ||
| 58 | }; | ||
| 59 | |||
| 60 | runner | ||
| 61 | .run(port, config, |ipv4| { | ||
| 62 | let Some(addr) = ipv4.address else { | ||
| 63 | warn!("PPP did not provide an IP address."); | ||
| 64 | return; | ||
| 65 | }; | ||
| 66 | let mut dns_servers = Vec::new(); | ||
| 67 | for s in ipv4.dns_servers.iter().flatten() { | ||
| 68 | let _ = dns_servers.push(Ipv4Address::from_bytes(&s.0)); | ||
| 69 | } | ||
| 70 | let config = ConfigV4::Static(embassy_net::StaticConfigV4 { | ||
| 71 | address: Ipv4Cidr::new(Ipv4Address::from_bytes(&addr.0), 0), | ||
| 72 | gateway: None, | ||
| 73 | dns_servers, | ||
| 74 | }); | ||
| 75 | stack.set_config_v4(config); | ||
| 76 | }) | ||
| 77 | .await | ||
| 78 | .unwrap(); | ||
| 79 | unreachable!() | ||
| 80 | } | ||
| 81 | |||
| 82 | #[embassy_executor::task] | ||
| 83 | async fn main_task(spawner: Spawner) { | ||
| 84 | let opts: Opts = Opts::parse(); | ||
| 85 | |||
| 86 | // Open serial port | ||
| 87 | let baudrate = termios::BaudRate::B115200; | ||
| 88 | let port = SerialPort::new(opts.device.as_str(), baudrate).unwrap(); | ||
| 89 | |||
| 90 | // Init network device | ||
| 91 | let state = make_static!(embassy_net_ppp::State::<4, 4>::new()); | ||
| 92 | let (device, runner) = embassy_net_ppp::new(state); | ||
| 93 | |||
| 94 | // Generate random seed | ||
| 95 | let mut seed = [0; 8]; | ||
| 96 | OsRng.fill_bytes(&mut seed); | ||
| 97 | let seed = u64::from_le_bytes(seed); | ||
| 98 | |||
| 99 | // Init network stack | ||
| 100 | let stack = &*make_static!(Stack::new( | ||
| 101 | device, | ||
| 102 | Config::default(), // don't configure IP yet | ||
| 103 | make_static!(StackResources::<3>::new()), | ||
| 104 | seed | ||
| 105 | )); | ||
| 106 | |||
| 107 | // Launch network task | ||
| 108 | spawner.spawn(net_task(stack)).unwrap(); | ||
| 109 | spawner.spawn(ppp_task(stack, runner, port)).unwrap(); | ||
| 110 | |||
| 111 | // Then we can use it! | ||
| 112 | let mut rx_buffer = [0; 4096]; | ||
| 113 | let mut tx_buffer = [0; 4096]; | ||
| 114 | let mut buf = [0; 4096]; | ||
| 115 | |||
| 116 | loop { | ||
| 117 | let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer); | ||
| 118 | socket.set_timeout(Some(embassy_time::Duration::from_secs(10))); | ||
| 119 | |||
| 120 | info!("Listening on TCP:1234..."); | ||
| 121 | if let Err(e) = socket.accept(1234).await { | ||
| 122 | warn!("accept error: {:?}", e); | ||
| 123 | continue; | ||
| 124 | } | ||
| 125 | |||
| 126 | info!("Received connection from {:?}", socket.remote_endpoint()); | ||
| 127 | |||
| 128 | loop { | ||
| 129 | let n = match socket.read(&mut buf).await { | ||
| 130 | Ok(0) => { | ||
| 131 | warn!("read EOF"); | ||
| 132 | break; | ||
| 133 | } | ||
| 134 | Ok(n) => n, | ||
| 135 | Err(e) => { | ||
| 136 | warn!("read error: {:?}", e); | ||
| 137 | break; | ||
| 138 | } | ||
| 139 | }; | ||
| 140 | |||
| 141 | info!("rxd {:02x?}", &buf[..n]); | ||
| 142 | |||
| 143 | match socket.write_all(&buf[..n]).await { | ||
| 144 | Ok(()) => {} | ||
| 145 | Err(e) => { | ||
| 146 | warn!("write error: {:?}", e); | ||
| 147 | break; | ||
| 148 | } | ||
| 149 | }; | ||
| 150 | } | ||
| 151 | } | ||
| 152 | } | ||
| 153 | |||
| 154 | static EXECUTOR: StaticCell<Executor> = StaticCell::new(); | ||
| 155 | |||
| 156 | fn main() { | ||
| 157 | env_logger::builder() | ||
| 158 | .filter_level(log::LevelFilter::Trace) | ||
| 159 | .filter_module("polling", log::LevelFilter::Info) | ||
| 160 | .filter_module("async_io", log::LevelFilter::Info) | ||
| 161 | .format_timestamp_nanos() | ||
| 162 | .init(); | ||
| 163 | |||
| 164 | let executor = EXECUTOR.init(Executor::new()); | ||
| 165 | executor.run(|spawner| { | ||
| 166 | spawner.spawn(main_task(spawner)).unwrap(); | ||
| 167 | }); | ||
| 168 | } | ||
| 169 | |||
| 170 | mod adapter { | ||
| 171 | use core::future::poll_fn; | ||
| 172 | use core::pin::Pin; | ||
| 173 | |||
| 174 | use futures::AsyncBufReadExt; | ||
| 175 | |||
| 176 | /// Adapter from `futures::io` traits. | ||
| 177 | #[derive(Clone)] | ||
| 178 | pub struct FromFutures<T: ?Sized> { | ||
| 179 | inner: T, | ||
| 180 | } | ||
| 181 | |||
| 182 | impl<T> FromFutures<T> { | ||
| 183 | /// Create a new adapter. | ||
| 184 | pub fn new(inner: T) -> Self { | ||
| 185 | Self { inner } | ||
| 186 | } | ||
| 187 | } | ||
| 188 | |||
| 189 | impl<T: ?Sized> embedded_io_async::ErrorType for FromFutures<T> { | ||
| 190 | type Error = std::io::Error; | ||
| 191 | } | ||
| 192 | |||
| 193 | impl<T: futures::io::AsyncRead + Unpin + ?Sized> embedded_io_async::Read for FromFutures<T> { | ||
| 194 | async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> { | ||
| 195 | poll_fn(|cx| Pin::new(&mut self.inner).poll_read(cx, buf)).await | ||
| 196 | } | ||
| 197 | } | ||
| 198 | |||
| 199 | impl<T: futures::io::AsyncBufRead + Unpin + ?Sized> embedded_io_async::BufRead for FromFutures<T> { | ||
| 200 | async fn fill_buf(&mut self) -> Result<&[u8], Self::Error> { | ||
| 201 | self.inner.fill_buf().await | ||
| 202 | } | ||
| 203 | |||
| 204 | fn consume(&mut self, amt: usize) { | ||
| 205 | Pin::new(&mut self.inner).consume(amt) | ||
| 206 | } | ||
| 207 | } | ||
| 208 | |||
| 209 | impl<T: futures::io::AsyncWrite + Unpin + ?Sized> embedded_io_async::Write for FromFutures<T> { | ||
| 210 | async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> { | ||
| 211 | poll_fn(|cx| Pin::new(&mut self.inner).poll_write(cx, buf)).await | ||
| 212 | } | ||
| 213 | |||
| 214 | async fn flush(&mut self) -> Result<(), Self::Error> { | ||
| 215 | poll_fn(|cx| Pin::new(&mut self.inner).poll_flush(cx)).await | ||
| 216 | } | ||
| 217 | } | ||
| 218 | } | ||
