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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

use super::*;

/// Seed combinator used for creating send descriptors for CoAP requests.
#[derive(Debug)]
pub enum CoapRequest {}

impl CoapRequest {
    /// Constructs a simple GET send descriptor.
    ///
    /// The generic parameter `IC` can (for the most part) be ignored: the type will be
    /// inferred when the send descriptor is passed to [`LocalEndpoint::send`] (or one of its
    /// [many][RemoteEndpoint::send_to] [variants][RemoteEndpoint::send]).
    #[inline(always)]
    pub fn get<IC>() -> SendGet<IC> {
        Default::default()
    }

    /// Constructs a simple GET send descriptor configured for observing.
    ///
    /// The generic parameter `IC` can (for the most part) be ignored: the type will be
    /// inferred when the send descriptor is passed to [`LocalEndpointExt::send_as_stream`] (or
    /// one of its [many][RemoteEndpointExt::send_to_as_stream]
    /// [variants][RemoteEndpointExt::send_as_stream]).
    #[inline(always)]
    pub fn observe<IC>() -> SendObserve<IC> {
        Default::default()
    }

    /// Constructs a simple POST send descriptor.
    ///
    /// The generic parameter `IC` can (for the most part) be ignored: the type will be
    /// inferred when the send descriptor is passed to [`LocalEndpoint::send`] (or one of its
    /// [many][RemoteEndpoint::send_to] [variants][RemoteEndpoint::send]).
    #[inline(always)]
    pub fn post<IC>() -> SendPost<IC> {
        Default::default()
    }

    /// Constructs a simple PUT send descriptor.
    ///
    /// The generic parameter `IC` can (for the most part) be ignored: the type will be
    /// inferred when the send descriptor is passed to [`LocalEndpoint::send`] (or one of its
    /// [many][RemoteEndpoint::send_to] [variants][RemoteEndpoint::send]).
    #[inline(always)]
    pub fn put<IC>() -> SendPut<IC> {
        Default::default()
    }

    /// Constructs a simple DELETE send descriptor.
    ///
    /// The generic parameter `IC` can (for the most part) be ignored: the type will be
    /// inferred when the send descriptor is passed to [`LocalEndpoint::send`] (or one of its
    /// [many][RemoteEndpoint::send_to] [variants][RemoteEndpoint::send]).
    #[inline(always)]
    pub fn delete<IC>() -> SendDelete<IC> {
        Default::default()
    }

    /// Constructs a simple send descriptor with an arbitrary CoAP method code.
    ///
    /// The value of `msg_code` is checked in debug mode to ensure it is a CoAP method.
    /// The value is not checked in release mode.
    ///
    /// The generic parameter `IC` can (for the most part) be ignored: the type will be
    /// inferred when the send descriptor is passed to [`LocalEndpoint::send`] (or one of its
    /// [many][RemoteEndpoint::send_to] [variants][RemoteEndpoint::send]).
    #[inline(always)]
    pub fn method<IC>(msg_code: MsgCode) -> CoapRequestMethod<IC> {
        debug_assert!(msg_code.is_method(), "{:?} is not a method", msg_code);
        CoapRequestMethod {
            msg_code,
            phantom: PhantomData,
        }
    }
}

