aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--embassy-net-driver-channel/src/lib.rs19
-rw-r--r--embassy-net-ppp/Cargo.toml28
-rw-r--r--embassy-net-ppp/README.md19
-rw-r--r--embassy-net-ppp/src/fmt.rs257
-rw-r--r--embassy-net-ppp/src/lib.rs180
-rw-r--r--embassy-net/Cargo.toml1
-rw-r--r--embassy-net/src/lib.rs5
-rw-r--r--examples/std/Cargo.toml4
-rw-r--r--examples/std/src/bin/net_ppp.rs218
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;
8use core::mem::MaybeUninit; 8use core::mem::MaybeUninit;
9use core::task::{Context, Poll}; 9use core::task::{Context, Poll};
10 10
11use driver::HardwareAddress;
11pub use embassy_net_driver as driver; 12pub use embassy_net_driver as driver;
12use embassy_net_driver::{Capabilities, LinkState, Medium}; 13use embassy_net_driver::{Capabilities, LinkState, Medium};
13use embassy_sync::blocking_mutex::raw::NoopRawMutex; 14use 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]
2name = "embassy-net-ppp"
3version = "0.1.0"
4description = "embassy-net driver for PPP over Serial"
5keywords = ["embedded", "ppp", "embassy-net", "embedded-hal-async", "ethernet", "async"]
6categories = ["embedded", "hardware-support", "no-std", "network-programming", "async"]
7license = "MIT OR Apache-2.0"
8edition = "2021"
9
10[features]
11defmt = ["dep:defmt", "ppproto/defmt"]
12log = ["dep:log", "ppproto/log"]
13
14[dependencies]
15defmt = { version = "0.3", optional = true }
16log = { version = "0.4.14", optional = true }
17
18embedded-io-async = { version = "0.5.0" }
19embassy-net-driver-channel = { version = "0.1.0", path = "../embassy-net-driver-channel" }
20embassy-futures = { version = "0.1.0", path = "../embassy-futures" }
21ppproto = { version = "0.1.1"}
22embassy-sync = { version = "0.2.0", path = "../embassy-sync" }
23
24[package.metadata.embassy_docs]
25src_base = "https://github.com/embassy-rs/embassy/blob/embassy-net-ppp-v$VERSION/embassy-net-ppp/src/"
26src_base_git = "https://github.com/embassy-rs/embassy/blob/$COMMIT/embassy-net-ppp/src/"
27target = "thumbv7em-none-eabi"
28features = ["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
7This crate can run on any executor.
8
9It supports any serial port implementing [`embedded-io-async`](https://crates.io/crates/embedded-io-async).
10
11## License
12
13This 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
19at 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
4use core::fmt::{Debug, Display, LowerHex};
5
6#[cfg(all(feature = "defmt", feature = "log"))]
7compile_error!("You may not enable both `defmt` and `log` features.");
8
9macro_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
20macro_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
31macro_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
42macro_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
53macro_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
64macro_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
75macro_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"))]
87macro_rules! unreachable {
88 ($($x:tt)*) => {
89 ::core::unreachable!($($x)*)
90 };
91}
92
93#[cfg(feature = "defmt")]
94macro_rules! unreachable {
95 ($($x:tt)*) => {
96 ::defmt::unreachable!($($x)*);
97 };
98}
99
100macro_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
111macro_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
124macro_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
137macro_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
150macro_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
163macro_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")]
177macro_rules! unwrap {
178 ($($x:tt)*) => {
179 ::defmt::unwrap!($($x)*)
180 };
181}
182
183#[cfg(not(feature = "defmt"))]
184macro_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)]
204pub struct NoneError;
205
206pub trait Try {
207 type Ok;
208 type Error;
209 fn into_result(self) -> Result<Self::Ok, Self::Error>;
210}
211
212impl<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
222impl<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
232pub struct Bytes<'a>(pub &'a [u8]);
233
234impl<'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
240impl<'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
246impl<'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")]
253impl<'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
6mod fmt;
7
8use core::convert::Infallible;
9use core::mem::MaybeUninit;
10
11use embassy_futures::select::{select, Either};
12use embassy_net_driver_channel as ch;
13use embassy_net_driver_channel::driver::LinkState;
14use embedded_io_async::{BufRead, Write, WriteAllError};
15use ppproto::pppos::{BufferFullError, PPPoS, PPPoSAction};
16pub use ppproto::{Config, Ipv4Status};
17
18const MTU: usize = 1500;
19
20/// Type alias for the embassy-net driver.
21pub type Device<'d> = embassy_net_driver_channel::Device<'d, MTU>;
22
23/// Internal state for the embassy-net integration.
24pub struct State<const N_RX: usize, const N_TX: usize> {
25 ch_state: ch::State<MTU, N_RX, N_TX>,
26}
27
28impl<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.
40pub 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))]
47pub 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
58impl<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
67impl<'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.
161pub 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
166struct OnDrop<F: FnOnce()> {
167 f: MaybeUninit<F>,
168}
169
170impl<F: FnOnce()> OnDrop<F> {
171 fn new(f: F) -> Self {
172 Self { f: MaybeUninit::new(f) }
173 }
174}
175
176impl<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"
8embassy-sync = { version = "0.2.0", path = "../../embassy-sync", features = ["log"] } 8embassy-sync = { version = "0.2.0", path = "../../embassy-sync", features = ["log"] }
9embassy-executor = { version = "0.3.0", path = "../../embassy-executor", features = ["arch-std", "executor-thread", "log", "nightly", "integrated-timers"] } 9embassy-executor = { version = "0.3.0", path = "../../embassy-executor", features = ["arch-std", "executor-thread", "log", "nightly", "integrated-timers"] }
10embassy-time = { version = "0.1.2", path = "../../embassy-time", features = ["log", "std", "nightly"] } 10embassy-time = { version = "0.1.2", path = "../../embassy-time", features = ["log", "std", "nightly"] }
11embassy-net = { version = "0.1.0", path = "../../embassy-net", features=[ "std", "nightly", "log", "medium-ethernet", "tcp", "udp", "dns", "dhcpv4", "proto-ipv6"] } 11embassy-net = { version = "0.1.0", path = "../../embassy-net", features=[ "std", "nightly", "log", "medium-ethernet", "medium-ip", "tcp", "udp", "dns", "dhcpv4", "proto-ipv6"] }
12embassy-net-tuntap = { version = "0.1.0", path = "../../embassy-net-tuntap" } 12embassy-net-tuntap = { version = "0.1.0", path = "../../embassy-net-tuntap" }
13embassy-net-ppp = { version = "0.1.0", path = "../../embassy-net-ppp", features = ["log"]}
13embedded-io-async = { version = "0.5.0" } 14embedded-io-async = { version = "0.5.0" }
14embedded-io-adapters = { version = "0.5.0", features = ["futures-03"] } 15embedded-io-adapters = { version = "0.5.0", features = ["futures-03"] }
15critical-section = { version = "1.1", features = ["std"] } 16critical-section = { version = "1.1", features = ["std"] }
17smoltcp = { version = "0.10.0", features = ["dns-max-server-count-4"] }
16 18
17async-io = "1.6.0" 19async-io = "1.6.0"
18env_logger = "0.9.0" 20env_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"]
14mod serial_port;
15
16use async_io::Async;
17use clap::Parser;
18use embassy_executor::{Executor, Spawner};
19use embassy_net::tcp::TcpSocket;
20use embassy_net::{Config, ConfigV4, Ipv4Address, Ipv4Cidr, Stack, StackResources};
21use embassy_net_ppp::Runner;
22use embedded_io_async::Write;
23use futures::io::BufReader;
24use heapless::Vec;
25use log::*;
26use nix::sys::termios;
27use rand_core::{OsRng, RngCore};
28use static_cell::{make_static, StaticCell};
29
30use crate::serial_port::SerialPort;
31
32#[derive(Parser)]
33#[clap(version = "1.0")]
34struct Opts {
35 /// Serial port device name
36 #[clap(short, long)]
37 device: String,
38}
39
40#[embassy_executor::task]
41async fn net_task(stack: &'static Stack<embassy_net_ppp::Device<'static>>) -> ! {
42 stack.run().await
43}
44
45#[embassy_executor::task]
46async 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]
83async 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
154static EXECUTOR: StaticCell<Executor> = StaticCell::new();
155
156fn 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
170mod 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}