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
//! Simple implementations of a [coap_request::Request]
//!
//! While the [coap_request] interfaces are geared toward portability, this crate provides
//! implementations of the [coap_request::Request] trait that are easy to set up. They follow a
//! builder pattern:
//!
//! ```
//! # struct X<S: coap_request::Stack>(S);
//! # impl<S: coap_request::Stack> X<S> {
//! # fn to(self, addr: u128) -> S {
//! # panic!("Not really")
//! # }
//! # }
//! # async fn run<S: coap_request::Stack>(stack: X<S>) {
//! stack
//! .to("[2001:db8::1]:5683".parse().unwrap())
//! .request(
//! coap_request_implementations::Code::get()
//! .with_path("/.well-known/core")
//! .processing_response_payload_through(|p| println!("Data: {:?}", p)),
//! )
//! .await;
//! # }
//! ```
//!
//! ## Stability
//!
//! This crate is in an early experimental stage, do not expect these APIs to persist. (Then
//! again, the crate that needs to be stable is [coap_request], as a single stack can easily be
//! used with request builders from multiple versions of this crate).
mod builder;
mod conversions;
use coap_message::{MinimalWritableMessage, ReadableMessage};
use coap_request::{Request, Stack};
use builder::Builder;
pub use conversions::AsUriPath;
/// A request that merely sends a code, and returns successful if the returned code as successful
/// and no critical options were present.
///
/// While not terribly useful on its own, its main purpose is as the start of a builder.
pub struct Code {
code: u8,
}
/// A request that sets a request Uri-Path.
///
/// This is based on a [Code], and built in [Code::with_path].
pub struct WithPath<S: Stack + ?Sized, Prev: Builder<S>, P: AsUriPath> {
previous: Prev,
path: P,
_phantom: core::marker::PhantomData<S>,
}
/// A request into which the user can populate a custom payload.
pub struct WritingRequest<S: Stack + ?Sized, Prev: Builder<S>, F>
where
F: Fn(&mut S::RequestMessage<'_>),
{
previous: Prev,
f: F,
_phantom: core::marker::PhantomData<S>,
}
/// A request that runs a user provided closure to read the response message's payload.
///
/// This is based on a [WithPath], and built in [WithPath::processing_response_payload_through].
// FIXME: Can we easily build this with an async closure as well? So far this has failed with
// lifetime trouble when
// F: for<'a> FnOnce(&'a [u8]) -> FO,
// for<'a> FO: core::future::Future<Output = O>,
// because we couldn't make the FO be 'a (even though it could be from its definition) and thus
// prolong 'a to its drop time.
pub struct ProcessingResponse<S: Stack + ?Sized, Prev: Builder<S, Output = Result<(), ()>>, O, F>
where
F: for<'a> FnOnce(&'a [u8]) -> O,
{
previous: Prev,
/// When this is None, a response has already been processed -- this does not expect multiple
/// responses.
f: Option<F>,
_phantom: core::marker::PhantomData<S>,
}
macro_rules! code_macro {
($l:ident, $u:ident) => {
#[doc=concat!("A request sending the ", stringify!($u), " code")]
pub fn $l() -> Self {
Self {
code: coap_numbers::code::$u,
}
}
};
}
impl Code {
code_macro!(get, GET);
code_macro!(post, POST);
code_macro!(put, PUT);
code_macro!(delete, DELETE);
code_macro!(fetch, FETCH);
code_macro!(patch, PATCH);
code_macro!(ipatch, IPATCH);
/// Set the Uri-Path options on a request.
pub fn with_path<S: Stack + ?Sized, P: conversions::AsUriPath>(
self,
path: P,
) -> WithPath<S, Self, P> {
WithPath {
previous: self,
path,
_phantom: Default::default(),
}
}
}
impl<S: Stack + ?Sized, Prev: Builder<S, Output = Result<(), ()>>, P: conversions::AsUriPath>
WithPath<S, Prev, P>
{
/// Set the request payload in a user callback.
///
/// ## Caveats
///
/// Note that while the user may do all sorts of writes to the request message, they better
/// stick to writing to the payload (for other uses might lead to panics).
///
/// Also, it is not sure whether this can actualy be used without ICEing (testing WIP).
pub fn with_request_payload<F>(self, f: F) -> WritingRequest<S, Self, F>
where
F: Fn(&mut S::RequestMessage<'_>),
{
WritingRequest {
previous: self,
f,
_phantom: Default::default(),
}
}
/// Provide the response payload to a user callback.
pub fn processing_response_payload_through<O, F>(
self,
f: F,
) -> ProcessingResponse<S, Self, O, F>
where
F: for<'a> FnOnce(&'a [u8]) -> O,
{
ProcessingResponse {
previous: self,
f: Some(f),
_phantom: Default::default(),
}
}
}
impl<S: Stack + ?Sized> Request<S> for Code {
type Carry = ();
type Output = Result<(), ()>;
async fn build_request(&mut self, req: &mut S::RequestMessage<'_>) {
req.set_code(
self.code
.try_into()
.ok()
.expect("Code can not be expressed"),
);
}
async fn process_response(&mut self, res: &S::ResponseMessage<'_>, _carry: ()) -> Self::Output {
let code: u8 = res.code().into();
use coap_numbers::code::{classify, Class, Range};
if !matches!(classify(code), Range::Response(Class::Success)) {
// This encompasses both unsuccessful responses and errors that the stack let through
// (it should have rejected them)
return Err(());
}
use coap_handler_implementations::option_processing::OptionsExt;
res.options().ignore_elective_others().map_err(|_| ())
}
}
impl<S: Stack + ?Sized> Builder<S> for Code {}
impl<S: Stack + ?Sized, Prev: Builder<S>, P: conversions::AsUriPath> Request<S>
for WithPath<S, Prev, P>
{
type Carry = Prev::Carry;
type Output = Prev::Output;
async fn build_request(&mut self, req: &mut S::RequestMessage<'_>) -> Self::Carry {
// FIXME: This is just `self.previous.build_request(req).await`; let's see if having M1/M2
// in the trait pays off elsewhere, otherwise the need to be this explicit here is
// horrible. (It looked even worse when we had M1 and M2)
let carry = <_ as coap_request::Request<S>>::build_request(&mut self.previous, req).await;
for p in self.path.as_uri_path() {
req.add_option(
coap_numbers::option::URI_PATH.try_into().ok().unwrap(),
p.as_bytes(),
);
}
carry
}
async fn process_response(
&mut self,
res: &S::ResponseMessage<'_>,
carry: Prev::Carry,
) -> Self::Output {
<_ as coap_request::Request<S>>::process_response(&mut self.previous, res, carry).await
}
}
impl<S: Stack + ?Sized, Prev: Builder<S>, P: conversions::AsUriPath> Builder<S>
for WithPath<S, Prev, P>
{
}
impl<S: Stack + ?Sized, Prev: Builder<S>, F> Request<S> for WritingRequest<S, Prev, F>
where
F: Fn(&mut S::RequestMessage<'_>),
{
type Carry = Prev::Carry;
type Output = Prev::Output;
async fn build_request(&mut self, req: &mut S::RequestMessage<'_>) -> Self::Carry {
let carry = <_ as coap_request::Request<S>>::build_request(&mut self.previous, req).await;
(self.f)(req);
carry
}
async fn process_response(
&mut self,
res: &S::ResponseMessage<'_>,
carry: Self::Carry,
) -> Self::Output {
<_ as coap_request::Request<S>>::process_response(&mut self.previous, res, carry).await
}
}
impl<S: Stack + ?Sized, Prev: Builder<S>, F> Builder<S> for WritingRequest<S, Prev, F> where
F: Fn(&mut S::RequestMessage<'_>)
{
}
impl<S: Stack + ?Sized, Prev: Builder<S, Output = Result<(), ()>>, O, F> Request<S>
for ProcessingResponse<S, Prev, O, F>
where
F: for<'a> FnOnce(&'a [u8]) -> O,
{
type Carry = Prev::Carry;
type Output = Result<O, ()>;
async fn build_request(&mut self, req: &mut S::RequestMessage<'_>) -> Self::Carry {
<_ as coap_request::Request<S>>::build_request(&mut self.previous, req).await
}
async fn process_response(
&mut self,
res: &S::ResponseMessage<'_>,
carry: Self::Carry,
) -> Self::Output {
<_ as coap_request::Request<S>>::process_response(&mut self.previous, res, carry).await?;
if let Some(f) = self.f.take() {
Ok(f(res.payload()))
} else {
Err(())
}
}
}
impl<S: Stack + ?Sized, Prev: Builder<S, Output = Result<(), ()>>, O, F> Builder<S>
for ProcessingResponse<S, Prev, O, F>
where
F: for<'a> FnOnce(&'a [u8]) -> O,
{
}