2023-05-15 00:39:57 +02:00
|
|
|
//! UDP sockets.
|
|
|
|
|
2022-12-03 00:56:16 +01:00
|
|
|
use core::cell::RefCell;
|
2022-09-22 16:42:49 +02:00
|
|
|
use core::future::poll_fn;
|
2022-07-28 10:25:47 +02:00
|
|
|
use core::mem;
|
2023-07-12 11:32:02 +02:00
|
|
|
use core::task::{Context, Poll};
|
2022-07-28 10:25:47 +02:00
|
|
|
|
2022-12-26 03:33:49 +01:00
|
|
|
use embassy_net_driver::Driver;
|
2022-07-28 10:25:47 +02:00
|
|
|
use smoltcp::iface::{Interface, SocketHandle};
|
2023-05-15 00:55:34 +02:00
|
|
|
use smoltcp::socket::udp;
|
|
|
|
pub use smoltcp::socket::udp::PacketMetadata;
|
2022-07-28 10:25:47 +02:00
|
|
|
use smoltcp::wire::{IpEndpoint, IpListenEndpoint};
|
|
|
|
|
2022-12-26 03:33:49 +01:00
|
|
|
use crate::{SocketStack, Stack};
|
2022-07-28 10:25:47 +02:00
|
|
|
|
2023-05-15 00:39:57 +02:00
|
|
|
/// Error returned by [`UdpSocket::bind`].
|
2022-07-28 10:25:47 +02:00
|
|
|
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
|
|
|
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
|
|
|
pub enum BindError {
|
|
|
|
/// The socket was already open.
|
|
|
|
InvalidState,
|
|
|
|
/// No route to host.
|
|
|
|
NoRoute,
|
|
|
|
}
|
|
|
|
|
2023-05-15 00:39:57 +02:00
|
|
|
/// Error returned by [`UdpSocket::recv_from`] and [`UdpSocket::send_to`].
|
2022-07-28 10:25:47 +02:00
|
|
|
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
|
|
|
|
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
|
|
|
|
pub enum Error {
|
|
|
|
/// No route to host.
|
|
|
|
NoRoute,
|
2023-09-10 20:13:56 +02:00
|
|
|
/// Socket not bound to an outgoing port.
|
|
|
|
SocketNotBound,
|
2022-07-28 10:25:47 +02:00
|
|
|
}
|
|
|
|
|
2023-05-15 00:39:57 +02:00
|
|
|
/// An UDP socket.
|
2022-07-28 10:25:47 +02:00
|
|
|
pub struct UdpSocket<'a> {
|
2022-12-03 00:56:16 +01:00
|
|
|
stack: &'a RefCell<SocketStack>,
|
2022-08-11 15:52:32 +02:00
|
|
|
handle: SocketHandle,
|
2022-07-28 10:25:47 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> UdpSocket<'a> {
|
2023-05-15 00:39:57 +02:00
|
|
|
/// Create a new UDP socket using the provided stack and buffers.
|
2022-12-26 03:33:49 +01:00
|
|
|
pub fn new<D: Driver>(
|
2022-07-28 10:25:47 +02:00
|
|
|
stack: &'a Stack<D>,
|
|
|
|
rx_meta: &'a mut [PacketMetadata],
|
|
|
|
rx_buffer: &'a mut [u8],
|
|
|
|
tx_meta: &'a mut [PacketMetadata],
|
|
|
|
tx_buffer: &'a mut [u8],
|
|
|
|
) -> Self {
|
2022-12-03 00:56:16 +01:00
|
|
|
let s = &mut *stack.socket.borrow_mut();
|
2022-07-28 10:25:47 +02:00
|
|
|
|
|
|
|
let rx_meta: &'static mut [PacketMetadata] = unsafe { mem::transmute(rx_meta) };
|
|
|
|
let rx_buffer: &'static mut [u8] = unsafe { mem::transmute(rx_buffer) };
|
|
|
|
let tx_meta: &'static mut [PacketMetadata] = unsafe { mem::transmute(tx_meta) };
|
|
|
|
let tx_buffer: &'static mut [u8] = unsafe { mem::transmute(tx_buffer) };
|
|
|
|
let handle = s.sockets.add(udp::Socket::new(
|
|
|
|
udp::PacketBuffer::new(rx_meta, rx_buffer),
|
|
|
|
udp::PacketBuffer::new(tx_meta, tx_buffer),
|
|
|
|
));
|
|
|
|
|
|
|
|
Self {
|
2022-08-11 15:52:32 +02:00
|
|
|
stack: &stack.socket,
|
|
|
|
handle,
|
2022-07-28 10:25:47 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-15 00:39:57 +02:00
|
|
|
/// Bind the socket to a local endpoint.
|
2022-07-28 10:25:47 +02:00
|
|
|
pub fn bind<T>(&mut self, endpoint: T) -> Result<(), BindError>
|
|
|
|
where
|
|
|
|
T: Into<IpListenEndpoint>,
|
|
|
|
{
|
|
|
|
let mut endpoint = endpoint.into();
|
|
|
|
|
|
|
|
if endpoint.port == 0 {
|
|
|
|
// If user didn't specify port allocate a dynamic port.
|
2022-12-03 00:56:16 +01:00
|
|
|
endpoint.port = self.stack.borrow_mut().get_local_port();
|
2022-07-28 10:25:47 +02:00
|
|
|
}
|
|
|
|
|
2022-12-03 00:56:16 +01:00
|
|
|
match self.with_mut(|s, _| s.bind(endpoint)) {
|
2022-07-28 10:25:47 +02:00
|
|
|
Ok(()) => Ok(()),
|
|
|
|
Err(udp::BindError::InvalidState) => Err(BindError::InvalidState),
|
|
|
|
Err(udp::BindError::Unaddressable) => Err(BindError::NoRoute),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-03 00:56:16 +01:00
|
|
|
fn with<R>(&self, f: impl FnOnce(&udp::Socket, &Interface) -> R) -> R {
|
|
|
|
let s = &*self.stack.borrow();
|
2022-07-28 10:25:47 +02:00
|
|
|
let socket = s.sockets.get::<udp::Socket>(self.handle);
|
|
|
|
f(socket, &s.iface)
|
|
|
|
}
|
|
|
|
|
2022-12-03 00:56:16 +01:00
|
|
|
fn with_mut<R>(&self, f: impl FnOnce(&mut udp::Socket, &mut Interface) -> R) -> R {
|
|
|
|
let s = &mut *self.stack.borrow_mut();
|
2022-07-28 10:25:47 +02:00
|
|
|
let socket = s.sockets.get_mut::<udp::Socket>(self.handle);
|
|
|
|
let res = f(socket, &mut s.iface);
|
|
|
|
s.waker.wake();
|
|
|
|
res
|
|
|
|
}
|
|
|
|
|
2023-05-15 00:39:57 +02:00
|
|
|
/// Receive a datagram.
|
|
|
|
///
|
|
|
|
/// This method will wait until a datagram is received.
|
|
|
|
///
|
|
|
|
/// Returns the number of bytes received and the remote endpoint.
|
2022-08-11 15:52:32 +02:00
|
|
|
pub async fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, IpEndpoint), Error> {
|
2023-07-12 11:32:02 +02:00
|
|
|
poll_fn(move |cx| self.poll_recv_from(buf, cx)).await
|
|
|
|
}
|
|
|
|
|
2023-07-12 11:32:02 +02:00
|
|
|
/// Receive a datagram.
|
2023-07-12 11:32:02 +02:00
|
|
|
///
|
2023-07-12 11:32:02 +02:00
|
|
|
/// When no datagram is available, this method will return `Poll::Pending` and
|
|
|
|
/// register the current task to be notified when a datagram is received.
|
2023-07-12 11:32:02 +02:00
|
|
|
///
|
2023-07-12 11:32:02 +02:00
|
|
|
/// When a datagram is received, this method will return `Poll::Ready` with the
|
|
|
|
/// number of bytes received and the remote endpoint.
|
2023-07-12 11:32:02 +02:00
|
|
|
pub fn poll_recv_from(&self, buf: &mut [u8], cx: &mut Context<'_>) -> Poll<Result<(usize, IpEndpoint), Error>> {
|
2023-07-12 11:32:02 +02:00
|
|
|
self.with_mut(|s, _| match s.recv_slice(buf) {
|
|
|
|
Ok((n, meta)) => Poll::Ready(Ok((n, meta.endpoint))),
|
|
|
|
// No data ready
|
|
|
|
Err(udp::RecvError::Exhausted) => {
|
|
|
|
s.register_recv_waker(cx.waker());
|
|
|
|
Poll::Pending
|
|
|
|
}
|
2022-07-28 10:25:47 +02:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-05-15 00:39:57 +02:00
|
|
|
/// Send a datagram to the specified remote endpoint.
|
2023-07-12 11:32:02 +02:00
|
|
|
///
|
2023-07-12 11:32:02 +02:00
|
|
|
/// This method will wait until the datagram has been sent.
|
2023-07-12 11:32:02 +02:00
|
|
|
///
|
2023-07-12 11:32:02 +02:00
|
|
|
/// When the remote endpoint is not reachable, this method will return `Err(Error::NoRoute)`
|
2022-08-11 15:52:32 +02:00
|
|
|
pub async fn send_to<T>(&self, buf: &[u8], remote_endpoint: T) -> Result<(), Error>
|
2023-07-12 11:32:02 +02:00
|
|
|
where
|
|
|
|
T: Into<IpEndpoint>,
|
|
|
|
{
|
2023-07-12 11:32:02 +02:00
|
|
|
let remote_endpoint: IpEndpoint = remote_endpoint.into();
|
2023-07-12 11:32:02 +02:00
|
|
|
poll_fn(move |cx| self.poll_send_to(buf, remote_endpoint, cx)).await
|
|
|
|
}
|
|
|
|
|
2023-07-12 11:32:02 +02:00
|
|
|
/// Send a datagram to the specified remote endpoint.
|
2023-07-12 11:32:02 +02:00
|
|
|
///
|
2023-07-12 11:32:02 +02:00
|
|
|
/// When the datagram has been sent, this method will return `Poll::Ready(Ok())`.
|
2023-07-12 11:32:02 +02:00
|
|
|
///
|
2023-07-12 11:32:02 +02:00
|
|
|
/// When the socket's send buffer is full, this method will return `Poll::Pending`
|
|
|
|
/// and register the current task to be notified when the buffer has space available.
|
2023-07-12 11:32:02 +02:00
|
|
|
///
|
2023-07-12 11:32:02 +02:00
|
|
|
/// When the remote endpoint is not reachable, this method will return `Poll::Ready(Err(Error::NoRoute))`.
|
|
|
|
pub fn poll_send_to<T>(&self, buf: &[u8], remote_endpoint: T, cx: &mut Context<'_>) -> Poll<Result<(), Error>>
|
2022-08-11 15:52:32 +02:00
|
|
|
where
|
|
|
|
T: Into<IpEndpoint>,
|
|
|
|
{
|
2023-07-12 11:32:02 +02:00
|
|
|
self.with_mut(|s, _| match s.send_slice(buf, remote_endpoint) {
|
|
|
|
// Entire datagram has been sent
|
|
|
|
Ok(()) => Poll::Ready(Ok(())),
|
|
|
|
Err(udp::SendError::BufferFull) => {
|
|
|
|
s.register_send_waker(cx.waker());
|
|
|
|
Poll::Pending
|
|
|
|
}
|
2023-09-10 20:13:56 +02:00
|
|
|
Err(udp::SendError::Unaddressable) => {
|
|
|
|
// If no sender/outgoing port is specified, there is not really "no route"
|
|
|
|
if s.endpoint().port == 0 {
|
|
|
|
Poll::Ready(Err(Error::SocketNotBound))
|
|
|
|
} else {
|
|
|
|
Poll::Ready(Err(Error::NoRoute))
|
|
|
|
}
|
|
|
|
}
|
2022-07-28 10:25:47 +02:00
|
|
|
})
|
|
|
|
}
|
2022-08-11 15:52:32 +02:00
|
|
|
|
2023-05-15 00:39:57 +02:00
|
|
|
/// Returns the local endpoint of the socket.
|
2022-08-11 15:52:32 +02:00
|
|
|
pub fn endpoint(&self) -> IpListenEndpoint {
|
2022-12-03 00:56:16 +01:00
|
|
|
self.with(|s, _| s.endpoint())
|
2022-08-11 15:52:32 +02:00
|
|
|
}
|
|
|
|
|
2023-05-15 00:39:57 +02:00
|
|
|
/// Returns whether the socket is open.
|
|
|
|
|
2022-08-11 15:52:32 +02:00
|
|
|
pub fn is_open(&self) -> bool {
|
2022-12-03 00:56:16 +01:00
|
|
|
self.with(|s, _| s.is_open())
|
2022-08-11 15:52:32 +02:00
|
|
|
}
|
|
|
|
|
2023-05-15 00:39:57 +02:00
|
|
|
/// Close the socket.
|
2022-08-11 15:52:32 +02:00
|
|
|
pub fn close(&mut self) {
|
2022-12-03 00:56:16 +01:00
|
|
|
self.with_mut(|s, _| s.close())
|
2022-08-11 15:52:32 +02:00
|
|
|
}
|
|
|
|
|
2023-05-15 00:39:57 +02:00
|
|
|
/// Returns whether the socket is ready to send data, i.e. it has enough buffer space to hold a packet.
|
2022-08-11 15:52:32 +02:00
|
|
|
pub fn may_send(&self) -> bool {
|
2022-12-03 00:56:16 +01:00
|
|
|
self.with(|s, _| s.can_send())
|
2022-08-11 15:52:32 +02:00
|
|
|
}
|
|
|
|
|
2023-05-15 00:39:57 +02:00
|
|
|
/// Returns whether the socket is ready to receive data, i.e. it has received a packet that's now in the buffer.
|
2022-08-11 15:52:32 +02:00
|
|
|
pub fn may_recv(&self) -> bool {
|
2022-12-03 00:56:16 +01:00
|
|
|
self.with(|s, _| s.can_recv())
|
2022-08-11 15:52:32 +02:00
|
|
|
}
|
2023-08-15 16:24:58 +02:00
|
|
|
|
|
|
|
/// Return the maximum number packets the socket can receive.
|
|
|
|
pub fn packet_recv_capacity(&self) -> usize {
|
|
|
|
self.with(|s, _| s.packet_recv_capacity())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the maximum number packets the socket can receive.
|
|
|
|
pub fn packet_send_capacity(&self) -> usize {
|
|
|
|
self.with(|s, _| s.packet_send_capacity())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the maximum number of bytes inside the recv buffer.
|
|
|
|
pub fn payload_recv_capacity(&self) -> usize {
|
|
|
|
self.with(|s, _| s.payload_recv_capacity())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the maximum number of bytes inside the transmit buffer.
|
|
|
|
pub fn payload_send_capacity(&self) -> usize {
|
|
|
|
self.with(|s, _| s.payload_send_capacity())
|
|
|
|
}
|
2022-08-11 15:52:32 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Drop for UdpSocket<'_> {
|
|
|
|
fn drop(&mut self) {
|
2022-12-03 00:56:16 +01:00
|
|
|
self.stack.borrow_mut().sockets.remove(self.handle);
|
2022-08-11 15:52:32 +02:00
|
|
|
}
|
2022-07-28 10:25:47 +02:00
|
|
|
}
|