High-level interface to CoAP messaging. More...

Detailed Description

High-level interface to CoAP messaging.

gcoap provides a high-level interface for writing CoAP messages via RIOT's sock networking API. gcoap internalizes network event processing so an application only needs to focus on request/response handling. For a server, gcoap accepts a list of resource paths with callbacks for writing the response. For a client, gcoap provides a function to send a request, with a callback for reading the server response.

gcoap allocates a RIOT message processing thread, so a single instance can serve multiple applications. This approach also means gcoap uses a single UDP port, which supports RFC 6282 compression. Internally, gcoap depends on the nanocoap package for base level structs and functionality.

gcoap also supports the Observe extension (RFC 7641) for a server. gcoap provides functions to generate and send an observe notification that are similar to the functions to send a client request.

Contents

Server Operation

gcoap listens for requests on GCOAP_PORT, 5683 by default. You can redefine this by uncommenting the appropriate lines in gcoap's make file.

gcoap allows an application to specify a collection of request resource paths it wants to be notified about. Create an array of resources (coap_resource_t structs) ordered by the resource path, specifically the ASCII encoding of the path characters (digit and capital precede lower case). Use gcoap_register_listener() at application startup to pass in these resources, wrapped in a gcoap_listener_t. Also see Server path matching in the base nanocoap documentation.

gcoap itself defines a resource for /.well-known/core discovery, which lists all of the registered paths.

Creating a response

An application resource includes a callback function, a coap_handler_t. After reading the request, the callback must use functions provided by gcoap to format the response, as described below. The callback must read the request thoroughly before calling the functions, because the response buffer likely reuses the request buffer. See examples/gcoap/gcoap_cli.c for a simple example of a callback.

Here is the expected sequence for a callback function:

Read request completely and parse request payload, if any. Use the coap_pkt_t payload and payload_len attributes.

If there is a payload, follow the steps below.

  1. Call gcoap_resp_init() to initialize the response.
  2. Use the coap_opt_add_xxx() functions to include any Options, for example coap_opt_add_format() for Content-Format of the payload.
  3. Call coap_opt_finish() to complete the PDU metadata. Retain the returned metadata length.
  4. Write the response payload, starting at the updated payload pointer in the coap_pkt_t, for up to payload_len bytes.
  5. Return the sum of the metadata length and payload length. If some error has occurred, return a negative errno code from the handler, and gcoap will send a server error (5.00).

If no payload, call only gcoap_response() to write the full response. If you need to add Options, follow the first three steps in the list above instead.

Client Operation

Client operation includes two phases: creating and sending a request, and handling the response aynchronously in a client supplied callback. See examples/gcoap/gcoap_cli.c for a simple example of sending a request and reading the response.

Creating a request

Here is the expected sequence to prepare and send a request:

Allocate a buffer and a coap_pkt_t for the request.

If there is a payload, follow the steps below.

  1. Call gcoap_req_init() to initialize the request.
  2. Optionally, mark the request confirmable by calling coap_hdr_set_type() with COAP_TYPE_CON.
  3. Use the coap_opt_add_xxx() functions to include any Options beyond Uri-Path, which was added in the first step.
  4. Call coap_opt_finish() to complete the PDU metadata. Retain the returned metadata length.
  5. Write the request payload, starting at the updated payload pointer in the coap_pkt_t, for up to payload_len bytes.

If no payload, call only gcoap_request() to write the full request. If you need to add Options, follow the first four steps in the list above instead.

Finally, call gcoap_req_send2() with the sum of the metadata length and payload length, the destination endpoint, and a callback function for the host's response.

Handling the response

When gcoap receives the response to a request, it executes the callback from the request. gcoap also executes the callback when a response is not received within GCOAP_RESPONSE_TIMEOUT.

