WIP embassy-net v2

This commit is contained in:
Dario Nieuwenhuis
2022-05-23 03:50:43 +02:00
parent 36a1f20364
commit a5aea995a8
17 changed files with 660 additions and 734 deletions

View File

@ -12,8 +12,9 @@ use embassy::channel::Channel;
use embassy::executor::Spawner;
use embassy::util::Forever;
use embassy_net::tcp::TcpSocket;
use embassy_net::{PacketBox, PacketBoxExt, PacketBuf};
use embassy_net::{PacketBox, PacketBoxExt, PacketBuf, Stack, StackResources};
use embassy_nrf::pac;
use embassy_nrf::rng::Rng;
use embassy_nrf::usb::Driver;
use embassy_nrf::Peripherals;
use embassy_nrf::{interrupt, peripherals};
@ -27,6 +28,14 @@ use panic_probe as _;
type MyDriver = Driver<'static, peripherals::USBD>;
macro_rules! forever {
($val:expr) => {{
type T = impl Sized;
static FOREVER: Forever<T> = Forever::new();
FOREVER.put_with(move || $val)
}};
}
#[embassy::task]
async fn usb_task(mut device: UsbDevice<'static, MyDriver>) -> ! {
device.run().await
@ -72,8 +81,8 @@ async fn usb_ncm_tx_task(mut class: Sender<'static, MyDriver>) {
}
#[embassy::task]
async fn net_task() -> ! {
embassy_net::run().await
async fn net_task(stack: &'static Stack<Device>) -> ! {
stack.run().await
}
#[embassy::main]
@ -114,8 +123,7 @@ async fn main(spawner: Spawner, p: Peripherals) {
control_buf: [u8; 128],
serial_state: State<'static>,
}
static RESOURCES: Forever<Resources> = Forever::new();
let res = RESOURCES.put(Resources {
let res: &mut Resources = forever!(Resources {
device_descriptor: [0; 256],
config_descriptor: [0; 256],
bos_descriptor: [0; 256],
@ -158,28 +166,31 @@ async fn main(spawner: Spawner, p: Peripherals) {
unwrap!(spawner.spawn(usb_ncm_rx_task(rx)));
unwrap!(spawner.spawn(usb_ncm_tx_task(tx)));
// Init embassy-net
struct NetResources {
resources: embassy_net::StackResources<1, 2, 8>,
configurator: embassy_net::DhcpConfigurator,
//configurator: StaticConfigurator,
device: Device,
}
static NET_RESOURCES: Forever<NetResources> = Forever::new();
let res = NET_RESOURCES.put(NetResources {
resources: embassy_net::StackResources::new(),
configurator: embassy_net::DhcpConfigurator::new(),
//configurator: embassy_net::StaticConfigurator::new(embassy_net::Config {
// address: Ipv4Cidr::new(Ipv4Address::new(10, 42, 0, 1), 24),
// dns_servers: Default::default(),
// gateway: None,
//}),
device: Device {
mac_addr: our_mac_addr,
},
});
embassy_net::init(&mut res.device, &mut res.configurator, &mut res.resources);
unwrap!(spawner.spawn(net_task()));
let config = embassy_net::ConfigStrategy::Dhcp;
//let config = embassy_net::ConfigStrategy::Static(embassy_net::Config {
// address: Ipv4Cidr::new(Ipv4Address::new(10, 42, 0, 61), 24),
// dns_servers: Vec::new(),
// gateway: Some(Ipv4Address::new(10, 42, 0, 1)),
//});
// Generate random seed
let mut rng = Rng::new(p.RNG, interrupt::take!(RNG));
let mut seed = [0; 8];
rng.blocking_fill_bytes(&mut seed);
let seed = u64::from_le_bytes(seed);
// Init network stack
let device = Device {
mac_addr: our_mac_addr,
};
let stack = &*forever!(Stack::new(
device,
config,
forever!(StackResources::<1, 2, 8>::new()),
seed
));
unwrap!(spawner.spawn(net_task(stack)));
// And now we can use it!
@ -188,7 +199,7 @@ async fn main(spawner: Spawner, p: Peripherals) {
let mut buf = [0; 4096];
loop {
let mut socket = TcpSocket::new(&mut rx_buffer, &mut tx_buffer);
let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer);
socket.set_timeout(Some(embassy_net::SmolDuration::from_secs(10)));
info!("Listening on TCP:1234...");
@ -246,7 +257,7 @@ impl embassy_net::Device for Device {
}
}
fn capabilities(&mut self) -> embassy_net::DeviceCapabilities {
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;
@ -271,9 +282,3 @@ impl embassy_net::Device for Device {
self.mac_addr
}
}
#[no_mangle]
fn _embassy_rand(buf: &mut [u8]) {
// TODO
buf.fill(0x42)
}

View File

@ -4,23 +4,24 @@ use clap::Parser;
use embassy::executor::{Executor, Spawner};
use embassy::util::Forever;
use embassy_net::tcp::TcpSocket;
use embassy_net::{
Config, Configurator, DhcpConfigurator, Ipv4Address, Ipv4Cidr, StackResources,
StaticConfigurator,
};
use embassy_net::{ConfigStrategy, Ipv4Address, Ipv4Cidr, Stack, StackResources};
use embedded_io::asynch::Write;
use heapless::Vec;
use log::*;
use rand_core::{OsRng, RngCore};
#[path = "../tuntap.rs"]
mod tuntap;
use crate::tuntap::TunTapDevice;
static DEVICE: Forever<TunTapDevice> = Forever::new();
static CONFIG_STATIC: Forever<StaticConfigurator> = Forever::new();
static CONFIG_DYNAMIC: Forever<DhcpConfigurator> = Forever::new();
static NET_RESOURCES: Forever<StackResources<1, 2, 8>> = Forever::new();
macro_rules! forever {
($val:expr) => {{
type T = impl Sized;
static FOREVER: Forever<T> = Forever::new();
FOREVER.put_with(move || $val)
}};
}
#[derive(Parser)]
#[clap(version = "1.0")]
@ -34,8 +35,8 @@ struct Opts {
}
#[embassy::task]
async fn net_task() {
embassy_net::run().await
async fn net_task(stack: &'static Stack<TunTapDevice>) -> ! {
stack.run().await
}
#[embassy::task]
@ -46,28 +47,36 @@ async fn main_task(spawner: Spawner) {
let device = TunTapDevice::new(&opts.tap).unwrap();
// Choose between dhcp or static ip
let config: &'static mut dyn Configurator = if opts.static_ip {
CONFIG_STATIC.put(StaticConfigurator::new(Config {
let config = if opts.static_ip {
ConfigStrategy::Static(embassy_net::Config {
address: Ipv4Cidr::new(Ipv4Address::new(192, 168, 69, 2), 24),
dns_servers: Vec::new(),
gateway: Some(Ipv4Address::new(192, 168, 69, 1)),
}))
})
} else {
CONFIG_DYNAMIC.put(DhcpConfigurator::new())
ConfigStrategy::Dhcp
};
let net_resources = StackResources::new();
// Generate random seed
let mut seed = [0; 8];
OsRng.fill_bytes(&mut seed);
let seed = u64::from_le_bytes(seed);
// Init network stack
embassy_net::init(DEVICE.put(device), config, NET_RESOURCES.put(net_resources));
let stack = &*forever!(Stack::new(
device,
config,
forever!(StackResources::<1, 2, 8>::new()),
seed
));
// Launch network task
spawner.spawn(net_task()).unwrap();
spawner.spawn(net_task(stack)).unwrap();
// Then we can use it!
let mut rx_buffer = [0; 4096];
let mut tx_buffer = [0; 4096];
let mut socket = TcpSocket::new(&mut rx_buffer, &mut tx_buffer);
let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer);
socket.set_timeout(Some(embassy_net::SmolDuration::from_secs(10)));
@ -88,12 +97,6 @@ async fn main_task(spawner: Spawner) {
}
}
#[no_mangle]
fn _embassy_rand(buf: &mut [u8]) {
use rand_core::{OsRng, RngCore};
OsRng.fill_bytes(buf);
}
static EXECUTOR: Forever<Executor> = Forever::new();
fn main() {

View File

@ -209,7 +209,7 @@ impl Device for TunTapDevice {
}
}
fn capabilities(&mut self) -> DeviceCapabilities {
fn capabilities(&self) -> DeviceCapabilities {
let mut caps = DeviceCapabilities::default();
caps.max_transmission_unit = self.device.get_ref().mtu;
caps

View File

@ -8,7 +8,7 @@ resolver = "2"
[dependencies]
embassy = { version = "0.1.0", path = "../../embassy", features = ["defmt", "defmt-timestamp-uptime"] }
embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["nightly", "defmt", "net", "stm32f767zi", "unstable-pac", "time-driver-any", "exti"] }
embassy-net = { path = "../../embassy-net", features = ["defmt", "tcp", "medium-ethernet", "pool-16"] }
embassy-net = { path = "../../embassy-net", features = ["defmt", "tcp", "dhcpv4", "medium-ethernet", "pool-16"] }
embedded-io = { version = "0.3.0", features = ["async"] }
defmt = "0.3"
@ -24,8 +24,3 @@ nb = "1.0.0"
rand_core = "0.6.3"
critical-section = "0.2.3"
embedded-storage = "0.3.0"
[dependencies.smoltcp]
version = "0.8.0"
default-features = false
features = ["defmt"]

View File

@ -2,130 +2,123 @@
#![no_main]
#![feature(type_alias_impl_trait)]
use cortex_m_rt::entry;
use defmt::*;
use embassy::executor::{Executor, Spawner};
use embassy::executor::Spawner;
use embassy::time::{Duration, Timer};
use embassy::util::Forever;
use embassy_net::tcp::TcpSocket;
use embassy_net::{Config as NetConfig, Ipv4Address, Ipv4Cidr, StackResources, StaticConfigurator};
use embassy_net::{Ipv4Address, Stack, StackResources};
use embassy_stm32::eth::generic_smi::GenericSMI;
use embassy_stm32::eth::{Ethernet, State};
use embassy_stm32::interrupt;
use embassy_stm32::peripherals::ETH;
use embassy_stm32::peripherals::RNG;
use embassy_stm32::rng::Rng;
use embassy_stm32::time::U32Ext;
use embassy_stm32::Config;
use embassy_stm32::{interrupt, Peripherals};
use embedded_io::asynch::Write;
use heapless::Vec;
use defmt_rtt as _; // global logger
use panic_probe as _;
use rand_core::RngCore;
macro_rules! forever {
($val:expr) => {{
type T = impl Sized;
static FOREVER: Forever<T> = Forever::new();
FOREVER.put_with(move || $val)
}};
}
type Device = Ethernet<'static, ETH, GenericSMI, 4, 4>;
#[embassy::task]
async fn main_task(
device: &'static mut Ethernet<'static, ETH, GenericSMI, 4, 4>,
config: &'static mut StaticConfigurator,
spawner: Spawner,
) {
let net_resources = NET_RESOURCES.put(StackResources::new());
// Init network stack
embassy_net::init(device, config, net_resources);
// Launch network task
unwrap!(spawner.spawn(net_task()));
info!("Network task initialized");
// Then we can use it!
let mut rx_buffer = [0; 1024];
let mut tx_buffer = [0; 1024];
let mut socket = TcpSocket::new(&mut rx_buffer, &mut tx_buffer);
socket.set_timeout(Some(embassy_net::SmolDuration::from_secs(10)));
let remote_endpoint = (Ipv4Address::new(192, 168, 0, 10), 8000);
let r = socket.connect(remote_endpoint).await;
if let Err(e) = r {
info!("connect error: {:?}", e);
return;
}
info!("connected!");
loop {
let r = socket.write_all(b"Hello\n").await;
if let Err(e) = r {
info!("write error: {:?}", e);
return;
}
Timer::after(Duration::from_secs(1)).await;
}
async fn net_task(stack: &'static Stack<Device>) -> ! {
stack.run().await
}
#[embassy::task]
async fn net_task() {
embassy_net::run().await
}
#[no_mangle]
fn _embassy_rand(buf: &mut [u8]) {
use rand_core::RngCore;
critical_section::with(|_| unsafe {
unwrap!(RNG_INST.as_mut()).fill_bytes(buf);
});
}
static mut RNG_INST: Option<Rng<RNG>> = None;
static EXECUTOR: Forever<Executor> = Forever::new();
static STATE: Forever<State<'static, ETH, 4, 4>> = Forever::new();
static ETH: Forever<Ethernet<'static, ETH, GenericSMI, 4, 4>> = Forever::new();
static CONFIG: Forever<StaticConfigurator> = Forever::new();
static NET_RESOURCES: Forever<StackResources<1, 2, 8>> = Forever::new();
fn config() -> Config {
let mut config = Config::default();
config.rcc.sys_ck = Some(200.mhz().into());
config
}
#[entry]
fn main() -> ! {
#[embassy::main(config = "config()")]
async fn main(spawner: Spawner, p: Peripherals) -> ! {
info!("Hello World!");
info!("Setup RCC...");
let p = embassy_stm32::init(config());
let rng = Rng::new(p.RNG);
unsafe {
RNG_INST.replace(rng);
}
// Generate random seed.
let mut rng = Rng::new(p.RNG);
let mut seed = [0; 8];
rng.fill_bytes(&mut seed);
let seed = u64::from_le_bytes(seed);
let eth_int = interrupt::take!(ETH);
let mac_addr = [0x00, 0x00, 0xDE, 0xAD, 0xBE, 0xEF];
let state = STATE.put(State::new());
let eth = unsafe {
ETH.put(Ethernet::new(
state, p.ETH, eth_int, p.PA1, p.PA2, p.PC1, p.PA7, p.PC4, p.PC5, p.PG13, p.PB13,
p.PG11, GenericSMI, mac_addr, 0,
))
let device = unsafe {
Ethernet::new(
forever!(State::new()),
p.ETH,
eth_int,
p.PA1,
p.PA2,
p.PC1,
p.PA7,
p.PC4,
p.PC5,
p.PG13,
p.PB13,
p.PG11,
GenericSMI,
mac_addr,
0,
)
};
let config = StaticConfigurator::new(NetConfig {
address: Ipv4Cidr::new(Ipv4Address::new(192, 168, 0, 61), 24),
dns_servers: Vec::new(),
gateway: Some(Ipv4Address::new(192, 168, 0, 1)),
});
let config = embassy_net::ConfigStrategy::Dhcp;
//let config = embassy_net::ConfigStrategy::Static(embassy_net::Config {
// address: Ipv4Cidr::new(Ipv4Address::new(10, 42, 0, 61), 24),
// dns_servers: Vec::new(),
// gateway: Some(Ipv4Address::new(10, 42, 0, 1)),
//});
let config = CONFIG.put(config);
// Init network stack
let stack = &*forever!(Stack::new(
device,
config,
forever!(StackResources::<1, 2, 8>::new()),
seed
));
let executor = EXECUTOR.put(Executor::new());
// Launch network task
unwrap!(spawner.spawn(net_task(&stack)));
executor.run(move |spawner| {
unwrap!(spawner.spawn(main_task(eth, config, spawner)));
})
info!("Network task initialized");
// Then we can use it!
let mut rx_buffer = [0; 1024];
let mut tx_buffer = [0; 1024];
loop {
let mut socket = TcpSocket::new(&stack, &mut rx_buffer, &mut tx_buffer);
socket.set_timeout(Some(embassy_net::SmolDuration::from_secs(10)));
let remote_endpoint = (Ipv4Address::new(10, 42, 0, 1), 8000);
info!("connecting...");
let r = socket.connect(remote_endpoint).await;
if let Err(e) = r {
info!("connect error: {:?}", e);
continue;
}
info!("connected!");
loop {
let r = socket.write_all(b"Hello\n").await;
if let Err(e) = r {
info!("write error: {:?}", e);
return;
}
Timer::after(Duration::from_secs(1)).await;
}
}
}

View File

@ -8,7 +8,7 @@ resolver = "2"
[dependencies]
embassy = { version = "0.1.0", path = "../../embassy", features = ["defmt", "defmt-timestamp-uptime", "unstable-traits"] }
embassy-stm32 = { version = "0.1.0", path = "../../embassy-stm32", features = ["nightly", "defmt", "stm32h743bi", "net", "time-driver-any", "exti", "unstable-pac", "unstable-traits"] }
embassy-net = { path = "../../embassy-net", features = ["defmt", "tcp", "medium-ethernet", "pool-16"] }
embassy-net = { path = "../../embassy-net", features = ["defmt", "tcp", "dhcpv4", "medium-ethernet", "pool-16"] }
embedded-io = { version = "0.3.0", features = ["async"] }
defmt = "0.3"
@ -28,11 +28,6 @@ micromath = "2.0.0"
stm32-fmc = "0.2.4"
embedded-storage = "0.3.0"
[dependencies.smoltcp]
version = "0.8.0"
default-features = false
features = ["defmt"]
# cargo build/run
[profile.dev]
codegen-units = 1

View File

@ -2,90 +2,40 @@
#![no_main]
#![feature(type_alias_impl_trait)]
use defmt_rtt as _; // global logger
use panic_probe as _;
use cortex_m_rt::entry;
use defmt::*;
use embassy::executor::{Executor, Spawner};
use embassy::executor::Spawner;
use embassy::time::{Duration, Timer};
use embassy::util::Forever;
use embassy_net::tcp::TcpSocket;
use embassy_net::{Config as NetConfig, Ipv4Address, Ipv4Cidr, StackResources, StaticConfigurator};
use embassy_net::{Ipv4Address, Stack, StackResources};
use embassy_stm32::eth::generic_smi::GenericSMI;
use embassy_stm32::eth::{Ethernet, State};
use embassy_stm32::interrupt;
use embassy_stm32::peripherals::ETH;
use embassy_stm32::peripherals::RNG;
use embassy_stm32::rng::Rng;
use embassy_stm32::time::U32Ext;
use embassy_stm32::Config;
use embassy_stm32::{interrupt, Peripherals};
use embedded_io::asynch::Write;
use heapless::Vec;
use defmt_rtt as _; // global logger
use panic_probe as _;
use rand_core::RngCore;
macro_rules! forever {
($val:expr) => {{
type T = impl Sized;
static FOREVER: Forever<T> = Forever::new();
FOREVER.put_with(move || $val)
}};
}
type Device = Ethernet<'static, ETH, GenericSMI, 4, 4>;
#[embassy::task]
async fn main_task(
device: &'static mut Ethernet<'static, ETH, GenericSMI, 4, 4>,
config: &'static mut StaticConfigurator,
spawner: Spawner,
) {
let net_resources = NET_RESOURCES.put(StackResources::new());
// Init network stack
embassy_net::init(device, config, net_resources);
// Launch network task
unwrap!(spawner.spawn(net_task()));
info!("Network task initialized");
// Then we can use it!
let mut rx_buffer = [0; 1024];
let mut tx_buffer = [0; 1024];
let mut socket = TcpSocket::new(&mut rx_buffer, &mut tx_buffer);
socket.set_timeout(Some(embassy_net::SmolDuration::from_secs(10)));
let remote_endpoint = (Ipv4Address::new(192, 168, 0, 10), 8000);
let r = socket.connect(remote_endpoint).await;
if let Err(e) = r {
info!("connect error: {:?}", e);
return;
}
info!("connected!");
loop {
let r = socket.write_all(b"Hello\n").await;
if let Err(e) = r {
info!("write error: {:?}", e);
return;
}
Timer::after(Duration::from_secs(1)).await;
}
async fn net_task(stack: &'static Stack<Device>) -> ! {
stack.run().await
}
#[embassy::task]
async fn net_task() {
embassy_net::run().await
}
#[no_mangle]
fn _embassy_rand(buf: &mut [u8]) {
use rand_core::RngCore;
critical_section::with(|_| unsafe {
unwrap!(RNG_INST.as_mut()).fill_bytes(buf);
});
}
static mut RNG_INST: Option<Rng<RNG>> = None;
static EXECUTOR: Forever<Executor> = Forever::new();
static STATE: Forever<State<'static, ETH, 4, 4>> = Forever::new();
static ETH: Forever<Ethernet<'static, ETH, GenericSMI, 4, 4>> = Forever::new();
static CONFIG: Forever<StaticConfigurator> = Forever::new();
static NET_RESOURCES: Forever<StackResources<1, 2, 8>> = Forever::new();
#[allow(unused)]
pub fn config() -> Config {
let mut config = Config::default();
config.rcc.sys_ck = Some(400.mhz().into());
@ -94,40 +44,83 @@ pub fn config() -> Config {
config
}
#[entry]
fn main() -> ! {
#[embassy::main(config = "config()")]
async fn main(spawner: Spawner, p: Peripherals) -> ! {
info!("Hello World!");
info!("Setup RCC...");
let p = embassy_stm32::init(config());
let rng = Rng::new(p.RNG);
unsafe {
RNG_INST.replace(rng);
}
// Generate random seed.
let mut rng = Rng::new(p.RNG);
let mut seed = [0; 8];
rng.fill_bytes(&mut seed);
let seed = u64::from_le_bytes(seed);
let eth_int = interrupt::take!(ETH);
let mac_addr = [0x10; 6];
let state = STATE.put(State::new());
let eth = unsafe {
ETH.put(Ethernet::new(
state, p.ETH, eth_int, p.PA1, p.PA2, p.PC1, p.PA7, p.PC4, p.PC5, p.PG13, p.PB13,
p.PG11, GenericSMI, mac_addr, 0,
))
let mac_addr = [0x00, 0x00, 0xDE, 0xAD, 0xBE, 0xEF];
let device = unsafe {
Ethernet::new(
forever!(State::new()),
p.ETH,
eth_int,
p.PA1,
p.PA2,
p.PC1,
p.PA7,
p.PC4,
p.PC5,
p.PG13,
p.PB13,
p.PG11,
GenericSMI,
mac_addr,
0,
)
};
let config = StaticConfigurator::new(NetConfig {
address: Ipv4Cidr::new(Ipv4Address::new(192, 168, 0, 61), 24),
dns_servers: Vec::new(),
gateway: Some(Ipv4Address::new(192, 168, 0, 1)),
});
let config = embassy_net::ConfigStrategy::Dhcp;
//let config = embassy_net::ConfigStrategy::Static(embassy_net::Config {
// address: Ipv4Cidr::new(Ipv4Address::new(10, 42, 0, 61), 24),
// dns_servers: Vec::new(),
// gateway: Some(Ipv4Address::new(10, 42, 0, 1)),
//});
let config = CONFIG.put(config);
// Init network stack
let stack = &*forever!(Stack::new(
device,
config,
forever!(StackResources::<1, 2, 8>::new()),
seed
));
let executor = EXECUTOR.put(Executor::new());
// Launch network task
unwrap!(spawner.spawn(net_task(&stack)));
executor.run(move |spawner| {
unwrap!(spawner.spawn(main_task(eth, config, spawner)));
})
info!("Network task initialized");
// Then we can use it!
let mut rx_buffer = [0; 1024];
let mut tx_buffer = [0; 1024];
loop {
let mut socket = TcpSocket::new(&stack, &mut rx_buffer, &mut tx_buffer);
socket.set_timeout(Some(embassy_net::SmolDuration::from_secs(10)));
let remote_endpoint = (Ipv4Address::new(10, 42, 0, 1), 8000);
info!("connecting...");
let r = socket.connect(remote_endpoint).await;
if let Err(e) = r {
info!("connect error: {:?}", e);
continue;
}
info!("connected!");
loop {
let r = socket.write_all(b"Hello\n").await;
if let Err(e) = r {
info!("write error: {:?}", e);
return;
}
Timer::after(Duration::from_secs(1)).await;
}
}
}