mirror of
https://github.com/embassy-rs/embassy.git
synced 2024-11-22 14:53:03 +00:00
usb/cdc-ncm: add embassy-net Device implementation.
This commit is contained in:
parent
aaaf5f23a8
commit
e9219405ca
@ -19,6 +19,7 @@ default = ["usbd-hid"]
|
|||||||
embassy-futures = { version = "0.1.0", path = "../embassy-futures" }
|
embassy-futures = { version = "0.1.0", path = "../embassy-futures" }
|
||||||
embassy-usb-driver = { version = "0.1.0", path = "../embassy-usb-driver" }
|
embassy-usb-driver = { version = "0.1.0", path = "../embassy-usb-driver" }
|
||||||
embassy-sync = { version = "0.1.0", path = "../embassy-sync" }
|
embassy-sync = { version = "0.1.0", path = "../embassy-sync" }
|
||||||
|
embassy-net = { version = "0.1.0", path = "../embassy-net", optional = true }
|
||||||
|
|
||||||
defmt = { version = "0.3", optional = true }
|
defmt = { version = "0.3", optional = true }
|
||||||
log = { version = "0.4.14", optional = true }
|
log = { version = "0.4.14", optional = true }
|
||||||
|
449
embassy-usb/src/class/cdc_ncm/embassy_net.rs
Normal file
449
embassy-usb/src/class/cdc_ncm/embassy_net.rs
Normal file
@ -0,0 +1,449 @@
|
|||||||
|
use core::cell::RefCell;
|
||||||
|
use core::mem::MaybeUninit;
|
||||||
|
use core::task::Context;
|
||||||
|
|
||||||
|
use embassy_futures::select::{select, Either};
|
||||||
|
use embassy_net::device::{Device as DeviceTrait, DeviceCapabilities, LinkState, Medium};
|
||||||
|
use embassy_sync::blocking_mutex::raw::NoopRawMutex;
|
||||||
|
use embassy_sync::blocking_mutex::Mutex;
|
||||||
|
use embassy_sync::waitqueue::WakerRegistration;
|
||||||
|
use embassy_usb_driver::Driver;
|
||||||
|
|
||||||
|
use super::{CdcNcmClass, Receiver, Sender};
|
||||||
|
|
||||||
|
pub struct State<'d, const MTU: usize, const N_RX: usize, const N_TX: usize> {
|
||||||
|
rx: [PacketBuf<MTU>; N_RX],
|
||||||
|
tx: [PacketBuf<MTU>; N_TX],
|
||||||
|
inner: MaybeUninit<StateInner<'d, MTU>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'d, const MTU: usize, const N_RX: usize, const N_TX: usize> State<'d, MTU, N_RX, N_TX> {
|
||||||
|
const NEW_PACKET: PacketBuf<MTU> = PacketBuf::new();
|
||||||
|
|
||||||
|
pub const fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
rx: [Self::NEW_PACKET; N_RX],
|
||||||
|
tx: [Self::NEW_PACKET; N_TX],
|
||||||
|
inner: MaybeUninit::uninit(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct StateInner<'d, const MTU: usize> {
|
||||||
|
rx: zerocopy_channel::Channel<'d, NoopRawMutex, PacketBuf<MTU>>,
|
||||||
|
tx: zerocopy_channel::Channel<'d, NoopRawMutex, PacketBuf<MTU>>,
|
||||||
|
link_state: Mutex<NoopRawMutex, RefCell<LinkStateState>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// State of the LinkState
|
||||||
|
struct LinkStateState {
|
||||||
|
state: LinkState,
|
||||||
|
waker: WakerRegistration,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Runner<'d, D: Driver<'d>, const MTU: usize> {
|
||||||
|
tx_usb: Sender<'d, D>,
|
||||||
|
tx_chan: zerocopy_channel::Receiver<'d, NoopRawMutex, PacketBuf<MTU>>,
|
||||||
|
rx_usb: Receiver<'d, D>,
|
||||||
|
rx_chan: zerocopy_channel::Sender<'d, NoopRawMutex, PacketBuf<MTU>>,
|
||||||
|
link_state: &'d Mutex<NoopRawMutex, RefCell<LinkStateState>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'d, D: Driver<'d>, const MTU: usize> Runner<'d, D, MTU> {
|
||||||
|
pub async fn run(mut self) -> ! {
|
||||||
|
let rx_fut = async move {
|
||||||
|
loop {
|
||||||
|
trace!("WAITING for connection");
|
||||||
|
self.link_state.lock(|s| {
|
||||||
|
let s = &mut *s.borrow_mut();
|
||||||
|
s.state = LinkState::Down;
|
||||||
|
s.waker.wake();
|
||||||
|
});
|
||||||
|
|
||||||
|
self.rx_usb.wait_connection().await.unwrap();
|
||||||
|
|
||||||
|
trace!("Connected");
|
||||||
|
self.link_state.lock(|s| {
|
||||||
|
let s = &mut *s.borrow_mut();
|
||||||
|
s.state = LinkState::Up;
|
||||||
|
s.waker.wake();
|
||||||
|
});
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let p = self.rx_chan.send().await;
|
||||||
|
match self.rx_usb.read_packet(&mut p.buf).await {
|
||||||
|
Ok(n) => {
|
||||||
|
p.len = n;
|
||||||
|
self.rx_chan.send_done();
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
warn!("error reading packet: {:?}", e);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let tx_fut = async move {
|
||||||
|
loop {
|
||||||
|
let p = self.tx_chan.recv().await;
|
||||||
|
if let Err(e) = self.tx_usb.write_packet(&p.buf[..p.len]).await {
|
||||||
|
warn!("Failed to TX packet: {:?}", e);
|
||||||
|
}
|
||||||
|
self.tx_chan.recv_done();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match select(rx_fut, tx_fut).await {
|
||||||
|
Either::First(x) => x,
|
||||||
|
Either::Second(x) => x,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'d, D: Driver<'d>> CdcNcmClass<'d, D> {
|
||||||
|
pub fn into_embassy_net_device<const MTU: usize, const N_RX: usize, const N_TX: usize>(
|
||||||
|
self,
|
||||||
|
state: &'d mut State<'d, MTU, N_RX, N_TX>,
|
||||||
|
ethernet_address: [u8; 6],
|
||||||
|
) -> (Runner<'d, D, MTU>, Device<'d, MTU>) {
|
||||||
|
let (tx_usb, rx_usb) = self.split();
|
||||||
|
|
||||||
|
let mut caps = DeviceCapabilities::default();
|
||||||
|
caps.max_transmission_unit = 1514; // 1500 IP + 14 ethernet header
|
||||||
|
caps.medium = Medium::Ethernet;
|
||||||
|
|
||||||
|
let state = state.inner.write(StateInner {
|
||||||
|
rx: zerocopy_channel::Channel::new(&mut state.rx[..]),
|
||||||
|
tx: zerocopy_channel::Channel::new(&mut state.tx[..]),
|
||||||
|
link_state: Mutex::new(RefCell::new(LinkStateState {
|
||||||
|
state: LinkState::Down,
|
||||||
|
waker: WakerRegistration::new(),
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
|
||||||
|
let (rx_sender, rx_receiver) = state.rx.split();
|
||||||
|
let (tx_sender, tx_receiver) = state.tx.split();
|
||||||
|
|
||||||
|
(
|
||||||
|
Runner {
|
||||||
|
tx_usb,
|
||||||
|
tx_chan: tx_receiver,
|
||||||
|
rx_usb,
|
||||||
|
rx_chan: rx_sender,
|
||||||
|
link_state: &state.link_state,
|
||||||
|
},
|
||||||
|
Device {
|
||||||
|
caps,
|
||||||
|
ethernet_address,
|
||||||
|
link_state: &state.link_state,
|
||||||
|
rx: rx_receiver,
|
||||||
|
tx: tx_sender,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct PacketBuf<const MTU: usize> {
|
||||||
|
len: usize,
|
||||||
|
buf: [u8; MTU],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const MTU: usize> PacketBuf<MTU> {
|
||||||
|
pub const fn new() -> Self {
|
||||||
|
Self { len: 0, buf: [0; MTU] }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Device<'d, const MTU: usize> {
|
||||||
|
rx: zerocopy_channel::Receiver<'d, NoopRawMutex, PacketBuf<MTU>>,
|
||||||
|
tx: zerocopy_channel::Sender<'d, NoopRawMutex, PacketBuf<MTU>>,
|
||||||
|
link_state: &'d Mutex<NoopRawMutex, RefCell<LinkStateState>>,
|
||||||
|
caps: DeviceCapabilities,
|
||||||
|
ethernet_address: [u8; 6],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'d, const MTU: usize> DeviceTrait for Device<'d, MTU> {
|
||||||
|
type RxToken<'a> = RxToken<'a, MTU> where Self: 'a ;
|
||||||
|
type TxToken<'a> = TxToken<'a, MTU> where Self: 'a ;
|
||||||
|
|
||||||
|
fn receive(&mut self, cx: &mut Context) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> {
|
||||||
|
if self.rx.poll_recv(cx).is_ready() && self.tx.poll_send(cx).is_ready() {
|
||||||
|
Some((RxToken { rx: self.rx.borrow() }, TxToken { tx: self.tx.borrow() }))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Construct a transmit token.
|
||||||
|
fn transmit(&mut self, cx: &mut Context) -> Option<Self::TxToken<'_>> {
|
||||||
|
if self.tx.poll_send(cx).is_ready() {
|
||||||
|
Some(TxToken { tx: self.tx.borrow() })
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get a description of device capabilities.
|
||||||
|
fn capabilities(&self) -> DeviceCapabilities {
|
||||||
|
self.caps.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ethernet_address(&self) -> [u8; 6] {
|
||||||
|
self.ethernet_address
|
||||||
|
}
|
||||||
|
|
||||||
|
fn link_state(&mut self, cx: &mut Context) -> LinkState {
|
||||||
|
self.link_state.lock(|s| {
|
||||||
|
let s = &mut *s.borrow_mut();
|
||||||
|
s.waker.register(cx.waker());
|
||||||
|
s.state
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct RxToken<'a, const MTU: usize> {
|
||||||
|
rx: zerocopy_channel::Receiver<'a, NoopRawMutex, PacketBuf<MTU>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, const MTU: usize> embassy_net::device::RxToken for RxToken<'a, MTU> {
|
||||||
|
fn consume<R, F>(mut self, f: F) -> R
|
||||||
|
where
|
||||||
|
F: FnOnce(&mut [u8]) -> R,
|
||||||
|
{
|
||||||
|
// NOTE(unwrap): we checked the queue wasn't full when creating the token.
|
||||||
|
let pkt = unwrap!(self.rx.try_recv());
|
||||||
|
let r = f(&mut pkt.buf[..pkt.len]);
|
||||||
|
self.rx.recv_done();
|
||||||
|
r
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct TxToken<'a, const MTU: usize> {
|
||||||
|
tx: zerocopy_channel::Sender<'a, NoopRawMutex, PacketBuf<MTU>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, const MTU: usize> embassy_net::device::TxToken for TxToken<'a, MTU> {
|
||||||
|
fn consume<R, F>(mut self, len: usize, f: F) -> R
|
||||||
|
where
|
||||||
|
F: FnOnce(&mut [u8]) -> R,
|
||||||
|
{
|
||||||
|
// NOTE(unwrap): we checked the queue wasn't full when creating the token.
|
||||||
|
let pkt = unwrap!(self.tx.try_send());
|
||||||
|
let r = f(&mut pkt.buf[..len]);
|
||||||
|
pkt.len = len;
|
||||||
|
self.tx.send_done();
|
||||||
|
r
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
mod zerocopy_channel {
|
||||||
|
use core::cell::RefCell;
|
||||||
|
use core::future::poll_fn;
|
||||||
|
use core::marker::PhantomData;
|
||||||
|
use core::task::{Context, Poll};
|
||||||
|
|
||||||
|
use embassy_sync::blocking_mutex::raw::RawMutex;
|
||||||
|
use embassy_sync::blocking_mutex::Mutex;
|
||||||
|
use embassy_sync::waitqueue::WakerRegistration;
|
||||||
|
|
||||||
|
pub struct Channel<'a, M: RawMutex, T> {
|
||||||
|
buf: *mut T,
|
||||||
|
phantom: PhantomData<&'a mut T>,
|
||||||
|
state: Mutex<M, RefCell<State>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, M: RawMutex, T> Channel<'a, M, T> {
|
||||||
|
pub fn new(buf: &'a mut [T]) -> Self {
|
||||||
|
let len = buf.len();
|
||||||
|
assert!(len != 0);
|
||||||
|
|
||||||
|
Self {
|
||||||
|
buf: buf.as_mut_ptr(),
|
||||||
|
phantom: PhantomData,
|
||||||
|
state: Mutex::new(RefCell::new(State {
|
||||||
|
len,
|
||||||
|
front: 0,
|
||||||
|
back: 0,
|
||||||
|
full: false,
|
||||||
|
send_waker: WakerRegistration::new(),
|
||||||
|
recv_waker: WakerRegistration::new(),
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn split(&mut self) -> (Sender<'_, M, T>, Receiver<'_, M, T>) {
|
||||||
|
(Sender { channel: self }, Receiver { channel: self })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Sender<'a, M: RawMutex, T> {
|
||||||
|
channel: &'a Channel<'a, M, T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, M: RawMutex, T> Sender<'a, M, T> {
|
||||||
|
pub fn borrow(&mut self) -> Sender<'_, M, T> {
|
||||||
|
Sender { channel: self.channel }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn try_send(&mut self) -> Option<&mut T> {
|
||||||
|
self.channel.state.lock(|s| {
|
||||||
|
let s = &mut *s.borrow_mut();
|
||||||
|
match s.push_index() {
|
||||||
|
Some(i) => Some(unsafe { &mut *self.channel.buf.add(i) }),
|
||||||
|
None => None,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn poll_send(&mut self, cx: &mut Context) -> Poll<&mut T> {
|
||||||
|
self.channel.state.lock(|s| {
|
||||||
|
let s = &mut *s.borrow_mut();
|
||||||
|
match s.push_index() {
|
||||||
|
Some(i) => Poll::Ready(unsafe { &mut *self.channel.buf.add(i) }),
|
||||||
|
None => {
|
||||||
|
s.recv_waker.register(cx.waker());
|
||||||
|
Poll::Pending
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn send(&mut self) -> &mut T {
|
||||||
|
let i = poll_fn(|cx| {
|
||||||
|
self.channel.state.lock(|s| {
|
||||||
|
let s = &mut *s.borrow_mut();
|
||||||
|
match s.push_index() {
|
||||||
|
Some(i) => Poll::Ready(i),
|
||||||
|
None => {
|
||||||
|
s.recv_waker.register(cx.waker());
|
||||||
|
Poll::Pending
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
unsafe { &mut *self.channel.buf.add(i) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn send_done(&mut self) {
|
||||||
|
self.channel.state.lock(|s| s.borrow_mut().push_done())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub struct Receiver<'a, M: RawMutex, T> {
|
||||||
|
channel: &'a Channel<'a, M, T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, M: RawMutex, T> Receiver<'a, M, T> {
|
||||||
|
pub fn borrow(&mut self) -> Receiver<'_, M, T> {
|
||||||
|
Receiver { channel: self.channel }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn try_recv(&mut self) -> Option<&mut T> {
|
||||||
|
self.channel.state.lock(|s| {
|
||||||
|
let s = &mut *s.borrow_mut();
|
||||||
|
match s.pop_index() {
|
||||||
|
Some(i) => Some(unsafe { &mut *self.channel.buf.add(i) }),
|
||||||
|
None => None,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn poll_recv(&mut self, cx: &mut Context) -> Poll<&mut T> {
|
||||||
|
self.channel.state.lock(|s| {
|
||||||
|
let s = &mut *s.borrow_mut();
|
||||||
|
match s.pop_index() {
|
||||||
|
Some(i) => Poll::Ready(unsafe { &mut *self.channel.buf.add(i) }),
|
||||||
|
None => {
|
||||||
|
s.send_waker.register(cx.waker());
|
||||||
|
Poll::Pending
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn recv(&mut self) -> &mut T {
|
||||||
|
let i = poll_fn(|cx| {
|
||||||
|
self.channel.state.lock(|s| {
|
||||||
|
let s = &mut *s.borrow_mut();
|
||||||
|
match s.pop_index() {
|
||||||
|
Some(i) => Poll::Ready(i),
|
||||||
|
None => {
|
||||||
|
s.send_waker.register(cx.waker());
|
||||||
|
Poll::Pending
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
unsafe { &mut *self.channel.buf.add(i) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn recv_done(&mut self) {
|
||||||
|
self.channel.state.lock(|s| s.borrow_mut().pop_done())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct State {
|
||||||
|
len: usize,
|
||||||
|
|
||||||
|
/// Front index. Always 0..=(N-1)
|
||||||
|
front: usize,
|
||||||
|
/// Back index. Always 0..=(N-1).
|
||||||
|
back: usize,
|
||||||
|
|
||||||
|
/// Used to distinguish "empty" and "full" cases when `front == back`.
|
||||||
|
/// May only be `true` if `front == back`, always `false` otherwise.
|
||||||
|
full: bool,
|
||||||
|
|
||||||
|
send_waker: WakerRegistration,
|
||||||
|
recv_waker: WakerRegistration,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl State {
|
||||||
|
fn increment(&self, i: usize) -> usize {
|
||||||
|
if i + 1 == self.len {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
i + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_full(&self) -> bool {
|
||||||
|
self.full
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_empty(&self) -> bool {
|
||||||
|
self.front == self.back && !self.full
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push_index(&mut self) -> Option<usize> {
|
||||||
|
match self.is_full() {
|
||||||
|
true => None,
|
||||||
|
false => Some(self.back),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push_done(&mut self) {
|
||||||
|
assert!(!self.is_full());
|
||||||
|
self.back = self.increment(self.back);
|
||||||
|
if self.back == self.front {
|
||||||
|
self.full = true;
|
||||||
|
}
|
||||||
|
self.send_waker.wake();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pop_index(&mut self) -> Option<usize> {
|
||||||
|
match self.is_empty() {
|
||||||
|
true => None,
|
||||||
|
false => Some(self.front),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pop_done(&mut self) {
|
||||||
|
assert!(!self.is_empty());
|
||||||
|
self.front = self.increment(self.front);
|
||||||
|
self.full = false;
|
||||||
|
self.recv_waker.wake();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,3 +1,18 @@
|
|||||||
|
/// CDC-NCM, aka Ethernet over USB.
|
||||||
|
///
|
||||||
|
/// # Compatibility
|
||||||
|
///
|
||||||
|
/// Windows: NOT supported in Windows 10. Supported in Windows 11.
|
||||||
|
///
|
||||||
|
/// Linux: Well-supported since forever.
|
||||||
|
///
|
||||||
|
/// Android: Support for CDC-NCM is spotty and varies across manufacturers.
|
||||||
|
///
|
||||||
|
/// - On Pixel 4a, it refused to work on Android 11, worked on Android 12.
|
||||||
|
/// - if the host's MAC address has the "locally-administered" bit set (bit 1 of first byte),
|
||||||
|
/// it doesn't work! The "Ethernet tethering" option in settings doesn't get enabled.
|
||||||
|
/// This is due to regex spaghetti: https://android.googlesource.com/platform/frameworks/base/+/refs/tags/android-mainline-12.0.0_r84/core/res/res/values/config.xml#417
|
||||||
|
/// and this nonsense in the linux kernel: https://github.com/torvalds/linux/blob/c00c5e1d157bec0ef0b0b59aa5482eb8dc7e8e49/drivers/net/usb/usbnet.c#L1751-L1757
|
||||||
use core::intrinsics::copy_nonoverlapping;
|
use core::intrinsics::copy_nonoverlapping;
|
||||||
use core::mem::{size_of, MaybeUninit};
|
use core::mem::{size_of, MaybeUninit};
|
||||||
|
|
||||||
@ -6,6 +21,9 @@ use crate::driver::{Driver, Endpoint, EndpointError, EndpointIn, EndpointOut};
|
|||||||
use crate::types::*;
|
use crate::types::*;
|
||||||
use crate::Builder;
|
use crate::Builder;
|
||||||
|
|
||||||
|
#[cfg(feature = "embassy-net")]
|
||||||
|
pub mod embassy_net;
|
||||||
|
|
||||||
/// This should be used as `device_class` when building the `UsbDevice`.
|
/// This should be used as `device_class` when building the `UsbDevice`.
|
||||||
pub const USB_CLASS_CDC: u8 = 0x02;
|
pub const USB_CLASS_CDC: u8 = 0x02;
|
||||||
|
|
@ -16,7 +16,7 @@ embassy-executor = { version = "0.1.0", path = "../../embassy-executor", feature
|
|||||||
embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] }
|
embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] }
|
||||||
embassy-nrf = { version = "0.1.0", path = "../../embassy-nrf", features = ["defmt", "nrf52840", "time-driver-rtc1", "gpiote", "unstable-pac"] }
|
embassy-nrf = { version = "0.1.0", path = "../../embassy-nrf", features = ["defmt", "nrf52840", "time-driver-rtc1", "gpiote", "unstable-pac"] }
|
||||||
embassy-net = { version = "0.1.0", path = "../../embassy-net", features = ["defmt", "tcp", "dhcpv4", "medium-ethernet", "pool-16"], optional = true }
|
embassy-net = { version = "0.1.0", path = "../../embassy-net", features = ["defmt", "tcp", "dhcpv4", "medium-ethernet", "pool-16"], optional = true }
|
||||||
embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"], optional = true }
|
embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt", "embassy-net"], optional = true }
|
||||||
embedded-io = "0.4.0"
|
embedded-io = "0.4.0"
|
||||||
embassy-lora = { version = "0.1.0", path = "../../embassy-lora", features = ["sx126x", "time", "defmt"], optional = true }
|
embassy-lora = { version = "0.1.0", path = "../../embassy-lora", features = ["sx126x", "time", "defmt"], optional = true }
|
||||||
|
|
||||||
|
@ -3,19 +3,16 @@
|
|||||||
#![feature(type_alias_impl_trait)]
|
#![feature(type_alias_impl_trait)]
|
||||||
|
|
||||||
use core::mem;
|
use core::mem;
|
||||||
use core::sync::atomic::{AtomicBool, Ordering};
|
|
||||||
use core::task::Waker;
|
|
||||||
|
|
||||||
use defmt::*;
|
use defmt::*;
|
||||||
use embassy_executor::Spawner;
|
use embassy_executor::Spawner;
|
||||||
use embassy_net::tcp::TcpSocket;
|
use embassy_net::tcp::TcpSocket;
|
||||||
use embassy_net::{PacketBox, PacketBoxExt, PacketBuf, Stack, StackResources};
|
use embassy_net::{Stack, StackResources};
|
||||||
use embassy_nrf::rng::Rng;
|
use embassy_nrf::rng::Rng;
|
||||||
use embassy_nrf::usb::{Driver, PowerUsb};
|
use embassy_nrf::usb::{Driver, PowerUsb};
|
||||||
use embassy_nrf::{interrupt, pac, peripherals};
|
use embassy_nrf::{interrupt, pac, peripherals};
|
||||||
use embassy_sync::blocking_mutex::raw::ThreadModeRawMutex;
|
use embassy_usb::class::cdc_ncm::embassy_net::{Device, Runner, State as NetState};
|
||||||
use embassy_sync::channel::Channel;
|
use embassy_usb::class::cdc_ncm::{CdcNcmClass, State};
|
||||||
use embassy_usb::class::cdc_ncm::{CdcNcmClass, Receiver, Sender, State};
|
|
||||||
use embassy_usb::{Builder, Config, UsbDevice};
|
use embassy_usb::{Builder, Config, UsbDevice};
|
||||||
use embedded_io::asynch::Write;
|
use embedded_io::asynch::Write;
|
||||||
use static_cell::StaticCell;
|
use static_cell::StaticCell;
|
||||||
@ -27,56 +24,25 @@ macro_rules! singleton {
|
|||||||
($val:expr) => {{
|
($val:expr) => {{
|
||||||
type T = impl Sized;
|
type T = impl Sized;
|
||||||
static STATIC_CELL: StaticCell<T> = StaticCell::new();
|
static STATIC_CELL: StaticCell<T> = StaticCell::new();
|
||||||
STATIC_CELL.init_with(move || $val)
|
let (x,) = STATIC_CELL.init(($val,));
|
||||||
|
x
|
||||||
}};
|
}};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const MTU: usize = 1514;
|
||||||
|
|
||||||
#[embassy_executor::task]
|
#[embassy_executor::task]
|
||||||
async fn usb_task(mut device: UsbDevice<'static, MyDriver>) -> ! {
|
async fn usb_task(mut device: UsbDevice<'static, MyDriver>) -> ! {
|
||||||
device.run().await
|
device.run().await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[embassy_executor::task]
|
#[embassy_executor::task]
|
||||||
async fn usb_ncm_rx_task(mut class: Receiver<'static, MyDriver>) {
|
async fn usb_ncm_task(class: Runner<'static, MyDriver, MTU>) -> ! {
|
||||||
loop {
|
class.run().await
|
||||||
warn!("WAITING for connection");
|
|
||||||
LINK_UP.store(false, Ordering::Relaxed);
|
|
||||||
|
|
||||||
class.wait_connection().await.unwrap();
|
|
||||||
|
|
||||||
warn!("Connected");
|
|
||||||
LINK_UP.store(true, Ordering::Relaxed);
|
|
||||||
|
|
||||||
loop {
|
|
||||||
let mut p = unwrap!(PacketBox::new(embassy_net::Packet::new()));
|
|
||||||
let n = match class.read_packet(&mut p[..]).await {
|
|
||||||
Ok(n) => n,
|
|
||||||
Err(e) => {
|
|
||||||
warn!("error reading packet: {:?}", e);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let buf = p.slice(0..n);
|
|
||||||
if RX_CHANNEL.try_send(buf).is_err() {
|
|
||||||
warn!("Failed pushing rx'd packet to channel.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[embassy_executor::task]
|
#[embassy_executor::task]
|
||||||
async fn usb_ncm_tx_task(mut class: Sender<'static, MyDriver>) {
|
async fn net_task(stack: &'static Stack<Device<'static, MTU>>) -> ! {
|
||||||
loop {
|
|
||||||
let pkt = TX_CHANNEL.recv().await;
|
|
||||||
if let Err(e) = class.write_packet(&pkt[..]).await {
|
|
||||||
warn!("Failed to TX packet: {:?}", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[embassy_executor::task]
|
|
||||||
async fn net_task(stack: &'static Stack<Device>) -> ! {
|
|
||||||
stack.run().await
|
stack.run().await
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -108,55 +74,32 @@ async fn main(spawner: Spawner) {
|
|||||||
config.device_sub_class = 0x02;
|
config.device_sub_class = 0x02;
|
||||||
config.device_protocol = 0x01;
|
config.device_protocol = 0x01;
|
||||||
|
|
||||||
struct Resources {
|
|
||||||
device_descriptor: [u8; 256],
|
|
||||||
config_descriptor: [u8; 256],
|
|
||||||
bos_descriptor: [u8; 256],
|
|
||||||
control_buf: [u8; 128],
|
|
||||||
serial_state: State<'static>,
|
|
||||||
}
|
|
||||||
let res: &mut Resources = singleton!(Resources {
|
|
||||||
device_descriptor: [0; 256],
|
|
||||||
config_descriptor: [0; 256],
|
|
||||||
bos_descriptor: [0; 256],
|
|
||||||
control_buf: [0; 128],
|
|
||||||
serial_state: State::new(),
|
|
||||||
});
|
|
||||||
|
|
||||||
// Create embassy-usb DeviceBuilder using the driver and config.
|
// Create embassy-usb DeviceBuilder using the driver and config.
|
||||||
let mut builder = Builder::new(
|
let mut builder = Builder::new(
|
||||||
driver,
|
driver,
|
||||||
config,
|
config,
|
||||||
&mut res.device_descriptor,
|
&mut singleton!([0; 256])[..],
|
||||||
&mut res.config_descriptor,
|
&mut singleton!([0; 256])[..],
|
||||||
&mut res.bos_descriptor,
|
&mut singleton!([0; 256])[..],
|
||||||
&mut res.control_buf,
|
&mut singleton!([0; 128])[..],
|
||||||
None,
|
None,
|
||||||
);
|
);
|
||||||
|
|
||||||
// WARNINGS for Android ethernet tethering:
|
|
||||||
// - On Pixel 4a, it refused to work on Android 11, worked on Android 12.
|
|
||||||
// - if the host's MAC address has the "locally-administered" bit set (bit 1 of first byte),
|
|
||||||
// it doesn't work! The "Ethernet tethering" option in settings doesn't get enabled.
|
|
||||||
// This is due to regex spaghetti: https://android.googlesource.com/platform/frameworks/base/+/refs/tags/android-mainline-12.0.0_r84/core/res/res/values/config.xml#417
|
|
||||||
// and this nonsense in the linux kernel: https://github.com/torvalds/linux/blob/c00c5e1d157bec0ef0b0b59aa5482eb8dc7e8e49/drivers/net/usb/usbnet.c#L1751-L1757
|
|
||||||
|
|
||||||
// Our MAC addr.
|
// Our MAC addr.
|
||||||
let our_mac_addr = [0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC];
|
let our_mac_addr = [0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC];
|
||||||
// Host's MAC addr. This is the MAC the host "thinks" its USB-to-ethernet adapter has.
|
// Host's MAC addr. This is the MAC the host "thinks" its USB-to-ethernet adapter has.
|
||||||
let host_mac_addr = [0x88, 0x88, 0x88, 0x88, 0x88, 0x88];
|
let host_mac_addr = [0x88, 0x88, 0x88, 0x88, 0x88, 0x88];
|
||||||
|
|
||||||
// Create classes on the builder.
|
// Create classes on the builder.
|
||||||
let class = CdcNcmClass::new(&mut builder, &mut res.serial_state, host_mac_addr, 64);
|
let class = CdcNcmClass::new(&mut builder, singleton!(State::new()), host_mac_addr, 64);
|
||||||
|
|
||||||
// Build the builder.
|
// Build the builder.
|
||||||
let usb = builder.build();
|
let usb = builder.build();
|
||||||
|
|
||||||
unwrap!(spawner.spawn(usb_task(usb)));
|
unwrap!(spawner.spawn(usb_task(usb)));
|
||||||
|
|
||||||
let (tx, rx) = class.split();
|
let (runner, device) = class.into_embassy_net_device::<MTU, 4, 4>(singleton!(NetState::new()), our_mac_addr);
|
||||||
unwrap!(spawner.spawn(usb_ncm_rx_task(rx)));
|
unwrap!(spawner.spawn(usb_ncm_task(runner)));
|
||||||
unwrap!(spawner.spawn(usb_ncm_tx_task(tx)));
|
|
||||||
|
|
||||||
let config = embassy_net::ConfigStrategy::Dhcp;
|
let config = embassy_net::ConfigStrategy::Dhcp;
|
||||||
//let config = embassy_net::ConfigStrategy::Static(embassy_net::Config {
|
//let config = embassy_net::ConfigStrategy::Static(embassy_net::Config {
|
||||||
@ -172,7 +115,6 @@ async fn main(spawner: Spawner) {
|
|||||||
let seed = u64::from_le_bytes(seed);
|
let seed = u64::from_le_bytes(seed);
|
||||||
|
|
||||||
// Init network stack
|
// Init network stack
|
||||||
let device = Device { mac_addr: our_mac_addr };
|
|
||||||
let stack = &*singleton!(Stack::new(
|
let stack = &*singleton!(Stack::new(
|
||||||
device,
|
device,
|
||||||
config,
|
config,
|
||||||
@ -225,50 +167,3 @@ async fn main(spawner: Spawner) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static TX_CHANNEL: Channel<ThreadModeRawMutex, PacketBuf, 8> = Channel::new();
|
|
||||||
static RX_CHANNEL: Channel<ThreadModeRawMutex, PacketBuf, 8> = Channel::new();
|
|
||||||
static LINK_UP: AtomicBool = AtomicBool::new(false);
|
|
||||||
|
|
||||||
struct Device {
|
|
||||||
mac_addr: [u8; 6],
|
|
||||||
}
|
|
||||||
|
|
||||||
impl embassy_net::Device for Device {
|
|
||||||
fn register_waker(&mut self, waker: &Waker) {
|
|
||||||
// loopy loopy wakey wakey
|
|
||||||
waker.wake_by_ref()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn link_state(&mut self) -> embassy_net::LinkState {
|
|
||||||
match LINK_UP.load(Ordering::Relaxed) {
|
|
||||||
true => embassy_net::LinkState::Up,
|
|
||||||
false => embassy_net::LinkState::Down,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn capabilities(&self) -> embassy_net::DeviceCapabilities {
|
|
||||||
let mut caps = embassy_net::DeviceCapabilities::default();
|
|
||||||
caps.max_transmission_unit = 1514; // 1500 IP + 14 ethernet header
|
|
||||||
caps.medium = embassy_net::Medium::Ethernet;
|
|
||||||
caps
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_transmit_ready(&mut self) -> bool {
|
|
||||||
true
|
|
||||||
}
|
|
||||||
|
|
||||||
fn transmit(&mut self, pkt: PacketBuf) {
|
|
||||||
if TX_CHANNEL.try_send(pkt).is_err() {
|
|
||||||
warn!("TX failed")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn receive<'a>(&mut self) -> Option<PacketBuf> {
|
|
||||||
RX_CHANNEL.try_recv().ok()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn ethernet_address(&self) -> [u8; 6] {
|
|
||||||
self.mac_addr
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@ -10,7 +10,7 @@ embassy-sync = { version = "0.1.0", path = "../../embassy-sync", features = ["de
|
|||||||
embassy-executor = { version = "0.1.0", path = "../../embassy-executor", features = ["defmt", "integrated-timers"] }
|
embassy-executor = { version = "0.1.0", path = "../../embassy-executor", features = ["defmt", "integrated-timers"] }
|
||||||
embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] }
|
embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime"] }
|
||||||
embassy-rp = { version = "0.1.0", path = "../../embassy-rp", features = ["defmt", "unstable-traits", "nightly", "unstable-pac", "time-driver", "pio", "critical-section-impl"] }
|
embassy-rp = { version = "0.1.0", path = "../../embassy-rp", features = ["defmt", "unstable-traits", "nightly", "unstable-pac", "time-driver", "pio", "critical-section-impl"] }
|
||||||
embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"] }
|
embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt", "embassy-net"] }
|
||||||
embassy-net = { version = "0.1.0", path = "../../embassy-net", features = ["defmt", "nightly", "tcp", "dhcpv4", "medium-ethernet", "pool-16"] }
|
embassy-net = { version = "0.1.0", path = "../../embassy-net", features = ["defmt", "nightly", "tcp", "dhcpv4", "medium-ethernet", "pool-16"] }
|
||||||
embassy-futures = { version = "0.1.0", path = "../../embassy-futures" }
|
embassy-futures = { version = "0.1.0", path = "../../embassy-futures" }
|
||||||
embassy-usb-logger = { version = "0.1.0", path = "../../embassy-usb-logger" }
|
embassy-usb-logger = { version = "0.1.0", path = "../../embassy-usb-logger" }
|
||||||
|
@ -2,18 +2,14 @@
|
|||||||
#![no_main]
|
#![no_main]
|
||||||
#![feature(type_alias_impl_trait)]
|
#![feature(type_alias_impl_trait)]
|
||||||
|
|
||||||
use core::sync::atomic::{AtomicBool, Ordering};
|
|
||||||
use core::task::Waker;
|
|
||||||
|
|
||||||
use defmt::*;
|
use defmt::*;
|
||||||
use embassy_executor::Spawner;
|
use embassy_executor::Spawner;
|
||||||
use embassy_net::tcp::TcpSocket;
|
use embassy_net::tcp::TcpSocket;
|
||||||
use embassy_net::{PacketBox, PacketBoxExt, PacketBuf, Stack, StackResources};
|
use embassy_net::{Stack, StackResources};
|
||||||
use embassy_rp::usb::Driver;
|
use embassy_rp::usb::Driver;
|
||||||
use embassy_rp::{interrupt, peripherals};
|
use embassy_rp::{interrupt, peripherals};
|
||||||
use embassy_sync::blocking_mutex::raw::ThreadModeRawMutex;
|
use embassy_usb::class::cdc_ncm::embassy_net::{Device, Runner, State as NetState};
|
||||||
use embassy_sync::channel::Channel;
|
use embassy_usb::class::cdc_ncm::{CdcNcmClass, State};
|
||||||
use embassy_usb::class::cdc_ncm::{CdcNcmClass, Receiver, Sender, State};
|
|
||||||
use embassy_usb::{Builder, Config, UsbDevice};
|
use embassy_usb::{Builder, Config, UsbDevice};
|
||||||
use embedded_io::asynch::Write;
|
use embedded_io::asynch::Write;
|
||||||
use static_cell::StaticCell;
|
use static_cell::StaticCell;
|
||||||
@ -25,56 +21,25 @@ macro_rules! singleton {
|
|||||||
($val:expr) => {{
|
($val:expr) => {{
|
||||||
type T = impl Sized;
|
type T = impl Sized;
|
||||||
static STATIC_CELL: StaticCell<T> = StaticCell::new();
|
static STATIC_CELL: StaticCell<T> = StaticCell::new();
|
||||||
STATIC_CELL.init_with(move || $val)
|
let (x,) = STATIC_CELL.init(($val,));
|
||||||
|
x
|
||||||
}};
|
}};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const MTU: usize = 1514;
|
||||||
|
|
||||||
#[embassy_executor::task]
|
#[embassy_executor::task]
|
||||||
async fn usb_task(mut device: UsbDevice<'static, MyDriver>) -> ! {
|
async fn usb_task(mut device: UsbDevice<'static, MyDriver>) -> ! {
|
||||||
device.run().await
|
device.run().await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[embassy_executor::task]
|
#[embassy_executor::task]
|
||||||
async fn usb_ncm_rx_task(mut class: Receiver<'static, MyDriver>) {
|
async fn usb_ncm_task(class: Runner<'static, MyDriver, MTU>) -> ! {
|
||||||
loop {
|
class.run().await
|
||||||
warn!("WAITING for connection");
|
|
||||||
LINK_UP.store(false, Ordering::Relaxed);
|
|
||||||
|
|
||||||
class.wait_connection().await.unwrap();
|
|
||||||
|
|
||||||
warn!("Connected");
|
|
||||||
LINK_UP.store(true, Ordering::Relaxed);
|
|
||||||
|
|
||||||
loop {
|
|
||||||
let mut p = unwrap!(PacketBox::new(embassy_net::Packet::new()));
|
|
||||||
let n = match class.read_packet(&mut p[..]).await {
|
|
||||||
Ok(n) => n,
|
|
||||||
Err(e) => {
|
|
||||||
warn!("error reading packet: {:?}", e);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let buf = p.slice(0..n);
|
|
||||||
if RX_CHANNEL.try_send(buf).is_err() {
|
|
||||||
warn!("Failed pushing rx'd packet to channel.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[embassy_executor::task]
|
#[embassy_executor::task]
|
||||||
async fn usb_ncm_tx_task(mut class: Sender<'static, MyDriver>) {
|
async fn net_task(stack: &'static Stack<Device<'static, MTU>>) -> ! {
|
||||||
loop {
|
|
||||||
let pkt = TX_CHANNEL.recv().await;
|
|
||||||
if let Err(e) = class.write_packet(&pkt[..]).await {
|
|
||||||
warn!("Failed to TX packet: {:?}", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[embassy_executor::task]
|
|
||||||
async fn net_task(stack: &'static Stack<Device>) -> ! {
|
|
||||||
stack.run().await
|
stack.run().await
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -100,55 +65,32 @@ async fn main(spawner: Spawner) {
|
|||||||
config.device_sub_class = 0x02;
|
config.device_sub_class = 0x02;
|
||||||
config.device_protocol = 0x01;
|
config.device_protocol = 0x01;
|
||||||
|
|
||||||
struct Resources {
|
|
||||||
device_descriptor: [u8; 256],
|
|
||||||
config_descriptor: [u8; 256],
|
|
||||||
bos_descriptor: [u8; 256],
|
|
||||||
control_buf: [u8; 128],
|
|
||||||
serial_state: State<'static>,
|
|
||||||
}
|
|
||||||
let res: &mut Resources = singleton!(Resources {
|
|
||||||
device_descriptor: [0; 256],
|
|
||||||
config_descriptor: [0; 256],
|
|
||||||
bos_descriptor: [0; 256],
|
|
||||||
control_buf: [0; 128],
|
|
||||||
serial_state: State::new(),
|
|
||||||
});
|
|
||||||
|
|
||||||
// Create embassy-usb DeviceBuilder using the driver and config.
|
// Create embassy-usb DeviceBuilder using the driver and config.
|
||||||
let mut builder = Builder::new(
|
let mut builder = Builder::new(
|
||||||
driver,
|
driver,
|
||||||
config,
|
config,
|
||||||
&mut res.device_descriptor,
|
&mut singleton!([0; 256])[..],
|
||||||
&mut res.config_descriptor,
|
&mut singleton!([0; 256])[..],
|
||||||
&mut res.bos_descriptor,
|
&mut singleton!([0; 256])[..],
|
||||||
&mut res.control_buf,
|
&mut singleton!([0; 128])[..],
|
||||||
None,
|
None,
|
||||||
);
|
);
|
||||||
|
|
||||||
// WARNINGS for Android ethernet tethering:
|
|
||||||
// - On Pixel 4a, it refused to work on Android 11, worked on Android 12.
|
|
||||||
// - if the host's MAC address has the "locally-administered" bit set (bit 1 of first byte),
|
|
||||||
// it doesn't work! The "Ethernet tethering" option in settings doesn't get enabled.
|
|
||||||
// This is due to regex spaghetti: https://android.googlesource.com/platform/frameworks/base/+/refs/tags/android-mainline-12.0.0_r84/core/res/res/values/config.xml#417
|
|
||||||
// and this nonsense in the linux kernel: https://github.com/torvalds/linux/blob/c00c5e1d157bec0ef0b0b59aa5482eb8dc7e8e49/drivers/net/usb/usbnet.c#L1751-L1757
|
|
||||||
|
|
||||||
// Our MAC addr.
|
// Our MAC addr.
|
||||||
let our_mac_addr = [0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC];
|
let our_mac_addr = [0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC];
|
||||||
// Host's MAC addr. This is the MAC the host "thinks" its USB-to-ethernet adapter has.
|
// Host's MAC addr. This is the MAC the host "thinks" its USB-to-ethernet adapter has.
|
||||||
let host_mac_addr = [0x88, 0x88, 0x88, 0x88, 0x88, 0x88];
|
let host_mac_addr = [0x88, 0x88, 0x88, 0x88, 0x88, 0x88];
|
||||||
|
|
||||||
// Create classes on the builder.
|
// Create classes on the builder.
|
||||||
let class = CdcNcmClass::new(&mut builder, &mut res.serial_state, host_mac_addr, 64);
|
let class = CdcNcmClass::new(&mut builder, singleton!(State::new()), host_mac_addr, 64);
|
||||||
|
|
||||||
// Build the builder.
|
// Build the builder.
|
||||||
let usb = builder.build();
|
let usb = builder.build();
|
||||||
|
|
||||||
unwrap!(spawner.spawn(usb_task(usb)));
|
unwrap!(spawner.spawn(usb_task(usb)));
|
||||||
|
|
||||||
let (tx, rx) = class.split();
|
let (runner, device) = class.into_embassy_net_device::<MTU, 4, 4>(singleton!(NetState::new()), our_mac_addr);
|
||||||
unwrap!(spawner.spawn(usb_ncm_rx_task(rx)));
|
unwrap!(spawner.spawn(usb_ncm_task(runner)));
|
||||||
unwrap!(spawner.spawn(usb_ncm_tx_task(tx)));
|
|
||||||
|
|
||||||
let config = embassy_net::ConfigStrategy::Dhcp;
|
let config = embassy_net::ConfigStrategy::Dhcp;
|
||||||
//let config = embassy_net::ConfigStrategy::Static(embassy_net::Config {
|
//let config = embassy_net::ConfigStrategy::Static(embassy_net::Config {
|
||||||
@ -161,7 +103,6 @@ async fn main(spawner: Spawner) {
|
|||||||
let seed = 1234; // guaranteed random, chosen by a fair dice roll
|
let seed = 1234; // guaranteed random, chosen by a fair dice roll
|
||||||
|
|
||||||
// Init network stack
|
// Init network stack
|
||||||
let device = Device { mac_addr: our_mac_addr };
|
|
||||||
let stack = &*singleton!(Stack::new(
|
let stack = &*singleton!(Stack::new(
|
||||||
device,
|
device,
|
||||||
config,
|
config,
|
||||||
@ -214,50 +155,3 @@ async fn main(spawner: Spawner) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static TX_CHANNEL: Channel<ThreadModeRawMutex, PacketBuf, 8> = Channel::new();
|
|
||||||
static RX_CHANNEL: Channel<ThreadModeRawMutex, PacketBuf, 8> = Channel::new();
|
|
||||||
static LINK_UP: AtomicBool = AtomicBool::new(false);
|
|
||||||
|
|
||||||
struct Device {
|
|
||||||
mac_addr: [u8; 6],
|
|
||||||
}
|
|
||||||
|
|
||||||
impl embassy_net::Device for Device {
|
|
||||||
fn register_waker(&mut self, waker: &Waker) {
|
|
||||||
// loopy loopy wakey wakey
|
|
||||||
waker.wake_by_ref()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn link_state(&mut self) -> embassy_net::LinkState {
|
|
||||||
match LINK_UP.load(Ordering::Relaxed) {
|
|
||||||
true => embassy_net::LinkState::Up,
|
|
||||||
false => embassy_net::LinkState::Down,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn capabilities(&self) -> embassy_net::DeviceCapabilities {
|
|
||||||
let mut caps = embassy_net::DeviceCapabilities::default();
|
|
||||||
caps.max_transmission_unit = 1514; // 1500 IP + 14 ethernet header
|
|
||||||
caps.medium = embassy_net::Medium::Ethernet;
|
|
||||||
caps
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_transmit_ready(&mut self) -> bool {
|
|
||||||
true
|
|
||||||
}
|
|
||||||
|
|
||||||
fn transmit(&mut self, pkt: PacketBuf) {
|
|
||||||
if TX_CHANNEL.try_send(pkt).is_err() {
|
|
||||||
warn!("TX failed")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn receive<'a>(&mut self) -> Option<PacketBuf> {
|
|
||||||
RX_CHANNEL.try_recv().ok()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn ethernet_address(&self) -> [u8; 6] {
|
|
||||||
self.mac_addr
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@ -11,7 +11,7 @@ embassy-sync = { version = "0.1.0", path = "../../embassy-sync", features = ["de
|
|||||||
embassy-executor = { version = "0.1.0", path = "../../embassy-executor", features = ["defmt", "integrated-timers"] }
|
embassy-executor = { version = "0.1.0", path = "../../embassy-executor", features = ["defmt", "integrated-timers"] }
|
||||||
embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] }
|
embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] }
|
||||||
embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["nightly", "defmt", "unstable-pac", "stm32l552ze", "time-driver-any", "exti", "unstable-traits", "memory-x"] }
|
embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["nightly", "defmt", "unstable-pac", "stm32l552ze", "time-driver-any", "exti", "unstable-traits", "memory-x"] }
|
||||||
embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"] }
|
embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt", "embassy-net"] }
|
||||||
embassy-net = { version = "0.1.0", path = "../../embassy-net", features = ["defmt", "nightly", "tcp", "dhcpv4", "medium-ethernet", "pool-16"] }
|
embassy-net = { version = "0.1.0", path = "../../embassy-net", features = ["defmt", "nightly", "tcp", "dhcpv4", "medium-ethernet", "pool-16"] }
|
||||||
embassy-futures = { version = "0.1.0", path = "../../embassy-futures" }
|
embassy-futures = { version = "0.1.0", path = "../../embassy-futures" }
|
||||||
usbd-hid = "0.6.0"
|
usbd-hid = "0.6.0"
|
||||||
|
@ -2,20 +2,16 @@
|
|||||||
#![no_main]
|
#![no_main]
|
||||||
#![feature(type_alias_impl_trait)]
|
#![feature(type_alias_impl_trait)]
|
||||||
|
|
||||||
use core::sync::atomic::{AtomicBool, Ordering};
|
|
||||||
use core::task::Waker;
|
|
||||||
|
|
||||||
use defmt::*;
|
use defmt::*;
|
||||||
use embassy_executor::Spawner;
|
use embassy_executor::Spawner;
|
||||||
use embassy_net::tcp::TcpSocket;
|
use embassy_net::tcp::TcpSocket;
|
||||||
use embassy_net::{PacketBox, PacketBoxExt, PacketBuf, Stack, StackResources};
|
use embassy_net::{Stack, StackResources};
|
||||||
use embassy_stm32::rcc::*;
|
use embassy_stm32::rcc::*;
|
||||||
use embassy_stm32::rng::Rng;
|
use embassy_stm32::rng::Rng;
|
||||||
use embassy_stm32::usb::Driver;
|
use embassy_stm32::usb::Driver;
|
||||||
use embassy_stm32::{interrupt, Config};
|
use embassy_stm32::{interrupt, Config};
|
||||||
use embassy_sync::blocking_mutex::raw::ThreadModeRawMutex;
|
use embassy_usb::class::cdc_ncm::embassy_net::{Device, Runner, State as NetState};
|
||||||
use embassy_sync::channel::Channel;
|
use embassy_usb::class::cdc_ncm::{CdcNcmClass, State};
|
||||||
use embassy_usb::class::cdc_ncm::{CdcNcmClass, Receiver, Sender, State};
|
|
||||||
use embassy_usb::{Builder, UsbDevice};
|
use embassy_usb::{Builder, UsbDevice};
|
||||||
use embedded_io::asynch::Write;
|
use embedded_io::asynch::Write;
|
||||||
use rand_core::RngCore;
|
use rand_core::RngCore;
|
||||||
@ -28,56 +24,25 @@ macro_rules! singleton {
|
|||||||
($val:expr) => {{
|
($val:expr) => {{
|
||||||
type T = impl Sized;
|
type T = impl Sized;
|
||||||
static STATIC_CELL: StaticCell<T> = StaticCell::new();
|
static STATIC_CELL: StaticCell<T> = StaticCell::new();
|
||||||
STATIC_CELL.init_with(move || $val)
|
let (x,) = STATIC_CELL.init(($val,));
|
||||||
|
x
|
||||||
}};
|
}};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const MTU: usize = 1514;
|
||||||
|
|
||||||
#[embassy_executor::task]
|
#[embassy_executor::task]
|
||||||
async fn usb_task(mut device: UsbDevice<'static, MyDriver>) -> ! {
|
async fn usb_task(mut device: UsbDevice<'static, MyDriver>) -> ! {
|
||||||
device.run().await
|
device.run().await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[embassy_executor::task]
|
#[embassy_executor::task]
|
||||||
async fn usb_ncm_rx_task(mut class: Receiver<'static, MyDriver>) {
|
async fn usb_ncm_task(class: Runner<'static, MyDriver, MTU>) -> ! {
|
||||||
loop {
|
class.run().await
|
||||||
warn!("WAITING for connection");
|
|
||||||
LINK_UP.store(false, Ordering::Relaxed);
|
|
||||||
|
|
||||||
class.wait_connection().await.unwrap();
|
|
||||||
|
|
||||||
warn!("Connected");
|
|
||||||
LINK_UP.store(true, Ordering::Relaxed);
|
|
||||||
|
|
||||||
loop {
|
|
||||||
let mut p = unwrap!(PacketBox::new(embassy_net::Packet::new()));
|
|
||||||
let n = match class.read_packet(&mut p[..]).await {
|
|
||||||
Ok(n) => n,
|
|
||||||
Err(e) => {
|
|
||||||
warn!("error reading packet: {:?}", e);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let buf = p.slice(0..n);
|
|
||||||
if RX_CHANNEL.try_send(buf).is_err() {
|
|
||||||
warn!("Failed pushing rx'd packet to channel.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[embassy_executor::task]
|
#[embassy_executor::task]
|
||||||
async fn usb_ncm_tx_task(mut class: Sender<'static, MyDriver>) {
|
async fn net_task(stack: &'static Stack<Device<'static, MTU>>) -> ! {
|
||||||
loop {
|
|
||||||
let pkt = TX_CHANNEL.recv().await;
|
|
||||||
if let Err(e) = class.write_packet(&pkt[..]).await {
|
|
||||||
warn!("Failed to TX packet: {:?}", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[embassy_executor::task]
|
|
||||||
async fn net_task(stack: &'static Stack<Device>) -> ! {
|
|
||||||
stack.run().await
|
stack.run().await
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -106,55 +71,32 @@ async fn main(spawner: Spawner) {
|
|||||||
config.device_sub_class = 0x02;
|
config.device_sub_class = 0x02;
|
||||||
config.device_protocol = 0x01;
|
config.device_protocol = 0x01;
|
||||||
|
|
||||||
struct Resources {
|
|
||||||
device_descriptor: [u8; 256],
|
|
||||||
config_descriptor: [u8; 256],
|
|
||||||
bos_descriptor: [u8; 256],
|
|
||||||
control_buf: [u8; 128],
|
|
||||||
serial_state: State<'static>,
|
|
||||||
}
|
|
||||||
let res: &mut Resources = singleton!(Resources {
|
|
||||||
device_descriptor: [0; 256],
|
|
||||||
config_descriptor: [0; 256],
|
|
||||||
bos_descriptor: [0; 256],
|
|
||||||
control_buf: [0; 128],
|
|
||||||
serial_state: State::new(),
|
|
||||||
});
|
|
||||||
|
|
||||||
// Create embassy-usb DeviceBuilder using the driver and config.
|
// Create embassy-usb DeviceBuilder using the driver and config.
|
||||||
let mut builder = Builder::new(
|
let mut builder = Builder::new(
|
||||||
driver,
|
driver,
|
||||||
config,
|
config,
|
||||||
&mut res.device_descriptor,
|
&mut singleton!([0; 256])[..],
|
||||||
&mut res.config_descriptor,
|
&mut singleton!([0; 256])[..],
|
||||||
&mut res.bos_descriptor,
|
&mut singleton!([0; 256])[..],
|
||||||
&mut res.control_buf,
|
&mut singleton!([0; 128])[..],
|
||||||
None,
|
None,
|
||||||
);
|
);
|
||||||
|
|
||||||
// WARNINGS for Android ethernet tethering:
|
|
||||||
// - On Pixel 4a, it refused to work on Android 11, worked on Android 12.
|
|
||||||
// - if the host's MAC address has the "locally-administered" bit set (bit 1 of first byte),
|
|
||||||
// it doesn't work! The "Ethernet tethering" option in settings doesn't get enabled.
|
|
||||||
// This is due to regex spaghetti: https://android.googlesource.com/platform/frameworks/base/+/refs/tags/android-mainline-12.0.0_r84/core/res/res/values/config.xml#417
|
|
||||||
// and this nonsense in the linux kernel: https://github.com/torvalds/linux/blob/c00c5e1d157bec0ef0b0b59aa5482eb8dc7e8e49/drivers/net/usb/usbnet.c#L1751-L1757
|
|
||||||
|
|
||||||
// Our MAC addr.
|
// Our MAC addr.
|
||||||
let our_mac_addr = [0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC];
|
let our_mac_addr = [0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC];
|
||||||
// Host's MAC addr. This is the MAC the host "thinks" its USB-to-ethernet adapter has.
|
// Host's MAC addr. This is the MAC the host "thinks" its USB-to-ethernet adapter has.
|
||||||
let host_mac_addr = [0x88, 0x88, 0x88, 0x88, 0x88, 0x88];
|
let host_mac_addr = [0x88, 0x88, 0x88, 0x88, 0x88, 0x88];
|
||||||
|
|
||||||
// Create classes on the builder.
|
// Create classes on the builder.
|
||||||
let class = CdcNcmClass::new(&mut builder, &mut res.serial_state, host_mac_addr, 64);
|
let class = CdcNcmClass::new(&mut builder, singleton!(State::new()), host_mac_addr, 64);
|
||||||
|
|
||||||
// Build the builder.
|
// Build the builder.
|
||||||
let usb = builder.build();
|
let usb = builder.build();
|
||||||
|
|
||||||
unwrap!(spawner.spawn(usb_task(usb)));
|
unwrap!(spawner.spawn(usb_task(usb)));
|
||||||
|
|
||||||
let (tx, rx) = class.split();
|
let (runner, device) = class.into_embassy_net_device::<MTU, 4, 4>(singleton!(NetState::new()), our_mac_addr);
|
||||||
unwrap!(spawner.spawn(usb_ncm_rx_task(rx)));
|
unwrap!(spawner.spawn(usb_ncm_task(runner)));
|
||||||
unwrap!(spawner.spawn(usb_ncm_tx_task(tx)));
|
|
||||||
|
|
||||||
let config = embassy_net::ConfigStrategy::Dhcp;
|
let config = embassy_net::ConfigStrategy::Dhcp;
|
||||||
//let config = embassy_net::ConfigStrategy::Static(embassy_net::Config {
|
//let config = embassy_net::ConfigStrategy::Static(embassy_net::Config {
|
||||||
@ -168,7 +110,6 @@ async fn main(spawner: Spawner) {
|
|||||||
let seed = rng.next_u64();
|
let seed = rng.next_u64();
|
||||||
|
|
||||||
// Init network stack
|
// Init network stack
|
||||||
let device = Device { mac_addr: our_mac_addr };
|
|
||||||
let stack = &*singleton!(Stack::new(
|
let stack = &*singleton!(Stack::new(
|
||||||
device,
|
device,
|
||||||
config,
|
config,
|
||||||
@ -221,50 +162,3 @@ async fn main(spawner: Spawner) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static TX_CHANNEL: Channel<ThreadModeRawMutex, PacketBuf, 8> = Channel::new();
|
|
||||||
static RX_CHANNEL: Channel<ThreadModeRawMutex, PacketBuf, 8> = Channel::new();
|
|
||||||
static LINK_UP: AtomicBool = AtomicBool::new(false);
|
|
||||||
|
|
||||||
struct Device {
|
|
||||||
mac_addr: [u8; 6],
|
|
||||||
}
|
|
||||||
|
|
||||||
impl embassy_net::Device for Device {
|
|
||||||
fn register_waker(&mut self, waker: &Waker) {
|
|
||||||
// loopy loopy wakey wakey
|
|
||||||
waker.wake_by_ref()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn link_state(&mut self) -> embassy_net::LinkState {
|
|
||||||
match LINK_UP.load(Ordering::Relaxed) {
|
|
||||||
true => embassy_net::LinkState::Up,
|
|
||||||
false => embassy_net::LinkState::Down,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn capabilities(&self) -> embassy_net::DeviceCapabilities {
|
|
||||||
let mut caps = embassy_net::DeviceCapabilities::default();
|
|
||||||
caps.max_transmission_unit = 1514; // 1500 IP + 14 ethernet header
|
|
||||||
caps.medium = embassy_net::Medium::Ethernet;
|
|
||||||
caps
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_transmit_ready(&mut self) -> bool {
|
|
||||||
true
|
|
||||||
}
|
|
||||||
|
|
||||||
fn transmit(&mut self, pkt: PacketBuf) {
|
|
||||||
if TX_CHANNEL.try_send(pkt).is_err() {
|
|
||||||
warn!("TX failed")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn receive<'a>(&mut self) -> Option<PacketBuf> {
|
|
||||||
RX_CHANNEL.try_recv().ok()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn ethernet_address(&self) -> [u8; 6] {
|
|
||||||
self.mac_addr
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
Loading…
Reference in New Issue
Block a user