Here is the expected sequence for handling a response in the callback.

  1. Test for a server response or timeout in the req_state callback parameter. See the GCOAP_MEMO... constants.
  2. Test the response with coap_get_code_class() and coap_get_code_detail().
  3. Test the response payload with the coap_pkt_t payload_len and content_type attributes.
  4. Read the payload, if any.

Observe Server Operation

A CoAP client may register for Observe notifications for any resource that an application has registered with gcoap. An application does not need to take any action to support Observe client registration. However, gcoap limits registration for a given resource to a single observer.

An Observe notification is considered a response to the original client registration request. So, the Observe server only needs to create and send the notification – no further communication or callbacks are required.

Creating a notification

Here is the expected sequence to prepare and send a notification:

Allocate a buffer and a coap_pkt_t for the notification, then follow the steps below.

  1. Call gcoap_obs_init() to initialize the notification for a resource. Test the return value, which may indicate there is not an observer for the resource. If so, you are done.
  2. Use the coap_opt_add_xxx() functions to include any Options, for example coap_opt_add_format() for Content-Format of the payload.
  3. Call coap_opt_finish() to complete the PDU metadata. Retain the returned metadata length.
  4. Write the notification payload, starting at the updated payload pointer in the coap_pkt_t, for up to payload_len bytes.

Finally, call gcoap_obs_send() for the resource, with the sum of the metadata length and payload length for the representation.

Other considerations

By default, the value for the Observe option in a notification is three bytes long. For resources that change slowly, this length can be reduced via GCOAP_OBS_VALUE_WIDTH.

A client always may re-register for a resource with the same token or with a new token to indicate continued interest in receiving notifications about it. Of course the client must not already be using any new token in the registration for a different resource. Successful registration always is indicated by the presence of the Observe option in the response.

To cancel registration, the server expects to receive a GET request with the Observe option value set to 1. The server does not support cancellation via a reset (RST) response to a non-confirmable notification.

Implementation Notes

Waiting for a response

We take advantage of RIOT's asynchronous messaging by using an xtimer to wait for a response, so the gcoap thread does not block while waiting. The user is notified via the same callback, whether the message is received or the wait times out. We track the response with an entry in the _coap_state.open_reqs array.

Implementation Status

gcoap includes server and client capability. Available features include:

Modules

 Gcoap compile configurations
 

Files

file  gcoap.h
 gcoap definition
 

Data Structures

struct  gcoap_listener
 A modular collection of resources for a server. More...
 
struct  gcoap_resend_t
 Extends request memo for resending a confirmable request. More...
 
struct  gcoap_request_memo_t
 Memo to handle a response for a request. More...
 
struct  gcoap_observe_memo_t
 Memo for Observe registration and notifications. More...
 

Macros

#define GCOAP_TOKENLEN_MAX   (8)
 Maximum length in bytes for a token.
 
#define GCOAP_HEADER_MAXLEN   (sizeof(coap_hdr_t) + GCOAP_TOKENLEN_MAX)
 Maximum length in bytes for a header, including the token.
 
#define GCOAP_PAYLOAD_MARKER   (0xFF)
 Marks the boundary between header and payload.
 
#define GCOAP_SEND_LIMIT_NON   (-1)
 Value for send_limit in request memo when non-confirmable type.
 
#define GCOAP_MSG_TYPE_TIMEOUT   (0x1501)
 Identifies waiting timed out for a response to a sent message.
 
#define GCOAP_MSG_TYPE_INTR   (0x1502)
 Identifies a request to interrupt listening for an incoming message on a sock. More...
 
#define GCOAP_OBS_TICK_EXPONENT   (5)
 See GCOAP_OBS_VALUE_WIDTH.
 
#define GCOAP_STACK_SIZE
 Stack size for module thread. More...
 

Typedefs

typedef struct gcoap_listener gcoap_listener_t
 A modular collection of resources for a server.
 
typedef void(* gcoap_resp_handler_t) (unsigned req_state, coap_pkt_t *pdu, sock_udp_ep_t *remote)
 Handler function for a server response, including the state for the originating request. More...
 

