net-ppp: Add it.

This commit is contained in:
Dario Nieuwenhuis 2023-08-25 01:04:51 +02:00
parent 100200d021
commit aacf14b62a
4 changed files with 469 additions and 0 deletions

View File

@ -0,0 +1,28 @@
[package]
name = "embassy-net-ppp"
version = "0.1.0"
description = "embassy-net driver for PPP over Serial"
keywords = ["embedded", "ppp", "embassy-net", "embedded-hal-async", "ethernet", "async"]
categories = ["embedded", "hardware-support", "no-std", "network-programming", "async"]
license = "MIT OR Apache-2.0"
edition = "2021"
[features]
defmt = ["dep:defmt", "ppproto/defmt"]
log = ["dep:log", "ppproto/log"]
[dependencies]
defmt = { version = "0.3", optional = true }
log = { version = "0.4.14", optional = true }
embedded-io-async = { version = "0.5.0" }
embassy-net-driver-channel = { version = "0.1.0", path = "../embassy-net-driver-channel" }
embassy-futures = { version = "0.1.0", path = "../embassy-futures" }
ppproto = { version = "0.1.1"}
embassy-sync = { version = "0.2.0", path = "../embassy-sync" }
[package.metadata.embassy_docs]
src_base = "https://github.com/embassy-rs/embassy/blob/embassy-net-ppp-v$VERSION/embassy-net-ppp/src/"
src_base_git = "https://github.com/embassy-rs/embassy/blob/$COMMIT/embassy-net-ppp/src/"
target = "thumbv7em-none-eabi"
features = ["defmt"]

19
embassy-net-ppp/README.md Normal file
View File

