aboutsummaryrefslogtreecommitdiff
path: root/embassy-net/src
diff options
context:
space:
mode:
authorbors[bot] <26634292+bors[bot]@users.noreply.github.com>2022-08-11 14:17:11 +0000
committerGitHub <[email protected]>2022-08-11 14:17:11 +0000
commit6ffca81a38d2c7f57da667ff49b4296c4eba78e2 (patch)
tree43b1ce2ccac5bda85e805a87ec1e71e259f0a970 /embassy-net/src
parent6cae87ee5da4e137fa3990b81cdb53aeebc676e0 (diff)
parentef473827a2beaca120f45fbe490f84a0be7d381d (diff)
Merge #880
880: Add UDP socket support r=Dirbaio a=arturkow2000 Co-authored-by: Artur Kowalski <[email protected]> Co-authored-by: Artur Kowalski <[email protected]>
Diffstat (limited to 'embassy-net/src')
-rw-r--r--embassy-net/src/lib.rs5
-rw-r--r--embassy-net/src/udp.rs157
2 files changed, 162 insertions, 0 deletions
diff --git a/embassy-net/src/lib.rs b/embassy-net/src/lib.rs
index 1c5ba103a..83d364715 100644
--- a/embassy-net/src/lib.rs
+++ b/embassy-net/src/lib.rs
@@ -16,6 +16,9 @@ pub use stack::{Config, ConfigStrategy, Stack, StackResources};
16#[cfg(feature = "tcp")] 16#[cfg(feature = "tcp")]
17pub mod tcp; 17pub mod tcp;
18 18
19#[cfg(feature = "udp")]
20pub mod udp;
21
19// smoltcp reexports 22// smoltcp reexports
20pub use smoltcp::phy::{DeviceCapabilities, Medium}; 23pub use smoltcp::phy::{DeviceCapabilities, Medium};
21pub use smoltcp::time::{Duration as SmolDuration, Instant as SmolInstant}; 24pub use smoltcp::time::{Duration as SmolDuration, Instant as SmolInstant};
@@ -24,3 +27,5 @@ pub use smoltcp::wire::{EthernetAddress, HardwareAddress};
24pub use smoltcp::wire::{IpAddress, IpCidr, Ipv4Address, Ipv4Cidr}; 27pub use smoltcp::wire::{IpAddress, IpCidr, Ipv4Address, Ipv4Cidr};
25#[cfg(feature = "proto-ipv6")] 28#[cfg(feature = "proto-ipv6")]
26pub use smoltcp::wire::{Ipv6Address, Ipv6Cidr}; 29pub use smoltcp::wire::{Ipv6Address, Ipv6Cidr};
30#[cfg(feature = "udp")]
31pub use smoltcp::{socket::udp::PacketMetadata, wire::IpListenEndpoint};
diff --git a/embassy-net/src/udp.rs b/embassy-net/src/udp.rs
new file mode 100644
index 000000000..78b09a492
--- /dev/null
+++ b/embassy-net/src/udp.rs
@@ -0,0 +1,157 @@
1use core::cell::UnsafeCell;
2use core::mem;
3use core::task::Poll;
4
5use futures::future::poll_fn;
6use smoltcp::iface::{Interface, SocketHandle};
7use smoltcp::socket::udp::{self, PacketMetadata};
8use smoltcp::wire::{IpEndpoint, IpListenEndpoint};
9
10use super::stack::SocketStack;
11use crate::{Device, Stack};
12
13#[derive(PartialEq, Eq, Clone, Copy, Debug)]
14#[cfg_attr(feature = "defmt", derive(defmt::Format))]
15pub enum BindError {
16 /// The socket was already open.
17 InvalidState,
18 /// No route to host.
19 NoRoute,
20}
21
22#[derive(PartialEq, Eq, Clone, Copy, Debug)]
23#[cfg_attr(feature = "defmt", derive(defmt::Format))]
24pub enum Error {
25 /// No route to host.
26 NoRoute,
27}
28
29pub struct UdpSocket<'a> {
30 stack: &'a UnsafeCell<SocketStack>,
31 handle: SocketHandle,
32}
33
34impl<'a> UdpSocket<'a> {
35 pub fn new<D: Device>(
36 stack: &'a Stack<D>,
37 rx_meta: &'a mut [PacketMetadata],
38 rx_buffer: &'a mut [u8],
39 tx_meta: &'a mut [PacketMetadata],
40 tx_buffer: &'a mut [u8],
41 ) -> Self {
42 // safety: not accessed reentrantly.
43 let s = unsafe { &mut *stack.socket.get() };
44
45 let rx_meta: &'static mut [PacketMetadata] = unsafe { mem::transmute(rx_meta) };
46 let rx_buffer: &'static mut [u8] = unsafe { mem::transmute(rx_buffer) };
47 let tx_meta: &'static mut [PacketMetadata] = unsafe { mem::transmute(tx_meta) };
48 let tx_buffer: &'static mut [u8] = unsafe { mem::transmute(tx_buffer) };
49 let handle = s.sockets.add(udp::Socket::new(
50 udp::PacketBuffer::new(rx_meta, rx_buffer),
51 udp::PacketBuffer::new(tx_meta, tx_buffer),
52 ));
53
54 Self {
55 stack: &stack.socket,
56 handle,
57 }
58 }
59
60 pub fn bind<T>(&mut self, endpoint: T) -> Result<(), BindError>
61 where
62 T: Into<IpListenEndpoint>,
63 {
64 let mut endpoint = endpoint.into();
65
66 // safety: not accessed reentrantly.
67 if endpoint.port == 0 {
68 // If user didn't specify port allocate a dynamic port.
69 endpoint.port = unsafe { &mut *self.stack.get() }.get_local_port();
70 }
71
72 // safety: not accessed reentrantly.
73 match unsafe { self.with_mut(|s, _| s.bind(endpoint)) } {
74 Ok(()) => Ok(()),
75 Err(udp::BindError::InvalidState) => Err(BindError::InvalidState),
76 Err(udp::BindError::Unaddressable) => Err(BindError::NoRoute),
77 }
78 }
79
80 /// SAFETY: must not call reentrantly.
81 unsafe fn with<R>(&self, f: impl FnOnce(&udp::Socket, &Interface) -> R) -> R {
82 let s = &*self.stack.get();
83 let socket = s.sockets.get::<udp::Socket>(self.handle);
84 f(socket, &s.iface)
85 }
86
87 /// SAFETY: must not call reentrantly.
88 unsafe fn with_mut<R>(&self, f: impl FnOnce(&mut udp::Socket, &mut Interface) -> R) -> R {
89 let s = &mut *self.stack.get();
90 let socket = s.sockets.get_mut::<udp::Socket>(self.handle);
91 let res = f(socket, &mut s.iface);
92 s.waker.wake();
93 res
94 }
95
96 pub async fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, IpEndpoint), Error> {
97 poll_fn(move |cx| unsafe {
98 self.with_mut(|s, _| match s.recv_slice(buf) {
99 Ok(x) => Poll::Ready(Ok(x)),
100 // No data ready
101 Err(udp::RecvError::Exhausted) => {
102 //s.register_recv_waker(cx.waker());
103 cx.waker().wake_by_ref();
104 Poll::Pending
105 }
106 })
107 })
108 .await
109 }
110
111 pub async fn send_to<T>(&self, buf: &[u8], remote_endpoint: T) -> Result<(), Error>
112 where
113 T: Into<IpEndpoint>,
114 {
115 let remote_endpoint = remote_endpoint.into();
116 poll_fn(move |cx| unsafe {
117 self.with_mut(|s, _| match s.send_slice(buf, remote_endpoint) {
118 // Entire datagram has been sent
119 Ok(()) => Poll::Ready(Ok(())),
120 Err(udp::SendError::BufferFull) => {
121 s.register_send_waker(cx.waker());
122 Poll::Pending
123 }
124 Err(udp::SendError::Unaddressable) => Poll::Ready(Err(Error::NoRoute)),
125 })
126 })
127 .await
128 }
129
130 pub fn endpoint(&self) -> IpListenEndpoint {
131 unsafe { self.with(|s, _| s.endpoint()) }
132 }
133
134 pub fn is_open(&self) -> bool {
135 unsafe { self.with(|s, _| s.is_open()) }
136 }
137
138 pub fn close(&mut self) {
139 unsafe { self.with_mut(|s, _| s.close()) }
140 }
141
142 pub fn may_send(&self) -> bool {
143 unsafe { self.with(|s, _| s.can_send()) }
144 }
145
146 pub fn may_recv(&self) -> bool {
147 unsafe { self.with(|s, _| s.can_recv()) }
148 }
149}
150
151impl Drop for UdpSocket<'_> {
152 fn drop(&mut self) {
153 // safety: not accessed reentrantly.
154 let s = unsafe { &mut *self.stack.get() };
155 s.sockets.remove(self.handle);
156 }
157}