diff --git a/sys/include/net/nanocoap.h b/sys/include/net/nanocoap.h index a721ff84a9b0..46c7191ffa9e 100644 --- a/sys/include/net/nanocoap.h +++ b/sys/include/net/nanocoap.h @@ -1405,6 +1405,26 @@ ssize_t coap_build_reply(coap_pkt_t *pkt, unsigned code, */ ssize_t coap_handle_req(coap_pkt_t *pkt, uint8_t *resp_buf, unsigned resp_buf_len); +/** + * @brief Pass a coap request to a matching handler + * + * This function will try to find a matching handler in @p resources and call + * the handler. + * + * @param[in] pkt pointer to (parsed) CoAP packet + * @param[out] resp_buf buffer for response + * @param[in] resp_buf_len size of response buffer + * @param[in] resources Array of coap endpoint resources + * @param[in] resources_numof length of the coap endpoint resources + * + * @returns size of the reply packet on success + * @returns <0 on error + */ +ssize_t coap_tree_handler(coap_pkt_t *pkt, uint8_t *resp_buf, + unsigned resp_buf_len, + const coap_resource_t *resources, + size_t resources_numof); + /** * @brief Convert message code (request method) into a corresponding bit field * diff --git a/sys/net/application_layer/nanocoap/nanocoap.c b/sys/net/application_layer/nanocoap/nanocoap.c index 5c2353c401a3..2c23f4d3f1bc 100644 --- a/sys/net/application_layer/nanocoap/nanocoap.c +++ b/sys/net/application_layer/nanocoap/nanocoap.c @@ -384,7 +384,15 @@ ssize_t coap_handle_req(coap_pkt_t *pkt, uint8_t *resp_buf, unsigned resp_buf_le if (pkt->hdr->code == 0) { return coap_build_reply(pkt, COAP_CODE_EMPTY, resp_buf, resp_buf_len, 0); } + return coap_tree_handler(pkt, resp_buf, resp_buf_len, coap_resources, + coap_resources_numof); +} +ssize_t coap_tree_handler(coap_pkt_t *pkt, uint8_t *resp_buf, + unsigned resp_buf_len, + const coap_resource_t *resources, + size_t resources_numof) +{ coap_method_flags_t method_flag = coap_method2flag(coap_get_code_detail(pkt)); uint8_t uri[NANOCOAP_URI_MAX]; @@ -393,8 +401,8 @@ ssize_t coap_handle_req(coap_pkt_t *pkt, uint8_t *resp_buf, unsigned resp_buf_le } DEBUG("nanocoap: URI path: \"%s\"\n", uri); - for (unsigned i = 0; i < coap_resources_numof; i++) { - const coap_resource_t *resource = &coap_resources[i]; + for (unsigned i = 0; i < resources_numof; i++) { + const coap_resource_t *resource = &resources[i]; if (!(resource->methods & method_flag)) { continue; }