riot_coap_handler_demos/
stdio.rsuse riot_wrappers::stdio::{println, Stdio};
use coap_message::{Code, MinimalWritableMessage, MutableWritableMessage, ReadableMessage};
use coap_message_utils::{Error, OptionsExt};
struct Write;
impl coap_handler::Handler for Write {
type RequestData = ();
type ExtractRequestError = Error;
type BuildResponseError<M: MinimalWritableMessage> = M::UnionError;
fn extract_request_data<M: ReadableMessage>(
&mut self,
request: &M,
) -> Result<Self::RequestData, Error> {
if request.code().into() != coap_numbers::code::POST {
return Err(Error::method_not_allowed());
}
request.options().ignore_elective_others()?;
let payload = core::str::from_utf8(request.payload())
.map_err(|ue| Error::bad_request_with_rbep(ue.valid_up_to()))?;
println!("{}", payload);
Ok(())
}
fn estimate_length(&mut self, _request: &Self::RequestData) -> usize {
1
}
fn build_response<M: MutableWritableMessage>(
&mut self,
response: &mut M,
_request: (),
) -> Result<(), M::UnionError> {
response.set_code(Code::new(coap_numbers::code::CHANGED)?);
Ok(())
}
}
struct Read;
impl coap_handler::Handler for Read {
type RequestData = ();
type ExtractRequestError = Error;
type BuildResponseError<M: MinimalWritableMessage> = M::UnionError;
fn extract_request_data<M: ReadableMessage>(&mut self, request: &M) -> Result<(), Error> {
if request.code().into() != coap_numbers::code::POST {
return Err(Error::method_not_allowed());
}
request.options().ignore_elective_others()?;
Ok(())
}
fn estimate_length(&mut self, _request: &Self::RequestData) -> usize {
1025
}
fn build_response<M: MutableWritableMessage>(
&mut self,
response: &mut M,
_request: (),
) -> Result<(), M::UnionError> {
response.set_code(Code::new(coap_numbers::code::CHANGED)?);
let payload = response.payload_mut_with_len(1024)?;
println!("Mapped {} bytes", payload.len());
let filled = (Stdio {}).read_raw(payload).unwrap().len();
response.truncate(filled)?;
Ok(())
}
}
pub fn write() -> impl coap_handler::Handler {
Write
}
pub fn read() -> impl coap_handler::Handler {
Read
}