The nRF Connect SDK provides the CoAP library, which is Zephyr’s implementation of the CoAP standard. The library supports both the server and client roles and is highly configurable.
The library is implemented using plain buffers, meaning the user must create the sockets for communication and then pass these to the library. This is similar to what we did in Lesson 3 Exercise 1.
Enable the CoAP library in your application by enabling the following Kconfig in the prj.conf
file.
CONFIG_COAP=y
KconfigInclude the header file for the CoAP library in your source code.
#include <zephyr/net/coap.h>
CCreate a CoAP packet message of type struct coap_packet
, using coap_packet_init()
which has the following signature:
cpkt
– Packet to be initialized, of type struct coap_packet
data
– Data can contain CoAP packet information to be used as input datamax_len
– length of data
ver
– CoAP header version, currently the value 1
.type
– CoAP header type, specified in enum coap_msgtype
. token_len
– length of token
token
– CoAP header tokencode
– CoAP header code, specified in enum coap_method
.id
– CoAP header message IDYou can add options to the CoAP packet using coap_packet_append_option()
, which has the following signature
cpkt
– Packet to be updatedcode
– Code for the packet option, see enum coap_option_num
.value
– Pointer to the value of the optionlen
– Size of data in value
Parse a received CoAP packet using coap_packet_parse()
, which has the following signature
cpkt
– Packet to be initialized, of type struct coap_packet
data
– Pointer to the CoAP packet to be parsedlen
– Length of the dataoptions
– Parse options of type struct coap_option
.opt_num
– Pass the number of options passed.When initiating a packet, we can use the function coap_next_id()
, which has the following signature
Extract the payload from a CoAP packet using coap_packet_get_payload()
, which has the following signature
Extract the token from a CoAP packet using coap_header_get_token()
, which has the following signature
Extract the code from the CoAP packet using coap_header_get_code()
, which has the following signature
We have now covered all the CoAP API functions we will be using in the exercise for this lesson. See the CoAP library documentation for the full API reference of this library.
As opposed to the MQTT Library covered in Lesson 4, the CoAP library does not natively support implementing a DTLS connection. Therefore, we will do this using the Modem key management library and the secure sockets implementation in Zephyr’s native BSD sockets API.