@ -0,0 +1,19 @@
# `embassy-net-ppp`
[`embassy-net`](https://crates.io/crates/embassy-net) integration for PPP over Serial.
## Interoperability
This crate can run on any executor.
It supports any serial port implementing [`embedded-io-async`](https://crates.io/crates/embedded-io-async).
## License
This work is licensed under either of
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or
http://www.apache.org/licenses/LICENSE-2.0)
- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
at your option.

257
embassy-net-ppp/src/fmt.rs Normal file
View File

@ -0,0 +1,257 @@
#![macro_use]
#![allow(unused_macros)]
use core::fmt::{Debug, Display, LowerHex};
#[cfg(all(feature = "defmt", feature = "log"))]
compile_error!("You may not enable both `defmt` and `log` features.");
macro_rules! assert {
($($x:tt)*) => {
{
#[cfg(not(feature = "defmt"))]
::core::assert!($($x)*);
#[cfg(feature = "defmt")]
::defmt::assert!($($x)*);
}
};
}
macro_rules! assert_eq {
($($x:tt)*) => {
{
#[cfg(not(feature = "defmt"))]
::core::assert_eq!($($x)*);
#[cfg(feature = "defmt")]
::defmt::assert_eq!($($x)*);
}
};
}
macro_rules! assert_ne {
($($x:tt)*) => {
{
#[cfg(not(feature = "defmt"))]
::core::assert_ne!($($x)*);
#[cfg(feature = "defmt")]
::defmt::assert_ne!($($x)*);
}
};
}
macro_rules! debug_assert {
($($x:tt)*) => {
{
#[cfg(not(feature = "defmt"))]
::core::debug_assert!($($x)*);
#[cfg(feature = "defmt")]
::defmt::debug_assert!($($x)*);
}
};
}
macro_rules! debug_assert_eq {
($($x:tt)*) => {
{
#[cfg(not(feature = "defmt"))]
::core::debug_assert_eq!($($x)*);
#[cfg(feature = "defmt")]
::defmt::debug_assert_eq!($($x)*);
}
};
}
macro_rules! debug_assert_ne {
($($x:tt)*) => {
{
#[cfg(not(feature = "defmt"))]
::core::debug_assert_ne!($($x)*);
#[cfg(feature = "defmt")]
::defmt::debug_assert_ne!($($x)*);
}
};
}
macro_rules! todo {
($($x:tt)*) => {
{
#[cfg(not(feature = "defmt"))]
::core::todo!($($x)*);
#[cfg(feature = "defmt")]
::defmt::todo!($($x)*);
}
};
}
#[cfg(not(feature = "defmt"))]
macro_rules! unreachable {
($($x:tt)*) => {
::core::unreachable!($($x)*)
};
}
#[cfg(feature = "defmt")]
macro_rules! unreachable {
($($x:tt)*) => {
::defmt::unreachable!($($x)*);
};
}
macro_rules! panic {
($($x:tt)*) => {
{
#[cfg(not(feature = "defmt"))]
::core::panic!($($x)*);
#[cfg(feature = "defmt")]
::defmt::panic!($($x)*);
}
};
}
macro_rules! trace {
($s:literal $(, $x:expr)* $(,)?) => {
{
#[cfg(feature = "log")]
::log::trace!($s $(, $x)*);
#[cfg(feature = "defmt")]
::defmt::trace!($s $(, $x)*);
#[cfg(not(any(feature = "log", feature="defmt")))]
let _ = ($( & $x ),*);
}
};
}
macro_rules! debug {
($s:literal $(, $x:expr)* $(,)?) => {
{
#[cfg(feature = "log")]
::log::debug!($s $(, $x)*);
#[cfg(feature = "defmt")]
::defmt::debug!($s $(, $x)*);
#[cfg(not(any(feature = "log", feature="defmt")))]
let _ = ($( & $x ),*);
}
};
}
macro_rules! info {
($s:literal $(, $x:expr)* $(,)?) => {
{
#[cfg(feature = "log")]
::log::info!($s $(, $x)*);
#[cfg(feature = "defmt")]
::defmt::info!($s $(, $x)*);
#[cfg(not(any(feature = "log", feature="defmt")))]
let _ = ($( & $x ),*);
}
};
}
macro_rules! warn {
($s:literal $(, $x:expr)* $(,)?) => {
{
#[cfg(feature = "log")]
::log::warn!($s $(, $x)*);
#[cfg(feature = "defmt")]
::defmt::warn!($s $(, $x)*);
#[cfg(not(any(feature = "log", feature="defmt")))]
let _ = ($( & $x ),*);
}
};
}
macro_rules! error {
($s:literal $(, $x:expr)* $(,)?) => {
{
#[cfg(feature = "log")]
::log::error!($s $(, $x)*);
#[cfg(feature = "defmt")]
::defmt::error!($s $(, $x)*);
#[cfg(not(any(feature = "log", feature="defmt")))]
let _ = ($( & $x ),*);
}
};
}
#[cfg(feature = "defmt")]
macro_rules! unwrap {
($($x:tt)*) => {
::defmt::unwrap!($($x)*)
};
}
#[cfg(not(feature = "defmt"))]
macro_rules! unwrap {
($arg:expr) => {
match $crate::fmt::Try::into_result($arg) {
::core::result::Result::Ok(t) => t,
::core::result::Result::Err(e) => {
::core::panic!("unwrap of `{}` failed: {:?}", ::core::stringify!($arg), e);
}
}
};
($arg:expr, $($msg:expr),+ $(,)? ) => {
match $crate::fmt::Try::into_result($arg) {
::core::result::Result::Ok(t) => t,
::core::result::Result::Err(e) => {
::core::panic!("unwrap of `{}` failed: {}: {:?}", ::core::stringify!($arg), ::core::format_args!($($msg,)*), e);
}
}
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct NoneError;
pub trait Try {
type Ok;
type Error;
fn into_result(self) -> Result<Self::Ok, Self::Error>;
}
impl<T> Try for Option<T> {
type Ok = T;
type Error = NoneError;
#[inline]
fn into_result(self) -> Result<T, NoneError> {
self.ok_or(NoneError)
}
}
impl<T, E> Try for Result<T, E> {
type Ok = T;
type Error = E;
#[inline]
fn into_result(self) -> Self {
self
}
}
pub struct Bytes<'a>(pub &'a [u8]);
impl<'a> Debug for Bytes<'a> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{:#02x?}", self.0)
}
}
impl<'a> Display for Bytes<'a> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{:#02x?}", self.0)
}
}
impl<'a> LowerHex for Bytes<'a> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{:#02x?}", self.0)
}
}
#[cfg(feature = "defmt")]
impl<'a> defmt::Format for Bytes<'a> {
fn format(&self, fmt: defmt::Formatter) {
defmt::write!(fmt, "{:02x}", self.0)
}
}

165
embassy-net-ppp/src/lib.rs Normal file
View File