Functions

kernel_pid_t gcoap_init (void)
 Initializes the gcoap thread and device. More...
 
void gcoap_register_listener (gcoap_listener_t *listener)
 Starts listening for resource paths. More...
 
int gcoap_req_init (coap_pkt_t *pdu, uint8_t *buf, size_t len, unsigned code, const char *path)
 Initializes a CoAP request PDU on a buffer. More...
 
ssize_t gcoap_finish (coap_pkt_t *pdu, size_t payload_len, unsigned format)
 Finishes formatting a CoAP PDU after the payload has been written. More...
 
static ssize_t gcoap_request (coap_pkt_t *pdu, uint8_t *buf, size_t len, unsigned code, char *path)
 Writes a complete CoAP request PDU when there is not a payload. More...
 
size_t gcoap_req_send (const uint8_t *buf, size_t len, const sock_udp_ep_t *remote, gcoap_resp_handler_t resp_handler)
 Sends a buffer containing a CoAP request to the provided endpoint. More...
 
static size_t gcoap_req_send2 (const uint8_t *buf, size_t len, const sock_udp_ep_t *remote, gcoap_resp_handler_t resp_handler)
 Sends a buffer containing a CoAP request to the provided endpoint. More...
 
int gcoap_resp_init (coap_pkt_t *pdu, uint8_t *buf, size_t len, unsigned code)
 Initializes a CoAP response packet on a buffer. More...
 
static ssize_t gcoap_response (coap_pkt_t *pdu, uint8_t *buf, size_t len, unsigned code)
 Writes a complete CoAP response PDU when there is no payload. More...
 
int gcoap_obs_init (coap_pkt_t *pdu, uint8_t *buf, size_t len, const coap_resource_t *resource)
 Initializes a CoAP Observe notification packet on a buffer, for the observer registered for a resource. More...
 
size_t gcoap_obs_send (const uint8_t *buf, size_t len, const coap_resource_t *resource)
 Sends a buffer containing a CoAP Observe notification to the observer registered for a resource. More...
 
uint8_t gcoap_op_state (void)
 Provides important operational statistics. More...
 
int gcoap_get_resource_list (void *buf, size_t maxlen, uint8_t cf)
 Get the resource list, currently only CoRE Link Format (COAP_FORMAT_LINK) supported. More...
 
int gcoap_add_qstring (coap_pkt_t *pdu, const char *key, const char *val)
 Adds a single Uri-Query option to a CoAP request. More...
 

States for the memo used to track waiting for a response

#define GCOAP_MEMO_UNUSED   (0)
 This memo is unused.
 
#define GCOAP_MEMO_WAIT   (1)
 Request sent; awaiting response.
 
#define GCOAP_MEMO_RESP   (2)
 Got response.
 
#define GCOAP_MEMO_TIMEOUT   (3)
 Timeout waiting for response.
 
#define GCOAP_MEMO_ERR   (4)
 Error processing response packet.
 

States for the memo used to track Observe registrations

#define GCOAP_OBS_MEMO_UNUSED   (0)
 This memo is unused.
 
#define GCOAP_OBS_MEMO_IDLE   (1)
 Registration OK; no current activity.
 
#define GCOAP_OBS_MEMO_PENDING   (2)
 Resource changed; notification pending.
 

Return values for gcoap_obs_init()

#define GCOAP_OBS_INIT_OK   (0)
 
#define GCOAP_OBS_INIT_ERR   (-1)
 
#define GCOAP_OBS_INIT_UNUSED   (-2)
 

Macro Definition Documentation

◆ GCOAP_MSG_TYPE_INTR

#define GCOAP_MSG_TYPE_INTR   (0x1502)

Identifies a request to interrupt listening for an incoming message on a sock.

Allows the event loop to process IPC messages.

Definition at line 365 of file gcoap.h.

◆ GCOAP_STACK_SIZE