macro_rules! send_desc_def_method {
    ($(#[$tags:meta])* $name:ident, $code:expr, $handler:expr) => {
        $(#[$tags])*
        #[derive(Debug)]
        pub struct $ name < IC > (PhantomData < IC > );
        send_desc_def_method!(@rest ($name,$code,$handler));
    };
    ($name:ident, $code:expr, $handler:expr) => {
        pub struct $ name < IC > (PhantomData < IC > );
        send_desc_def_method!(@rest ($name,$code,$handler));
    };
    (@rest ($name:ident, $code:expr, $handler:expr)) => {
        impl<IC> SendDescUnicast for $name<IC> {}

        impl<IC> Default for $name<IC> {
            #[inline(always)]
            fn default() -> Self {
                Self(PhantomData)
            }
        }

        impl<IC> $name<IC> {
            /// Returns a nonconfirmable version of this send descriptor.
            #[inline(always)]
            pub fn nonconfirmable(self) -> Nonconfirmable<$name<IC>> {
                Nonconfirmable(self)
            }

            /// Returns a multicast version of this send descriptor.
            #[inline(always)]
            pub fn multicast(self) -> Multicast<$name<IC>> {
                Multicast(self)
            }
        }

        impl<IC: InboundContext> SendDesc<IC, ()> for $name<IC> {
            fn write_options(
                &self,
                _msg: &mut dyn OptionInsert,
                _socket_addr: &IC::SocketAddr,
                _start: Bound<OptionNumber>,
                _end: Bound<OptionNumber>,
            ) -> Result<(), Error> {
                Ok(())
            }

            fn write_payload(
                &self,
                msg: &mut dyn MessageWrite,
                _socket_addr: &IC::SocketAddr,
            ) -> Result<(), Error> {
                msg.set_msg_code($code);
                Ok(())
            }

            fn handler(
                &mut self,
                context: Result<&IC, Error>,
            ) -> Result<ResponseStatus<()>, Error> {
                let context = context?;

                if context.is_dupe() {
                    // Ignore dupes.
                    return Ok(ResponseStatus::Continue);
                }

                let code = context.message().msg_code();
                ($handler)(code)
            }
        }
    };
}

send_desc_def_method!(
    /// Send descriptor created by [`CoapRequest::get`] used for sending CoAP GET requests.
    SendGet,
    MsgCode::MethodGet,
    |code| {
        match code {
            MsgCode::SuccessContent | MsgCode::SuccessValid => Ok(ResponseStatus::Done(())),
            MsgCode::ClientErrorNotFound => Err(Error::ResourceNotFound),
            MsgCode::ClientErrorForbidden => Err(Error::Forbidden),
            MsgCode::ClientErrorUnauthorized => Err(Error::Unauthorized),
            code if code.is_client_error() => Err(Error::ClientRequestError),
            _ => Err(Error::ServerError),
        }
    }
);

send_desc_def_method!(
    /// Send descriptor created by [`CoapRequest::put`] used for sending CoAP PUT requests.
    SendPut,
    MsgCode::MethodPut,
    |code| {
        match code {
            MsgCode::SuccessCreated | MsgCode::SuccessChanged | MsgCode::SuccessValid => {
                Ok(ResponseStatus::Done(()))
            }
            MsgCode::ClientErrorNotFound => Err(Error::ResourceNotFound),
            MsgCode::ClientErrorForbidden => Err(Error::Forbidden),
            MsgCode::ClientErrorUnauthorized => Err(Error::Unauthorized),
            code if code.is_client_error() => Err(Error::ClientRequestError),
            _ => Err(Error::ServerError),
        }
    }
);

send_desc_def_method!(
    /// Send descriptor created by [`CoapRequest::post`] used for sending CoAP POST requests.
    SendPost,
    MsgCode::MethodPost,
    |code| {
        match code {
            code if code.is_success() => Ok(ResponseStatus::Done(())),
            MsgCode::ClientErrorNotFound => Err(Error::ResourceNotFound),
            MsgCode::ClientErrorForbidden => Err(Error::Forbidden),
            MsgCode::ClientErrorUnauthorized => Err(Error::Unauthorized),
            code if code.is_client_error() => Err(Error::ClientRequestError),
            _ => Err(Error::ServerError),
        }
    }
);

send_desc_def_method!(
    /// Send descriptor created by [`CoapRequest::delete`] used for sending CoAP DELETE requests.
    SendDelete,
    MsgCode::MethodDelete,
    |code| {
        match code {
            MsgCode::SuccessDeleted => Ok(ResponseStatus::Done(())),
            MsgCode::ClientErrorNotFound => Err(Error::ResourceNotFound),
            MsgCode::ClientErrorForbidden => Err(Error::Forbidden),
            MsgCode::ClientErrorUnauthorized => Err(Error::Unauthorized),
            code if code.is_client_error() => Err(Error::ClientRequestError),
            _ => Err(Error::ServerError),
        }
    }
);

/// Send descriptor created by [`CoapRequest::method`] used for sending CoAP requests with a
/// programmatically defined method.
#[derive(Debug)]
pub struct CoapRequestMethod<IC> {
    msg_code: MsgCode,
    phantom: PhantomData<IC>,
}

impl<IC> SendDescUnicast for CoapRequestMethod<IC> {}

impl<IC> CoapRequestMethod<IC> {
    /// Returns a nonconfirmable version of this send descriptor.
    #[inline(always)]
    pub fn nonconfirmable(self) -> Nonconfirmable<CoapRequestMethod<IC>> {
        Nonconfirmable(self)
    }

    /// Returns a multicast version of this send descriptor.
    #[inline(always)]
    pub fn multicast(self) -> Multicast<CoapRequestMethod<IC>> {
        Multicast(self)
    }
}

impl<IC> SendDesc<IC, ()> for CoapRequestMethod<IC>
where
    IC: InboundContext,
{
    fn write_options(
        &self,
        _msg: &mut dyn OptionInsert,
        _socket_addr: &IC::SocketAddr,
        _start: Bound<OptionNumber>,
        _end: Bound<OptionNumber>,
    ) -> Result<(), Error> {
        Ok(())
    }

    fn write_payload(
        &self,
        msg: &mut dyn MessageWrite,
        _socket_addr: &IC::SocketAddr,
    ) -> Result<(), Error> {
        msg.set_msg_code(self.msg_code);
        Ok(())
    }

    fn handler(&mut self, context: Result<&IC, Error>) -> Result<ResponseStatus<()>, Error> {
        let context = context?;

        if context.is_dupe() {
            // Ignore dupes.
            return Ok(ResponseStatus::Continue);
        }

        let code = context.message().msg_code();

        match code {
            code if code.is_success() => Ok(ResponseStatus::Done(())),
            MsgCode::ClientErrorNotFound => Err(Error::ResourceNotFound),
            MsgCode::ClientErrorForbidden => Err(Error::Forbidden),
            MsgCode::ClientErrorUnauthorized => Err(Error::Unauthorized),
            code if code.is_client_error() => Err(Error::ClientRequestError),
            _ => Err(Error::ServerError),
        }
    }
}