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 298 299 300 301 302 303 304
use kwap_common::Array;
use kwap_msg::{EnumerateOptNumbers, Message, Opt, OptNumber, Payload, TryIntoBytes, Type};
use crate::ToCoapValue;
/// Request methods
pub mod method;
#[doc(inline)]
pub use method::Method;
/// Request builder
pub mod builder;
#[doc(inline)]
pub use builder::*;
use crate::config::{self, Config};
/// A CoAP request
///
/// ```
/// use kwap::config::Std;
/// use kwap::req::Req;
/// use kwap::resp::Resp;
///
/// # main();
/// fn main() {
/// let client = Client::new();
/// let mut req = Req::<Std>::post("coap://myfunnyserver.com", 5632, "hello");
/// req.set_payload("john".bytes());
///
/// let resp = client.send(req);
/// let resp_body = resp.payload_string().unwrap();
/// assert_eq!(resp_body, "Hello, john!".to_string())
/// }
///
/// struct Client {
/// // clienty things
/// # __field: (),
/// }
///
/// impl Client {
/// fn new() -> Self {
/// // create a new client
/// # Self {__field: ()}
/// }
///
/// fn send(&self, req: Req<Std>) -> Resp<Std> {
/// // send the request
/// # let body = req.payload_str().unwrap().to_string();
/// # let mut resp = Resp::for_request(req);
/// # resp.set_payload(format!("Hello, {}!", body).bytes());
/// # resp
/// }
/// }
/// ```
#[derive(Debug, Clone)]
pub struct Req<Cfg: Config> {
pub(crate) msg: config::Message<Cfg>,
opts: Option<Cfg::OptMap>,
}
impl<Cfg: Config> Req<Cfg> {
fn new(method: Method, host: impl AsRef<str>, port: u16, path: impl AsRef<str>) -> Self {
let msg = Message { ty: Type::Con,
ver: Default::default(),
code: method.0,
id: crate::generate_id(),
opts: Default::default(),
payload: Payload(Default::default()),
token: crate::generate_token() };
let mut me = Self { msg,
opts: Default::default() };
fn strbytes<'a, S: AsRef<str> + 'a>(s: &'a S) -> impl Iterator<Item = u8> + 'a {
s.as_ref().as_bytes().iter().copied()
}
// Uri-Host
me.set_option(3, strbytes(&host));
// Uri-Port
me.set_option(7, port.to_be_bytes());
// Uri-Path
me.set_option(11, strbytes(&path));
me
}
/// Get the request method
pub fn method(&self) -> Method {
Method(self.msg.code)
}
/// Get the request type (confirmable, non-confirmable)
pub fn msg_type(&self) -> kwap_msg::Type {
self.msg.ty
}
/// Set this request to be non-confirmable
///
/// Some messages do not require an acknowledgement.
///
/// This is particularly true for messages that are repeated regularly for
/// application requirements, such as repeated readings from a sensor.
pub fn non(&mut self) -> () {
self.msg.ty = Type::Non;
}
/// Get a copy of the message id for this request
///
/// ```
/// use kwap::config::Std;
/// use kwap::req::Req;
///
/// let req = Req::<Std>::get("1.1.1.1", 5683, "/hello");
/// let _msg_id = req.msg_id();
/// ```
pub fn msg_id(&self) -> kwap_msg::Id {
self.msg.id
}
/// Get a copy of the message token for this request
pub fn msg_token(&self) -> kwap_msg::Token {
self.msg.token
}
/// Add a custom option to this request
///
/// If there was no room in the collection, returns the arguments back as `Some(number, value)`.
/// Otherwise, returns `None`.
///
/// ```
/// use kwap::config::Std;
/// use kwap::req::Req;
///
/// let mut req = Req::<Std>::get("1.1.1.1", 5683, "/hello");
/// req.set_option(17, Some(50)); // Accept: application/json
/// ```
pub fn set_option<V: IntoIterator<Item = u8>>(&mut self, number: u32, value: V) -> Option<(u32, V)> {
if self.opts.is_none() {
self.opts = Some(Default::default());
}
crate::option::add(self.opts.as_mut().unwrap(), false, number, value)
}
/// Add an instance of a repeatable option to the request.
pub fn add_option<V: IntoIterator<Item = u8>>(&mut self, number: u32, value: V) -> Option<(u32, V)> {
if self.opts.is_none() {
self.opts = Some(Default::default());
}
crate::option::add(self.opts.as_mut().unwrap(), true, number, value)
}
/// Creates a new GET request
///
/// ```
/// use kwap::config::Std;
/// use kwap::req::Req;
///
/// let _req = Req::<Std>::get("1.1.1.1", 5683, "/hello");
/// ```
pub fn get(host: impl AsRef<str>, port: u16, path: impl AsRef<str>) -> Self {
Self::new(Method::GET, host, port, path)
}
/// Creates a new POST request
///
/// ```
/// use kwap::config::Std;
/// use kwap::req::Req;
///
/// let mut req = Req::<Std>::post("1.1.1.1", 5683, "/hello");
/// req.set_payload("Hi!".bytes());
/// ```
pub fn post(host: impl AsRef<str>, port: u16, path: impl AsRef<str>) -> Self {
Self::new(Method::POST, host, port, path)
}
/// Creates a new PUT request
///
/// ```
/// use kwap::config::Std;
/// use kwap::req::Req;
///
/// let mut req = Req::<Std>::put("1.1.1.1", 5683, "/hello");
/// req.set_payload("Hi!".bytes());
/// ```
pub fn put(host: impl AsRef<str>, port: u16, path: impl AsRef<str>) -> Self {
Self::new(Method::PUT, host, port, path)
}
/// Creates a new DELETE request
///
/// ```
/// use kwap::config::Std;
/// use kwap::req::Req;
///
/// let _req = Req::<Std>::delete("1.1.1.1", 5683, "/users/john");
/// ```
pub fn delete(host: impl AsRef<str>, port: u16, path: impl AsRef<str>) -> Self {
Self::new(Method::DELETE, host, port, path)
}
/// Add a payload to this request
///
/// ```
/// use kwap::config::Std;
/// use kwap::req::Req;
///
/// let mut req = Req::<Std>::put("1.1.1.1", 5683, "/hello");
/// req.set_payload("Hi!".bytes());
/// ```
pub fn set_payload<P: ToCoapValue>(&mut self, payload: P) {
self.msg.payload = Payload(payload.to_coap_value::<Cfg::PayloadBuffer>());
}
/// Get the payload's raw bytes
///
/// ```
/// use kwap::config::Std;
/// use kwap::req::Req;
///
/// let mut req = Req::<Std>::post("1.1.1.1", 5683, "/hello");
/// req.set_payload("Hi!".bytes());
///
/// assert!(req.payload().iter().copied().eq("Hi!".bytes()))
/// ```
pub fn payload(&self) -> &[u8] {
&self.msg.payload.0
}
/// Read an option by its number from the request
///
/// ```
/// use kwap::config::Std;
/// use kwap::req::Req;
///
/// let req = Req::<Std>::post("1.1.1.1", 5683, "/hello");
/// let uri_host = req.get_option(3).unwrap();
/// assert_eq!(uri_host.value.0, "1.1.1.1".bytes().collect::<Vec<_>>());
/// ```
pub fn get_option(&self, n: u32) -> Option<&Opt<Cfg::OptBytes>> {
self.opts
.as_ref()
.and_then(|opts| opts.iter().find(|(num, _)| num.0 == n).map(|(_, o)| o))
}
/// Get the payload and attempt to interpret it as an ASCII string
///
/// ```
/// use kwap::config::Std;
/// use kwap::req::Req;
///
/// let mut req = Req::<Std>::post("1.1.1.1", 5683, "/hello");
/// req.set_payload("Hi!".bytes());
///
/// assert_eq!(req.payload_str().unwrap(), "Hi!")
/// ```
pub fn payload_str(&self) -> Result<&str, core::str::Utf8Error> {
core::str::from_utf8(self.payload())
}
/// Drains the internal associated list of opt number <> opt and converts the numbers into deltas to prepare for message transmission
fn normalize_opts(&mut self) {
if let Some(opts) = Option::take(&mut self.opts) {
self.msg.opts = crate::option::normalize(opts);
}
}
/// Iterate over the options attached to this request
pub fn opts(&self) -> impl Iterator<Item = &(OptNumber, Opt<Cfg::OptBytes>)> {
self.opts.iter().flat_map(|opts| opts.iter())
}
}
impl<Cfg: Config> From<Req<Cfg>> for config::Message<Cfg> {
fn from(mut req: Req<Cfg>) -> Self {
req.normalize_opts();
req.msg
}
}
impl<Cfg: Config> TryIntoBytes for Req<Cfg> {
type Error = <config::Message<Cfg> as TryIntoBytes>::Error;
fn try_into_bytes<C: Array<Item = u8>>(self) -> Result<C, Self::Error> {
config::Message::<Cfg>::from(self).try_into_bytes()
}
}
impl<Cfg: Config> From<config::Message<Cfg>> for Req<Cfg> {
fn from(mut msg: config::Message<Cfg>) -> Self {
let opts = msg.opts.into_iter().enumerate_option_numbers().collect();
msg.opts = Default::default();
Self { msg, opts: Some(opts) }
}
}