#define GCOAP_STACK_SIZE
Value:
+ sizeof(coap_pkt_t))
#define DEBUG_EXTRA_STACKSIZE
Extra stacksize needed when ENABLE_DEBUG==1.
Definition: debug.h:106
#define THREAD_STACKSIZE_DEFAULT
A reasonable default stack size that will suffice most smaller tasks.
Definition: thread.h:195
CoAP PDU parsing context structure.
Definition: nanocoap.h:184

Stack size for module thread.

Definition at line 440 of file gcoap.h.

Typedef Documentation

◆ gcoap_resp_handler_t

typedef void(* gcoap_resp_handler_t) (unsigned req_state, coap_pkt_t *pdu, sock_udp_ep_t *remote)

Handler function for a server response, including the state for the originating request.

If request timed out, the packet header is for the request.

Definition at line 468 of file gcoap.h.

Function Documentation

◆ gcoap_add_qstring()

int gcoap_add_qstring ( coap_pkt_t pdu,
const char *  key,
const char *  val 
)

Adds a single Uri-Query option to a CoAP request.

To add multiple Uri-Query options, simply call this function multiple times. The Uri-Query options will be added in the order those calls.

Parameters
[out]pduThe package that is being build
[in]keyKey to add to the query string
[in]valValue to assign to key (may be NULL)
Precondition
((pdu != NULL) && (key != NULL))
Returns
overall length of new query string
-1 on error

◆ gcoap_finish()

ssize_t gcoap_finish ( coap_pkt_t pdu,
size_t  payload_len,
unsigned  format 
)

Finishes formatting a CoAP PDU after the payload has been written.

Assumes the PDU has been initialized with a gcoap_xxx_init() function, like gcoap_req_init().

Warning
To use this function, you only may have added an Option with option number less than COAP_OPT_CONTENT_FORMAT. Otherwise, use the struct-based API described with nanocoap. With this API, you specify the format with coap_opt_add_uint(), prepare for the payload with coap_opt_finish(), and then write the payload.
Parameters
[in,out]pduRequest metadata
[in]payload_lenLength of the payload, or 0 if none
[in]formatFormat code for the payload; use COAP_FORMAT_NONE if not specified
Returns
size of the PDU
< 0 on error

◆ gcoap_get_resource_list()

int gcoap_get_resource_list ( void *  buf,
size_t  maxlen,
uint8_t  cf 
)

Get the resource list, currently only CoRE Link Format (COAP_FORMAT_LINK) supported.

If buf := NULL, nothing will be written but the size of the resulting resource list is computed and returned.

Parameters
[out]bufoutput buffer to write resource list into, my be NULL
[in]maxlenlength of buf, ignored if buf is NULL
[in]cfcontent format to use for the resource list, currently only COAP_FORMAT_LINK supported
Todo:

add support for JSON CoRE Link Format

add support for 'CBOR CoRE Link Format`

Returns
the number of bytes written to buf
-1 on error

◆ gcoap_init()

kernel_pid_t gcoap_init ( void  )

Initializes the gcoap thread and device.

Must call once before first use.

Returns
PID of the gcoap thread on success.
-EEXIST, if thread already has been created.
-EINVAL, if the IP port already is in use.

◆ gcoap_obs_init()

int gcoap_obs_init ( coap_pkt_t pdu,
uint8_t *  buf,
size_t  len,
const coap_resource_t resource 
)

Initializes a CoAP Observe notification packet on a buffer, for the observer registered for a resource.

First verifies that an observer has been registered for the resource.

Parameters
[out]pduNotification metadata
[out]bufBuffer containing the PDU
[in]lenLength of the buffer
[in]resourceResource for the notification
Returns
GCOAP_OBS_INIT_OK on success
GCOAP_OBS_INIT_ERR on error
GCOAP_OBS_INIT_UNUSED if no observer for resource

◆ gcoap_obs_send()

