aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--embassy-net-w5500/Cargo.toml16
-rw-r--r--embassy-net-w5500/README.md7
-rw-r--r--embassy-net-w5500/src/device.rs131
-rw-r--r--embassy-net-w5500/src/lib.rs108
-rw-r--r--embassy-net-w5500/src/socket.rs80
-rw-r--r--embassy-net-w5500/src/spi.rs28
-rw-r--r--examples/rp/Cargo.toml4
-rw-r--r--examples/rp/src/bin/ethernet_w5500_multisocket.rs139
-rw-r--r--examples/rp/src/bin/ethernet_w5500_tcp_client.rs127
-rw-r--r--examples/rp/src/bin/ethernet_w5500_tcp_server.rs136
-rw-r--r--examples/rp/src/bin/ethernet_w5500_udp.rs115
11 files changed, 890 insertions, 1 deletions
diff --git a/embassy-net-w5500/Cargo.toml b/embassy-net-w5500/Cargo.toml
new file mode 100644
index 000000000..3f19e3d39
--- /dev/null
+++ b/embassy-net-w5500/Cargo.toml
@@ -0,0 +1,16 @@
1[package]
2name = "embassy-net-w5500"
3version = "0.1.0"
4description = "embassy-net driver for the W5500 ethernet chip"
5keywords = ["embedded", "w5500", "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[dependencies]
11embedded-hal = { version = "1.0.0-alpha.10" }
12embedded-hal-async = { version = "=0.2.0-alpha.1" }
13embassy-net-driver-channel = { version = "0.1.0", path = "../embassy-net-driver-channel"}
14embassy-time = { version = "0.1.0" }
15embassy-futures = { version = "0.1.0" }
16defmt = { version = "0.3", optional = true }
diff --git a/embassy-net-w5500/README.md b/embassy-net-w5500/README.md
new file mode 100644
index 000000000..9eaf4b700
--- /dev/null
+++ b/embassy-net-w5500/README.md
@@ -0,0 +1,7 @@
1# WIZnet W5500 `embassy-net` integration
2
3[`embassy-net`](https://crates.io/crates/embassy-net) integration for the WIZnet W5500 SPI ethernet chip, operating in MACRAW mode.
4
5Supports any SPI driver implementing [`embedded-hal-async`](https://crates.io/crates/embedded-hal-async)
6
7See [`examples`](https://github.com/kalkyl/embassy-net-w5500/tree/main/examples) directory for usage examples with the rp2040 [`WIZnet W5500-EVB-Pico`](https://www.wiznet.io/product-item/w5500-evb-pico/) module. \ No newline at end of file
diff --git a/embassy-net-w5500/src/device.rs b/embassy-net-w5500/src/device.rs
new file mode 100644
index 000000000..9874df0d6
--- /dev/null
+++ b/embassy-net-w5500/src/device.rs
@@ -0,0 +1,131 @@
1use embedded_hal_async::spi::SpiDevice;
2
3use crate::socket;
4use crate::spi::SpiInterface;
5
6pub const MODE: u16 = 0x00;
7pub const MAC: u16 = 0x09;
8pub const SOCKET_INTR: u16 = 0x18;
9pub const PHY_CFG: u16 = 0x2E;
10
11#[repr(u8)]
12pub enum RegisterBlock {
13 Common = 0x00,
14 Socket0 = 0x01,
15 TxBuf = 0x02,
16 RxBuf = 0x03,
17}
18
19/// W5500 in MACRAW mode
20#[derive(Debug)]
21#[cfg_attr(feature = "defmt", derive(defmt::Format))]
22pub struct W5500<SPI> {
23 bus: SpiInterface<SPI>,
24}
25
26impl<SPI: SpiDevice> W5500<SPI> {
27 /// Create and initialize the W5500 driver
28 pub async fn new(spi: SPI, mac_addr: [u8; 6]) -> Result<W5500<SPI>, SPI::Error> {
29 let mut bus = SpiInterface(spi);
30 // Reset device
31 bus.write_frame(RegisterBlock::Common, MODE, &[0x80]).await?;
32
33 // Enable interrupt pin
34 bus.write_frame(RegisterBlock::Common, SOCKET_INTR, &[0x01]).await?;
35 // Enable receive interrupt
36 bus.write_frame(
37 RegisterBlock::Socket0,
38 socket::SOCKET_INTR_MASK,
39 &[socket::Interrupt::Receive as u8],
40 )
41 .await?;
42
43 // Set MAC address
44 bus.write_frame(RegisterBlock::Common, MAC, &mac_addr).await?;
45
46 // Set the raw socket RX/TX buffer sizes to 16KB
47 bus.write_frame(RegisterBlock::Socket0, socket::TXBUF_SIZE, &[16])
48 .await?;
49 bus.write_frame(RegisterBlock::Socket0, socket::RXBUF_SIZE, &[16])
50 .await?;
51
52 // MACRAW mode with MAC filtering.
53 let mode: u8 = (1 << 2) | (1 << 7);
54 bus.write_frame(RegisterBlock::Socket0, socket::MODE, &[mode]).await?;
55 socket::command(&mut bus, socket::Command::Open).await?;
56
57 Ok(Self { bus })
58 }
59
60 /// Read bytes from the RX buffer. Returns the number of bytes read.
61 async fn read_bytes(&mut self, buffer: &mut [u8], offset: u16) -> Result<usize, SPI::Error> {
62 let rx_size = socket::get_rx_size(&mut self.bus).await? as usize;
63
64 let read_buffer = if rx_size > buffer.len() + offset as usize {
65 buffer
66 } else {
67 &mut buffer[..rx_size - offset as usize]
68 };
69
70 let read_ptr = socket::get_rx_read_ptr(&mut self.bus).await?.wrapping_add(offset);
71 self.bus.read_frame(RegisterBlock::RxBuf, read_ptr, read_buffer).await?;
72 socket::set_rx_read_ptr(&mut self.bus, read_ptr.wrapping_add(read_buffer.len() as u16)).await?;
73
74 Ok(read_buffer.len())
75 }
76
77 /// Read an ethernet frame from the device. Returns the number of bytes read.
78 pub async fn read_frame(&mut self, frame: &mut [u8]) -> Result<usize, SPI::Error> {
79 let rx_size = socket::get_rx_size(&mut self.bus).await? as usize;
80 if rx_size == 0 {
81 return Ok(0);
82 }
83
84 socket::reset_interrupt(&mut self.bus, socket::Interrupt::Receive).await?;
85
86 // First two bytes gives the size of the received ethernet frame
87 let expected_frame_size: usize = {
88 let mut frame_bytes = [0u8; 2];
89 assert!(self.read_bytes(&mut frame_bytes[..], 0).await? == 2);
90 u16::from_be_bytes(frame_bytes) as usize - 2
91 };
92
93 // Read the ethernet frame
94 let read_buffer = if frame.len() > expected_frame_size {
95 &mut frame[..expected_frame_size]
96 } else {
97 frame
98 };
99
100 let recvd_frame_size = self.read_bytes(read_buffer, 2).await?;
101
102 // Register RX as completed
103 socket::command(&mut self.bus, socket::Command::Receive).await?;
104
105 // If the whole frame wasn't read, drop it
106 if recvd_frame_size < expected_frame_size {
107 Ok(0)
108 } else {
109 Ok(recvd_frame_size)
110 }
111 }
112
113 /// Write an ethernet frame to the device. Returns number of bytes written
114 pub async fn write_frame(&mut self, frame: &[u8]) -> Result<usize, SPI::Error> {
115 while socket::get_tx_free_size(&mut self.bus).await? < frame.len() as u16 {}
116 let write_ptr = socket::get_tx_write_ptr(&mut self.bus).await?;
117 self.bus.write_frame(RegisterBlock::TxBuf, write_ptr, frame).await?;
118 socket::set_tx_write_ptr(&mut self.bus, write_ptr.wrapping_add(frame.len() as u16)).await?;
119 socket::command(&mut self.bus, socket::Command::Send).await?;
120 Ok(frame.len())
121 }
122
123 pub async fn is_link_up(&mut self) -> bool {
124 let mut link = [0];
125 self.bus
126 .read_frame(RegisterBlock::Common, PHY_CFG, &mut link)
127 .await
128 .ok();
129 link[0] & 1 == 1
130 }
131}
diff --git a/embassy-net-w5500/src/lib.rs b/embassy-net-w5500/src/lib.rs
new file mode 100644
index 000000000..6821373e3
--- /dev/null
+++ b/embassy-net-w5500/src/lib.rs
@@ -0,0 +1,108 @@
1#![no_std]
2/// [`embassy-net`](crates.io/crates/embassy-net) driver for the WIZnet W5500 ethernet chip.
3mod device;
4mod socket;
5mod spi;
6
7use embassy_futures::select::{select, Either};
8use embassy_net_driver_channel as ch;
9use embassy_net_driver_channel::driver::LinkState;
10use embassy_time::{Duration, Timer};
11use embedded_hal::digital::OutputPin;
12use embedded_hal_async::digital::Wait;
13use embedded_hal_async::spi::SpiDevice;
14
15use crate::device::W5500;
16const MTU: usize = 1514;
17
18/// Type alias for the embassy-net driver for W5500
19pub type Device<'d> = embassy_net_driver_channel::Device<'d, MTU>;
20
21/// Internal state for the embassy-net integration.
22pub struct State<const N_RX: usize, const N_TX: usize> {
23 ch_state: ch::State<MTU, N_RX, N_TX>,
24}
25
26impl<const N_RX: usize, const N_TX: usize> State<N_RX, N_TX> {
27 /// Create a new `State`.
28 pub const fn new() -> Self {
29 Self {
30 ch_state: ch::State::new(),
31 }
32 }
33}
34
35/// Background runner for the W5500.
36///
37/// You must call `.run()` in a background task for the W5500 to operate.
38pub struct Runner<'d, SPI: SpiDevice, INT: Wait, RST: OutputPin> {
39 mac: W5500<SPI>,
40 ch: ch::Runner<'d, MTU>,
41 int: INT,
42 _reset: RST,
43}
44
45/// You must call this in a background task for the W5500 to operate.
46impl<'d, SPI: SpiDevice, INT: Wait, RST: OutputPin> Runner<'d, SPI, INT, RST> {
47 pub async fn run(mut self) -> ! {
48 let (state_chan, mut rx_chan, mut tx_chan) = self.ch.split();
49 loop {
50 if self.mac.is_link_up().await {
51 state_chan.set_link_state(LinkState::Up);
52 loop {
53 match select(
54 async {
55 self.int.wait_for_low().await.ok();
56 rx_chan.rx_buf().await
57 },
58 tx_chan.tx_buf(),
59 )
60 .await
61 {
62 Either::First(p) => {
63 if let Ok(n) = self.mac.read_frame(p).await {
64 rx_chan.rx_done(n);
65 }
66 }
67 Either::Second(p) => {
68 self.mac.write_frame(p).await.ok();
69 tx_chan.tx_done();
70 }
71 }
72 }
73 } else {
74 state_chan.set_link_state(LinkState::Down);
75 }
76 }
77 }
78}
79
80/// Obtain a driver for using the W5500 with [`embassy-net`](crates.io/crates/embassy-net).
81pub async fn new<'a, const N_RX: usize, const N_TX: usize, SPI: SpiDevice, INT: Wait, RST: OutputPin>(
82 mac_addr: [u8; 6],
83 state: &'a mut State<N_RX, N_TX>,
84 spi_dev: SPI,
85 int: INT,
86 mut reset: RST,
87) -> (Device<'a>, Runner<'a, SPI, INT, RST>) {
88 // Reset the W5500.
89 reset.set_low().ok();
90 // Ensure the reset is registered.
91 Timer::after(Duration::from_millis(1)).await;
92 reset.set_high().ok();
93 // Wait for the W5500 to achieve PLL lock.
94 Timer::after(Duration::from_millis(2)).await;
95
96 let mac = W5500::new(spi_dev, mac_addr).await.unwrap();
97
98 let (runner, device) = ch::new(&mut state.ch_state, mac_addr);
99 (
100 device,
101 Runner {
102 ch: runner,
103 mac,
104 int,
105 _reset: reset,
106 },
107 )
108}
diff --git a/embassy-net-w5500/src/socket.rs b/embassy-net-w5500/src/socket.rs
new file mode 100644
index 000000000..3d65583c1
--- /dev/null
+++ b/embassy-net-w5500/src/socket.rs
@@ -0,0 +1,80 @@
1use embedded_hal_async::spi::SpiDevice;
2
3use crate::device::RegisterBlock;
4use crate::spi::SpiInterface;
5
6pub const MODE: u16 = 0x00;
7pub const COMMAND: u16 = 0x01;
8pub const RXBUF_SIZE: u16 = 0x1E;
9pub const TXBUF_SIZE: u16 = 0x1F;
10pub const TX_FREE_SIZE: u16 = 0x20;
11pub const TX_DATA_WRITE_PTR: u16 = 0x24;
12pub const RECVD_SIZE: u16 = 0x26;
13pub const RX_DATA_READ_PTR: u16 = 0x28;
14pub const SOCKET_INTR_MASK: u16 = 0x2C;
15
16#[repr(u8)]
17pub enum Command {
18 Open = 0x01,
19 Send = 0x20,
20 Receive = 0x40,
21}
22
23pub const INTR: u16 = 0x02;
24#[repr(u8)]
25pub enum Interrupt {
26 Receive = 0b00100_u8,
27}
28
29pub async fn reset_interrupt<SPI: SpiDevice>(bus: &mut SpiInterface<SPI>, code: Interrupt) -> Result<(), SPI::Error> {
30 let data = [code as u8];
31 bus.write_frame(RegisterBlock::Socket0, INTR, &data).await
32}
33
34pub async fn get_tx_write_ptr<SPI: SpiDevice>(bus: &mut SpiInterface<SPI>) -> Result<u16, SPI::Error> {
35 let mut data = [0u8; 2];
36 bus.read_frame(RegisterBlock::Socket0, TX_DATA_WRITE_PTR, &mut data)
37 .await?;
38 Ok(u16::from_be_bytes(data))
39}
40
41pub async fn set_tx_write_ptr<SPI: SpiDevice>(bus: &mut SpiInterface<SPI>, ptr: u16) -> Result<(), SPI::Error> {
42 let data = ptr.to_be_bytes();
43 bus.write_frame(RegisterBlock::Socket0, TX_DATA_WRITE_PTR, &data).await
44}
45
46pub async fn get_rx_read_ptr<SPI: SpiDevice>(bus: &mut SpiInterface<SPI>) -> Result<u16, SPI::Error> {
47 let mut data = [0u8; 2];
48 bus.read_frame(RegisterBlock::Socket0, RX_DATA_READ_PTR, &mut data)
49 .await?;
50 Ok(u16::from_be_bytes(data))
51}
52
53pub async fn set_rx_read_ptr<SPI: SpiDevice>(bus: &mut SpiInterface<SPI>, ptr: u16) -> Result<(), SPI::Error> {
54 let data = ptr.to_be_bytes();
55 bus.write_frame(RegisterBlock::Socket0, RX_DATA_READ_PTR, &data).await
56}
57
58pub async fn command<SPI: SpiDevice>(bus: &mut SpiInterface<SPI>, command: Command) -> Result<(), SPI::Error> {
59 let data = [command as u8];
60 bus.write_frame(RegisterBlock::Socket0, COMMAND, &data).await
61}
62
63pub async fn get_rx_size<SPI: SpiDevice>(bus: &mut SpiInterface<SPI>) -> Result<u16, SPI::Error> {
64 loop {
65 // Wait until two sequential reads are equal
66 let mut res0 = [0u8; 2];
67 bus.read_frame(RegisterBlock::Socket0, RECVD_SIZE, &mut res0).await?;
68 let mut res1 = [0u8; 2];
69 bus.read_frame(RegisterBlock::Socket0, RECVD_SIZE, &mut res1).await?;
70 if res0 == res1 {
71 break Ok(u16::from_be_bytes(res0));
72 }
73 }
74}
75
76pub async fn get_tx_free_size<SPI: SpiDevice>(bus: &mut SpiInterface<SPI>) -> Result<u16, SPI::Error> {
77 let mut data = [0; 2];
78 bus.read_frame(RegisterBlock::Socket0, TX_FREE_SIZE, &mut data).await?;
79 Ok(u16::from_be_bytes(data))
80}
diff --git a/embassy-net-w5500/src/spi.rs b/embassy-net-w5500/src/spi.rs
new file mode 100644
index 000000000..6cd52c44d
--- /dev/null
+++ b/embassy-net-w5500/src/spi.rs
@@ -0,0 +1,28 @@
1use embedded_hal_async::spi::{Operation, SpiDevice};
2
3use crate::device::RegisterBlock;
4
5#[derive(Debug)]
6#[cfg_attr(feature = "defmt", derive(defmt::Format))]
7pub struct SpiInterface<SPI>(pub SPI);
8
9impl<SPI: SpiDevice> SpiInterface<SPI> {
10 pub async fn read_frame(&mut self, block: RegisterBlock, address: u16, data: &mut [u8]) -> Result<(), SPI::Error> {
11 let address_phase = address.to_be_bytes();
12 let control_phase = [(block as u8) << 3];
13 let operations = &mut [
14 Operation::Write(&address_phase),
15 Operation::Write(&control_phase),
16 Operation::TransferInPlace(data),
17 ];
18 self.0.transaction(operations).await
19 }
20
21 pub async fn write_frame(&mut self, block: RegisterBlock, address: u16, data: &[u8]) -> Result<(), SPI::Error> {
22 let address_phase = address.to_be_bytes();
23 let control_phase = [(block as u8) << 3 | 0b0000_0100];
24 let data_phase = data;
25 let operations = &[&address_phase[..], &control_phase, &data_phase];
26 self.0.write_transaction(operations).await
27 }
28}
diff --git a/examples/rp/Cargo.toml b/examples/rp/Cargo.toml
index f77377a6f..58b701915 100644
--- a/examples/rp/Cargo.toml
+++ b/examples/rp/Cargo.toml
@@ -12,7 +12,8 @@ embassy-executor = { version = "0.2.0", path = "../../embassy-executor", feature
12embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["nightly", "unstable-traits", "defmt", "defmt-timestamp-uptime"] } 12embassy-time = { version = "0.1.0", path = "../../embassy-time", features = ["nightly", "unstable-traits", "defmt", "defmt-timestamp-uptime"] }
13embassy-rp = { version = "0.1.0", path = "../../embassy-rp", features = ["defmt", "unstable-traits", "nightly", "unstable-pac", "time-driver", "critical-section-impl"] } 13embassy-rp = { version = "0.1.0", path = "../../embassy-rp", features = ["defmt", "unstable-traits", "nightly", "unstable-pac", "time-driver", "critical-section-impl"] }
14embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"] } 14embassy-usb = { version = "0.1.0", path = "../../embassy-usb", features = ["defmt"] }
15embassy-net = { version = "0.1.0", path = "../../embassy-net", features = ["defmt", "nightly", "tcp", "dhcpv4", "medium-ethernet"] } 15embassy-net = { version = "0.1.0", path = "../../embassy-net", features = ["defmt", "nightly", "tcp", "udp", "dhcpv4", "medium-ethernet"] }
16embassy-net-w5500 = { version = "0.1.0", path = "../../embassy-net-w5500", features = ["defmt"] }
16embassy-futures = { version = "0.1.0", path = "../../embassy-futures" } 17embassy-futures = { version = "0.1.0", path = "../../embassy-futures" }
17embassy-usb-logger = { version = "0.1.0", path = "../../embassy-usb-logger" } 18embassy-usb-logger = { version = "0.1.0", path = "../../embassy-usb-logger" }
18embassy-lora = { version = "0.1.0", path = "../../embassy-lora", features = ["time", "defmt"] } 19embassy-lora = { version = "0.1.0", path = "../../embassy-lora", features = ["time", "defmt"] }
@@ -48,6 +49,7 @@ static_cell = "1.0.0"
48log = "0.4" 49log = "0.4"
49pio-proc = "0.2" 50pio-proc = "0.2"
50pio = "0.2.1" 51pio = "0.2.1"
52rand = { version = "0.8.5", default-features = false }
51 53
52[profile.release] 54[profile.release]
53debug = true 55debug = true
diff --git a/examples/rp/src/bin/ethernet_w5500_multisocket.rs b/examples/rp/src/bin/ethernet_w5500_multisocket.rs
new file mode 100644
index 000000000..c8e6d46a6
--- /dev/null
+++ b/examples/rp/src/bin/ethernet_w5500_multisocket.rs
@@ -0,0 +1,139 @@
1//! This example shows how you can allow multiple simultaneous TCP connections, by having multiple sockets listening on the same port.
2//!
3//! Example written for the [`WIZnet W5500-EVB-Pico`](https://www.wiznet.io/product-item/w5500-evb-pico/) board.
4
5#![no_std]
6#![no_main]
7#![feature(type_alias_impl_trait)]
8
9use defmt::*;
10use embassy_executor::Spawner;
11use embassy_futures::yield_now;
12use embassy_net::{Stack, StackResources};
13use embassy_net_w5500::*;
14use embassy_rp::clocks::RoscRng;
15use embassy_rp::gpio::{Input, Level, Output, Pull};
16use embassy_rp::peripherals::{PIN_17, PIN_20, PIN_21, SPI0};
17use embassy_rp::spi::{Async, Config as SpiConfig, Spi};
18use embassy_time::Duration;
19use embedded_hal_async::spi::ExclusiveDevice;
20use embedded_io::asynch::Write;
21use rand::RngCore;
22use static_cell::StaticCell;
23use {defmt_rtt as _, panic_probe as _};
24
25macro_rules! singleton {
26 ($val:expr) => {{
27 type T = impl Sized;
28 static STATIC_CELL: StaticCell<T> = StaticCell::new();
29 let (x,) = STATIC_CELL.init(($val,));
30 x
31 }};
32}
33
34#[embassy_executor::task]
35async fn ethernet_task(
36 runner: Runner<
37 'static,
38 ExclusiveDevice<Spi<'static, SPI0, Async>, Output<'static, PIN_17>>,
39 Input<'static, PIN_21>,
40 Output<'static, PIN_20>,
41 >,
42) -> ! {
43 runner.run().await
44}
45
46#[embassy_executor::task]
47async fn net_task(stack: &'static Stack<Device<'static>>) -> ! {
48 stack.run().await
49}
50
51#[embassy_executor::main]
52async fn main(spawner: Spawner) {
53 let p = embassy_rp::init(Default::default());
54 let mut rng = RoscRng;
55
56 let mut spi_cfg = SpiConfig::default();
57 spi_cfg.frequency = 50_000_000;
58 let (miso, mosi, clk) = (p.PIN_16, p.PIN_19, p.PIN_18);
59 let spi = Spi::new(p.SPI0, clk, mosi, miso, p.DMA_CH0, p.DMA_CH1, spi_cfg);
60 let cs = Output::new(p.PIN_17, Level::High);
61 let w5500_int = Input::new(p.PIN_21, Pull::Up);
62 let w5500_reset = Output::new(p.PIN_20, Level::High);
63
64 let mac_addr = [0x02, 0x00, 0x00, 0x00, 0x00, 0x00];
65 let state = singleton!(State::<8, 8>::new());
66 let (device, runner) =
67 embassy_net_w5500::new(mac_addr, state, ExclusiveDevice::new(spi, cs), w5500_int, w5500_reset).await;
68 unwrap!(spawner.spawn(ethernet_task(runner)));
69
70 // Generate random seed
71 let seed = rng.next_u64();
72
73 // Init network stack
74 let stack = &*singleton!(Stack::new(
75 device,
76 embassy_net::Config::Dhcp(Default::default()),
77 singleton!(StackResources::<3>::new()),
78 seed
79 ));
80
81 // Launch network task
82 unwrap!(spawner.spawn(net_task(&stack)));
83
84 info!("Waiting for DHCP...");
85 let cfg = wait_for_config(stack).await;
86 let local_addr = cfg.address.address();
87 info!("IP address: {:?}", local_addr);
88
89 // Create two sockets listening to the same port, to handle simultaneous connections
90 unwrap!(spawner.spawn(listen_task(&stack, 0, 1234)));
91 unwrap!(spawner.spawn(listen_task(&stack, 1, 1234)));
92}
93
94#[embassy_executor::task(pool_size = 2)]
95async fn listen_task(stack: &'static Stack<Device<'static>>, id: u8, port: u16) {
96 let mut rx_buffer = [0; 4096];
97 let mut tx_buffer = [0; 4096];
98 let mut buf = [0; 4096];
99 loop {
100 let mut socket = embassy_net::tcp::TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer);
101 socket.set_timeout(Some(Duration::from_secs(10)));
102
103 info!("SOCKET {}: Listening on TCP:{}...", id, port);
104 if let Err(e) = socket.accept(port).await {
105 warn!("accept error: {:?}", e);
106 continue;
107 }
108 info!("SOCKET {}: Received connection from {:?}", id, socket.remote_endpoint());
109
110 loop {
111 let n = match socket.read(&mut buf).await {
112 Ok(0) => {
113 warn!("read EOF");
114 break;
115 }
116 Ok(n) => n,
117 Err(e) => {
118 warn!("SOCKET {}: {:?}", id, e);
119 break;
120 }
121 };
122 info!("SOCKET {}: rxd {}", id, core::str::from_utf8(&buf[..n]).unwrap());
123
124 if let Err(e) = socket.write_all(&buf[..n]).await {
125 warn!("write error: {:?}", e);
126 break;
127 }
128 }
129 }
130}
131
132async fn wait_for_config(stack: &'static Stack<Device<'static>>) -> embassy_net::StaticConfig {
133 loop {
134 if let Some(config) = stack.config() {
135 return config.clone();
136 }
137 yield_now().await;
138 }
139}
diff --git a/examples/rp/src/bin/ethernet_w5500_tcp_client.rs b/examples/rp/src/bin/ethernet_w5500_tcp_client.rs
new file mode 100644
index 000000000..9a7c3ad19
--- /dev/null
+++ b/examples/rp/src/bin/ethernet_w5500_tcp_client.rs
@@ -0,0 +1,127 @@
1//! This example implements a TCP client that attempts to connect to a host on port 1234 and send it some data once per second.
2//!
3//! Example written for the [`WIZnet W5500-EVB-Pico`](https://www.wiznet.io/product-item/w5500-evb-pico/) board.
4
5#![no_std]
6#![no_main]
7#![feature(type_alias_impl_trait)]
8
9use core::str::FromStr;
10
11use defmt::*;
12use embassy_executor::Spawner;
13use embassy_futures::yield_now;
14use embassy_net::{Stack, StackResources};
15use embassy_net_w5500::*;
16use embassy_rp::clocks::RoscRng;
17use embassy_rp::gpio::{Input, Level, Output, Pull};
18use embassy_rp::peripherals::{PIN_17, PIN_20, PIN_21, SPI0};
19use embassy_rp::spi::{Async, Config as SpiConfig, Spi};
20use embassy_time::{Duration, Timer};
21use embedded_hal_async::spi::ExclusiveDevice;
22use embedded_io::asynch::Write;
23use rand::RngCore;
24use static_cell::StaticCell;
25use {defmt_rtt as _, panic_probe as _};
26
27macro_rules! singleton {
28 ($val:expr) => {{
29 type T = impl Sized;
30 static STATIC_CELL: StaticCell<T> = StaticCell::new();
31 let (x,) = STATIC_CELL.init(($val,));
32 x
33 }};
34}
35
36#[embassy_executor::task]
37async fn ethernet_task(
38 runner: Runner<
39 'static,
40 ExclusiveDevice<Spi<'static, SPI0, Async>, Output<'static, PIN_17>>,
41 Input<'static, PIN_21>,
42 Output<'static, PIN_20>,
43 >,
44) -> ! {
45 runner.run().await
46}
47
48#[embassy_executor::task]
49async fn net_task(stack: &'static Stack<Device<'static>>) -> ! {
50 stack.run().await
51}
52
53#[embassy_executor::main]
54async fn main(spawner: Spawner) {
55 let p = embassy_rp::init(Default::default());
56 let mut rng = RoscRng;
57 let mut led = Output::new(p.PIN_25, Level::Low);
58
59 let mut spi_cfg = SpiConfig::default();
60 spi_cfg.frequency = 50_000_000;
61 let (miso, mosi, clk) = (p.PIN_16, p.PIN_19, p.PIN_18);
62 let spi = Spi::new(p.SPI0, clk, mosi, miso, p.DMA_CH0, p.DMA_CH1, spi_cfg);
63 let cs = Output::new(p.PIN_17, Level::High);
64 let w5500_int = Input::new(p.PIN_21, Pull::Up);
65 let w5500_reset = Output::new(p.PIN_20, Level::High);
66
67 let mac_addr = [0x02, 0x00, 0x00, 0x00, 0x00, 0x00];
68 let state = singleton!(State::<8, 8>::new());
69 let (device, runner) =
70 embassy_net_w5500::new(mac_addr, state, ExclusiveDevice::new(spi, cs), w5500_int, w5500_reset).await;
71 unwrap!(spawner.spawn(ethernet_task(runner)));
72
73 // Generate random seed
74 let seed = rng.next_u64();
75
76 // Init network stack
77 let stack = &*singleton!(Stack::new(
78 device,
79 embassy_net::Config::Dhcp(Default::default()),
80 singleton!(StackResources::<2>::new()),
81 seed
82 ));
83
84 // Launch network task
85 unwrap!(spawner.spawn(net_task(&stack)));
86
87 info!("Waiting for DHCP...");
88 let cfg = wait_for_config(stack).await;
89 let local_addr = cfg.address.address();
90 info!("IP address: {:?}", local_addr);
91
92 let mut rx_buffer = [0; 4096];
93 let mut tx_buffer = [0; 4096];
94 loop {
95 let mut socket = embassy_net::tcp::TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer);
96 socket.set_timeout(Some(Duration::from_secs(10)));
97
98 led.set_low();
99 info!("Connecting...");
100 let host_addr = embassy_net::Ipv4Address::from_str("192.168.1.110").unwrap();
101 if let Err(e) = socket.connect((host_addr, 1234)).await {
102 warn!("connect error: {:?}", e);
103 continue;
104 }
105 info!("Connected to {:?}", socket.remote_endpoint());
106 led.set_high();
107
108 let msg = b"Hello world!\n";
109 loop {
110 if let Err(e) = socket.write_all(msg).await {
111 warn!("write error: {:?}", e);
112 break;
113 }
114 info!("txd: {}", core::str::from_utf8(msg).unwrap());
115 Timer::after(Duration::from_secs(1)).await;
116 }
117 }
118}
119
120async fn wait_for_config(stack: &'static Stack<Device<'static>>) -> embassy_net::StaticConfig {
121 loop {
122 if let Some(config) = stack.config() {
123 return config.clone();
124 }
125 yield_now().await;
126 }
127}
diff --git a/examples/rp/src/bin/ethernet_w5500_tcp_server.rs b/examples/rp/src/bin/ethernet_w5500_tcp_server.rs
new file mode 100644
index 000000000..f02543246
--- /dev/null
+++ b/examples/rp/src/bin/ethernet_w5500_tcp_server.rs
@@ -0,0 +1,136 @@
1//! This example implements a TCP echo server on port 1234 and using DHCP.
2//! Send it some data, you should see it echoed back and printed in the console.
3//!
4//! Example written for the [`WIZnet W5500-EVB-Pico`](https://www.wiznet.io/product-item/w5500-evb-pico/) board.
5
6#![no_std]
7#![no_main]
8#![feature(type_alias_impl_trait)]
9
10use defmt::*;
11use embassy_executor::Spawner;
12use embassy_futures::yield_now;
13use embassy_net::{Stack, StackResources};
14use embassy_net_w5500::*;
15use embassy_rp::clocks::RoscRng;
16use embassy_rp::gpio::{Input, Level, Output, Pull};
17use embassy_rp::peripherals::{PIN_17, PIN_20, PIN_21, SPI0};
18use embassy_rp::spi::{Async, Config as SpiConfig, Spi};
19use embassy_time::Duration;
20use embedded_hal_async::spi::ExclusiveDevice;
21use embedded_io::asynch::Write;
22use rand::RngCore;
23use static_cell::StaticCell;
24use {defmt_rtt as _, panic_probe as _};
25
26macro_rules! singleton {
27 ($val:expr) => {{
28 type T = impl Sized;
29 static STATIC_CELL: StaticCell<T> = StaticCell::new();
30 let (x,) = STATIC_CELL.init(($val,));
31 x
32 }};
33}
34
35#[embassy_executor::task]
36async fn ethernet_task(
37 runner: Runner<
38 'static,
39 ExclusiveDevice<Spi<'static, SPI0, Async>, Output<'static, PIN_17>>,
40 Input<'static, PIN_21>,
41 Output<'static, PIN_20>,
42 >,
43) -> ! {
44 runner.run().await
45}
46
47#[embassy_executor::task]
48async fn net_task(stack: &'static Stack<Device<'static>>) -> ! {
49 stack.run().await
50}
51
52#[embassy_executor::main]
53async fn main(spawner: Spawner) {
54 let p = embassy_rp::init(Default::default());
55 let mut rng = RoscRng;
56 let mut led = Output::new(p.PIN_25, Level::Low);
57
58 let mut spi_cfg = SpiConfig::default();
59 spi_cfg.frequency = 50_000_000;
60 let (miso, mosi, clk) = (p.PIN_16, p.PIN_19, p.PIN_18);
61 let spi = Spi::new(p.SPI0, clk, mosi, miso, p.DMA_CH0, p.DMA_CH1, spi_cfg);
62 let cs = Output::new(p.PIN_17, Level::High);
63 let w5500_int = Input::new(p.PIN_21, Pull::Up);
64 let w5500_reset = Output::new(p.PIN_20, Level::High);
65
66 let mac_addr = [0x02, 0x00, 0x00, 0x00, 0x00, 0x00];
67 let state = singleton!(State::<8, 8>::new());
68 let (device, runner) =
69 embassy_net_w5500::new(mac_addr, state, ExclusiveDevice::new(spi, cs), w5500_int, w5500_reset).await;
70 unwrap!(spawner.spawn(ethernet_task(runner)));
71
72 // Generate random seed
73 let seed = rng.next_u64();
74
75 // Init network stack
76 let stack = &*singleton!(Stack::new(
77 device,
78 embassy_net::Config::Dhcp(Default::default()),
79 singleton!(StackResources::<2>::new()),
80 seed
81 ));
82
83 // Launch network task
84 unwrap!(spawner.spawn(net_task(&stack)));
85
86 info!("Waiting for DHCP...");
87 let cfg = wait_for_config(stack).await;
88 let local_addr = cfg.address.address();
89 info!("IP address: {:?}", local_addr);
90
91 let mut rx_buffer = [0; 4096];
92 let mut tx_buffer = [0; 4096];
93 let mut buf = [0; 4096];
94 loop {
95 let mut socket = embassy_net::tcp::TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer);
96 socket.set_timeout(Some(Duration::from_secs(10)));
97
98 led.set_low();
99 info!("Listening on TCP:1234...");
100 if let Err(e) = socket.accept(1234).await {
101 warn!("accept error: {:?}", e);
102 continue;
103 }
104 info!("Received connection from {:?}", socket.remote_endpoint());
105 led.set_high();
106
107 loop {
108 let n = match socket.read(&mut buf).await {
109 Ok(0) => {
110 warn!("read EOF");
111 break;
112 }
113 Ok(n) => n,
114 Err(e) => {
115 warn!("{:?}", e);
116 break;
117 }
118 };
119 info!("rxd {}", core::str::from_utf8(&buf[..n]).unwrap());
120
121 if let Err(e) = socket.write_all(&buf[..n]).await {
122 warn!("write error: {:?}", e);
123 break;
124 }
125 }
126 }
127}
128
129async fn wait_for_config(stack: &'static Stack<Device<'static>>) -> embassy_net::StaticConfig {
130 loop {
131 if let Some(config) = stack.config() {
132 return config.clone();
133 }
134 yield_now().await;
135 }
136}
diff --git a/examples/rp/src/bin/ethernet_w5500_udp.rs b/examples/rp/src/bin/ethernet_w5500_udp.rs
new file mode 100644
index 000000000..2c54f711e
--- /dev/null
+++ b/examples/rp/src/bin/ethernet_w5500_udp.rs
@@ -0,0 +1,115 @@
1//! This example implements a UDP server listening on port 1234 and echoing back the data.
2//!
3//! Example written for the [`WIZnet W5500-EVB-Pico`](https://www.wiznet.io/product-item/w5500-evb-pico/) board.
4
5#![no_std]
6#![no_main]
7#![feature(type_alias_impl_trait)]
8
9use defmt::*;
10use embassy_executor::Spawner;
11use embassy_futures::yield_now;
12use embassy_net::udp::{PacketMetadata, UdpSocket};
13use embassy_net::{Stack, StackResources};
14use embassy_net_w5500::*;
15use embassy_rp::clocks::RoscRng;
16use embassy_rp::gpio::{Input, Level, Output, Pull};
17use embassy_rp::peripherals::{PIN_17, PIN_20, PIN_21, SPI0};
18use embassy_rp::spi::{Async, Config as SpiConfig, Spi};
19use embedded_hal_async::spi::ExclusiveDevice;
20use rand::RngCore;
21use static_cell::StaticCell;
22use {defmt_rtt as _, panic_probe as _};
23
24macro_rules! singleton {
25 ($val:expr) => {{
26 type T = impl Sized;
27 static STATIC_CELL: StaticCell<T> = StaticCell::new();
28 let (x,) = STATIC_CELL.init(($val,));
29 x
30 }};
31}
32
33#[embassy_executor::task]
34async fn ethernet_task(
35 runner: Runner<
36 'static,
37 ExclusiveDevice<Spi<'static, SPI0, Async>, Output<'static, PIN_17>>,
38 Input<'static, PIN_21>,
39 Output<'static, PIN_20>,
40 >,
41) -> ! {
42 runner.run().await
43}
44
45#[embassy_executor::task]
46async fn net_task(stack: &'static Stack<Device<'static>>) -> ! {
47 stack.run().await
48}
49
50#[embassy_executor::main]
51async fn main(spawner: Spawner) {
52 let p = embassy_rp::init(Default::default());
53 let mut rng = RoscRng;
54
55 let mut spi_cfg = SpiConfig::default();
56 spi_cfg.frequency = 50_000_000;
57 let (miso, mosi, clk) = (p.PIN_16, p.PIN_19, p.PIN_18);
58 let spi = Spi::new(p.SPI0, clk, mosi, miso, p.DMA_CH0, p.DMA_CH1, spi_cfg);
59 let cs = Output::new(p.PIN_17, Level::High);
60 let w5500_int = Input::new(p.PIN_21, Pull::Up);
61 let w5500_reset = Output::new(p.PIN_20, Level::High);
62
63 let mac_addr = [0x02, 0x00, 0x00, 0x00, 0x00, 0x00];
64 let state = singleton!(State::<8, 8>::new());
65 let (device, runner) =
66 embassy_net_w5500::new(mac_addr, state, ExclusiveDevice::new(spi, cs), w5500_int, w5500_reset).await;
67 unwrap!(spawner.spawn(ethernet_task(runner)));
68
69 // Generate random seed
70 let seed = rng.next_u64();
71
72 // Init network stack
73 let stack = &*singleton!(Stack::new(
74 device,
75 embassy_net::Config::Dhcp(Default::default()),
76 singleton!(StackResources::<2>::new()),
77 seed
78 ));
79
80 // Launch network task
81 unwrap!(spawner.spawn(net_task(&stack)));
82
83 info!("Waiting for DHCP...");
84 let cfg = wait_for_config(stack).await;
85 let local_addr = cfg.address.address();
86 info!("IP address: {:?}", local_addr);
87
88 // Then we can use it!
89 let mut rx_buffer = [0; 4096];
90 let mut tx_buffer = [0; 4096];
91 let mut rx_meta = [PacketMetadata::EMPTY; 16];
92 let mut tx_meta = [PacketMetadata::EMPTY; 16];
93 let mut buf = [0; 4096];
94 loop {
95 let mut socket = UdpSocket::new(stack, &mut rx_meta, &mut rx_buffer, &mut tx_meta, &mut tx_buffer);
96 socket.bind(1234).unwrap();
97
98 loop {
99 let (n, ep) = socket.recv_from(&mut buf).await.unwrap();
100 if let Ok(s) = core::str::from_utf8(&buf[..n]) {
101 info!("rxd from {}: {}", ep, s);
102 }
103 socket.send_to(&buf[..n], ep).await.unwrap();
104 }
105 }
106}
107
108async fn wait_for_config(stack: &'static Stack<Device<'static>>) -> embassy_net::StaticConfig {
109 loop {
110 if let Some(config) = stack.config() {
111 return config.clone();
112 }
113 yield_now().await;
114 }
115}