1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
mod meta;
mod ref_;
mod ring_buffer;
mod set;
pub mod tcp;
pub mod udp;

pub(crate) use self::meta::Meta as SocketMeta;
pub use self::ring_buffer::RingBuffer;
use embedded_nal::SocketAddr;
use heapless::ArrayLength;

#[cfg(feature = "socket-tcp")]
pub use tcp::{State as TcpState, TcpSocket};
#[cfg(feature = "socket-udp")]
pub use udp::{State as UdpState, UdpSocket};

pub use self::set::{ChannelId, Handle as SocketHandle, Item as SocketSetItem, Set as SocketSet};

pub use self::ref_::Ref as SocketRef;
pub(crate) use self::ref_::Session as SocketSession;

/// The error type for the networking stack.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, defmt::Format)]
pub enum Error {
    /// An operation cannot proceed because a buffer is empty or full.
    Exhausted,
    /// An operation is not permitted in the current state.
    Illegal,
    /// An endpoint or address of a remote host could not be translated to a lower level address.
    /// E.g. there was no an Ethernet address corresponding to an IPv4 address in the ARP cache,
    /// or a TCP connection attempt was made to an unspecified endpoint.
    Unaddressable,

    SocketSetFull,
    InvalidSocket,
}

type Result<T> = core::result::Result<T, Error>;

/// A network socket.
///
/// This enumeration abstracts the various types of sockets based on the IP protocol.
/// To downcast a `Socket` value to a concrete socket, use the [AnySocket] trait,
/// e.g. to get `UdpSocket`, call `UdpSocket::downcast(socket)`.
///
/// It is usually more convenient to use [SocketSet::get] instead.
///
/// [AnySocket]: trait.AnySocket.html
/// [SocketSet::get]: struct.SocketSet.html#method.get
#[non_exhaustive]
pub enum Socket<L: ArrayLength<u8>> {
    // #[cfg(feature = "socket-raw")]
    // Raw(RawSocket<'a, 'b>),
    // #[cfg(all(
    //     feature = "socket-icmp",
    //     any(feature = "proto-ipv4", feature = "proto-ipv6")
    // ))]
    // Icmp(IcmpSocket<'a, 'b>),
    #[cfg(feature = "socket-udp")]
    Udp(UdpSocket<L>),
    #[cfg(feature = "socket-tcp")]
    Tcp(TcpSocket<L>),
}

#[non_exhaustive]
#[derive(Debug)]
pub enum SocketType {
    Udp,
    Tcp,
}

impl<L: ArrayLength<u8>> Socket<L> {
    pub fn get_type(&self) -> SocketType {
        match self {
            Socket::Tcp(_) => SocketType::Tcp,
            Socket::Udp(_) => SocketType::Udp,
        }
    }
}

macro_rules! dispatch_socket {
    ($self_:expr, |$socket:ident| $code:expr) => {
        dispatch_socket!(@inner $self_, |$socket| $code);
    };
    (mut $self_:expr, |$socket:ident| $code:expr) => {
        dispatch_socket!(@inner mut $self_, |$socket| $code);
    };
    (@inner $( $mut_:ident )* $self_:expr, |$socket:ident| $code:expr) => {
        match *$self_ {
            // #[cfg(feature = "socket-raw")]
            // Socket::Raw(ref $( $mut_ )* $socket) => $code,
            // #[cfg(all(feature = "socket-icmp", any(feature = "proto-ipv4", feature = "proto-ipv6")))]
            // Socket::Icmp(ref $( $mut_ )* $socket) => $code,
            #[cfg(feature = "socket-udp")]
            Socket::Udp(ref $( $mut_ )* $socket) => $code,
            #[cfg(feature = "socket-tcp")]
            Socket::Tcp(ref $( $mut_ )* $socket) => $code,
        }
    };
}

impl<L: ArrayLength<u8>> Socket<L> {
    /// Return the socket handle.
    #[inline]
    pub fn handle(&self) -> SocketHandle {
        self.meta().handle
    }

    /// Return the socket channel id.
    #[inline]
    pub fn channel_id(&self) -> ChannelId {
        self.meta().channel_id
    }

    pub(crate) fn meta(&self) -> &SocketMeta {
        dispatch_socket!(self, |socket| &socket.meta)
    }

    pub(crate) fn endpoint(&self) -> &SocketAddr {
        dispatch_socket!(self, |socket| &socket.endpoint)
    }

    // pub(crate) fn meta_mut(&mut self) -> &mut SocketMeta {
    //     dispatch_socket!(mut self, |socket| &mut socket.meta)
    // }
}

impl<L: ArrayLength<u8>> SocketSession for Socket<L> {
    fn finish(&mut self) {
        dispatch_socket!(mut self, |socket| socket.finish())
    }
}

/// A conversion trait for network sockets.
pub trait AnySocket<L: ArrayLength<u8>>: SocketSession + Sized {
    fn downcast(socket_ref: SocketRef<'_, Socket<L>>) -> Result<SocketRef<'_, Self>>;
}

/// A trait for setting a value to a known state.
///
/// In-place analog of Default.
pub trait Resettable {
    fn reset(&mut self);
}

macro_rules! from_socket {
    ($socket:ty, $variant:ident) => {
        impl<L: ArrayLength<u8>> AnySocket<L> for $socket {
            fn downcast(ref_: SocketRef<'_, Socket<L>>) -> Result<SocketRef<'_, Self>> {
                match SocketRef::into_inner(ref_) {
                    Socket::$variant(ref mut socket) => Ok(SocketRef::new(socket)),
                    _ => Err(Error::Illegal),
                }
            }
        }
    };
}

// #[cfg(feature = "socket-raw")]
// from_socket!(RawSocket, Raw);
// #[cfg(all(
//     feature = "socket-icmp",
//     any(feature = "proto-ipv4", feature = "proto-ipv6")
// ))]
// from_socket!(IcmpSocket, Icmp);
#[cfg(feature = "socket-udp")]
from_socket!(UdpSocket<L>, Udp);
#[cfg(feature = "socket-tcp")]
from_socket!(TcpSocket<L>, Tcp);