@ -0,0 +1,165 @@
#![no_std]
#![warn(missing_docs)]
#![doc = include_str!("../README.md")]
// must be first
mod fmt;
use core::convert::Infallible;
use core::mem::MaybeUninit;
use embassy_futures::select::{select3, Either3};
use embassy_net_driver_channel as ch;
use embassy_net_driver_channel::driver::LinkState;
use embassy_sync::blocking_mutex::raw::NoopRawMutex;
use embassy_sync::signal::Signal;
use embedded_io_async::{BufRead, Write, WriteAllError};
use ppproto::pppos::{BufferFullError, PPPoS, PPPoSAction};
const MTU: usize = 1500;
/// Type alias for the embassy-net driver.
pub type Device<'d> = embassy_net_driver_channel::Device<'d, MTU>;
/// Internal state for the embassy-net integration.
pub struct State<const N_RX: usize, const N_TX: usize> {
ch_state: ch::State<MTU, N_RX, N_TX>,
}
impl<const N_RX: usize, const N_TX: usize> State<N_RX, N_TX> {
/// Create a new `State`.
pub const fn new() -> Self {
Self {
ch_state: ch::State::new(),
}
}
}
/// Background runner for the driver.
///
/// You must call `.run()` in a background task for the driver to operate.
pub struct Runner<'d, R: BufRead, W: Write> {
ch: ch::Runner<'d, MTU>,
r: R,
w: W,
}
/// Error returned by [`Runner::run`].
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum RunError<RE, WE> {
/// Reading from the serial port failed.
Read(RE),
/// Writing to the serial port failed.
Write(WE),
/// Writing to the serial port wrote zero bytes, indicating it can't accept more data.
WriteZero,
/// Writing to the serial got EOF.
Eof,
}
impl<'d, R: BufRead, W: Write> Runner<'d, R, W> {
/// You must call this in a background task for the driver to operate.
pub async fn run(mut self) -> Result<Infallible, RunError<R::Error, W::Error>> {
let config = ppproto::Config {
username: b"myuser",
password: b"mypass",
};
let mut ppp = PPPoS::new(config);
ppp.open().unwrap();
let (state_chan, mut rx_chan, mut tx_chan) = self.ch.split();
state_chan.set_link_state(LinkState::Down);
let _ondrop = OnDrop::new(|| state_chan.set_link_state(LinkState::Down));
let mut rx_buf = [0; 2048];
let mut tx_buf = [0; 2048];
let poll_signal: Signal<NoopRawMutex, ()> = Signal::new();
poll_signal.signal(());
loop {
let mut poll = false;
match select3(self.r.fill_buf(), tx_chan.tx_buf(), poll_signal.wait()).await {
Either3::First(r) => {
let data = r.map_err(RunError::Read)?;
if data.is_empty() {
return Err(RunError::Eof);
}
let n = ppp.consume(data, &mut rx_buf);
self.r.consume(n);
poll = true;
}
Either3::Second(pkt) => {
match ppp.send(pkt, &mut tx_buf) {
Ok(n) => match self.w.write_all(&tx_buf[..n]).await {
Ok(()) => {}
Err(WriteAllError::WriteZero) => return Err(RunError::WriteZero),
Err(WriteAllError::Other(e)) => return Err(RunError::Write(e)),
},
Err(BufferFullError) => unreachable!(),
}
tx_chan.tx_done();
}
Either3::Third(_) => poll = true,
}
if poll {
match ppp.poll(&mut tx_buf, &mut rx_buf) {
PPPoSAction::None => {}
PPPoSAction::Received(rg) => {
let pkt = &rx_buf[rg];
let buf = rx_chan.rx_buf().await; // TODO: fix possible deadlock
buf[..pkt.len()].copy_from_slice(pkt);
rx_chan.rx_done(pkt.len());
poll_signal.signal(());
}
PPPoSAction::Transmit(n) => {
match self.w.write_all(&tx_buf[..n]).await {
Ok(()) => {}
Err(WriteAllError::WriteZero) => return Err(RunError::WriteZero),
Err(WriteAllError::Other(e)) => return Err(RunError::Write(e)),
}
poll_signal.signal(());
}
}
match ppp.status().phase {
ppproto::Phase::Open => state_chan.set_link_state(LinkState::Up),
_ => state_chan.set_link_state(LinkState::Down),
}
}
}
}
}
/// Create a PPP embassy-net driver instance.
///
/// This returns two structs:
/// - a `Device` that you must pass to the `embassy-net` stack.
/// - a `Runner`. You must call `.run()` on it in a background task.
pub fn new<'a, const N_RX: usize, const N_TX: usize, R: BufRead, W: Write>(
state: &'a mut State<N_RX, N_TX>,
r: R,
w: W,
) -> (Device<'a>, Runner<'a, R, W>) {
let (runner, device) = ch::new(&mut state.ch_state, ch::driver::HardwareAddress::Ip);
(device, Runner { ch: runner, r, w })
}
struct OnDrop<F: FnOnce()> {
f: MaybeUninit<F>,
}
impl<F: FnOnce()> OnDrop<F> {
fn new(f: F) -> Self {
Self { f: MaybeUninit::new(f) }
}
}
impl<F: FnOnce()> Drop for OnDrop<F> {
fn drop(&mut self) {
unsafe { self.f.as_ptr().read()() }
}
}