size_t gcoap_obs_send ( const uint8_t *  buf,
size_t  len,
const coap_resource_t resource 
)

Sends a buffer containing a CoAP Observe notification to the observer registered for a resource.

Assumes a single observer for a resource.

Parameters
[in]bufBuffer containing the PDU
[in]lenLength of the buffer
[in]resourceResource to send
Returns
length of the packet
0 if cannot send

◆ gcoap_op_state()

uint8_t gcoap_op_state ( void  )

Provides important operational statistics.

Useful for monitoring.

Returns
count of unanswered requests

◆ gcoap_register_listener()

void gcoap_register_listener ( gcoap_listener_t listener)

Starts listening for resource paths.

Parameters
[in]listenerListener containing the resources.

◆ gcoap_req_init()

int gcoap_req_init ( coap_pkt_t pdu,
uint8_t *  buf,
size_t  len,
unsigned  code,
const char *  path 
)

Initializes a CoAP request PDU on a buffer.

Parameters
[out]pduRequest metadata
[out]bufBuffer containing the PDU
[in]lenLength of the buffer
[in]codeRequest code, one of COAP_METHOD_XXX
[in]pathResource path, may be NULL
Precondition
path must start with / if not NULL
Returns
0 on success
< 0 on error

◆ gcoap_req_send()

size_t gcoap_req_send ( const uint8_t *  buf,
size_t  len,
const sock_udp_ep_t remote,
gcoap_resp_handler_t  resp_handler 
)

Sends a buffer containing a CoAP request to the provided endpoint.

Parameters
[in]bufBuffer containing the PDU
[in]lenLength of the buffer
[in]remoteDestination for the packet
[in]resp_handlerCallback when response received, may be NULL
Returns
length of the packet
0 if cannot send

◆ gcoap_req_send2()

static size_t gcoap_req_send2 ( const uint8_t *  buf,
size_t  len,
const sock_udp_ep_t remote,
gcoap_resp_handler_t  resp_handler 
)
inlinestatic

Sends a buffer containing a CoAP request to the provided endpoint.

Deprecated:
Migration alias for gcoap_req_send(). Will be removed after the 2020.01 release.
Parameters
[in]bufBuffer containing the PDU
[in]lenLength of the buffer
[in]remoteDestination for the packet
[in]resp_handlerCallback when response received, may be NULL
Returns
length of the packet
0 if cannot send

Definition at line 614 of file gcoap.h.

◆ gcoap_request()

static ssize_t gcoap_request ( coap_pkt_t pdu,
uint8_t *  buf,
size_t  len,
unsigned  code,
char *  path 
)
inlinestatic

Writes a complete CoAP request PDU when there is not a payload.

Parameters
[in,out]pduRequest metadata
[in,out]bufBuffer containing the PDU
[in]lenLength of the buffer
[in]codeRequest code: GCOAP_[GET|POST|PUT|DELETE]
[in]pathResource path, must start with '/'
Returns
size of the PDU within the buffer
< 0 on error

Definition at line 577 of file gcoap.h.

◆ gcoap_resp_init()

int gcoap_resp_init ( coap_pkt_t pdu,
uint8_t *  buf,
size_t  len,
unsigned  code 
)

Initializes a CoAP response packet on a buffer.

Initializes payload location within the buffer based on packet setup.

Parameters
[out]pduResponse metadata
[in]bufBuffer containing the PDU
[in]lenLength of the buffer
[in]codeResponse code
Returns
0 on success
< 0 on error

◆ gcoap_response()

static ssize_t gcoap_response ( coap_pkt_t pdu,
uint8_t *  buf,
size_t  len,
unsigned  code 
)
inlinestatic

Writes a complete CoAP response PDU when there is no payload.

Parameters
[out]pduResponse metadata
[out]bufBuffer containing the PDU
[in]lenLength of the buffer
[in]codeResponse code
Returns
size of the PDU within the buffer
< 0 on error

Definition at line 647 of file gcoap.h.