[![Build Status](https://gitlab.com/chrysn/coap-handler/badges/master/pipeline.svg)](https://gitlab.com/chrysn/coap-handler/commits/master)

# coap-handler

The `coap-handler` crate defines an interface between a [CoAP] server (that listens for
requests on the network and parses the messages) and request handlers (that process the
requests and creates responses from them).

The interface is generic over message formats by using the [coap-message] crate, which allows
the handler to construct the response right into the send buffer prepared by the server
implementation. By separating the request processing and the response phase, a server can be
implemented even on network stacks that have only a single network buffer.

Along with the interface, the crate provides some simple implementations, from the generic "4.04
Not Found" responder up to a handler that creates a [write] formatter for GET-only resources,
and even provides [block-wise transfer] that.
The [implementations::SimpleCBORWrapper] enables the easy creation of [serde_cbor] based
resource implementations with GET, PUT and POST support in CBOR format.
The `HandlerBuilder` implements crude static path based routing
that may suffice for some applications, and is also useful to get started quickly.

[CoAP]: https://coap.technology/
[coap-message]: https://crates.io/crates/coap-message
[write]: https://doc.rust-lang.org/core/fmt/trait.Write.html
[block-wise transfer]: https://tools.ietf.org/html/rfc7959
[serde_cbor]: https://crates.io/crates/serde_cbor

Known shortcomings of the current interface are:

* No consideration for asynchronous processing.
* Handler mutability is a bit iffy -- there's no way yet for the server to express any promise
  about only running one handler at a time, thus handlers often hold shared references to a
  [`RefCell`] that is [`borrow_mut()`]'d (if no other code that can be concurrent with the CoAP
  server can have access to the `T`), or [`try_borrow_mut()`]'d (and errs back with a 5.03
  Max-Age:0 response).

  Alternatives (where multiple handlers could be built based on a single mutable reference to
  their data) are being explored.
* Multiple responses (as, for example, in observations) are not supported.

[`RefCell`]: https://doc.rust-lang.org/core/cell/struct.RefCell.html
[`borrow_mut()`]: https://doc.rust-lang.org/core/cell/struct.RefCell.html#method.borrow_mut
[`try_borrow_mut()`]: https://doc.rust-lang.org/core/cell/struct.RefCell.html#method.try_borrow_mut


License: MIT OR Apache-2.0
