Loading...
Searching...
No Matches

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 uses nanocoap's Packet API to write message options.

gcoap 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. gcoap also supports the Block extension (RFC 7959) with block-specific option functions as well as some helpers.

Contents

Server Operation

gcoap listens for requests on CONFIG_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. See the Resource list creation section below for more.

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/client.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. Options must be written in order by option number (see "CoAP option numbers" in CoAP defines).
  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.

Resource list creation

gcoap allows customization of the function that provides the list of registered resources for /.well-known/core and CoRE Resource Directory registration. By default gcoap provides gcoap_encode_link(), which lists only the target path for each link. However, an application may specify a custom function in the gcoap_listener_t it registers with gcoap. For example, this function may add parameters to provide more information about the resource, as described in RFC 6690. See the gcoap example for use of a custom encoder function.

Client Operation

Client operation includes two phases: creating and sending a request, and handling the response asynchronously in a client supplied callback. See examples/gcoap/client.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. Options must be written in order by option number (see "CoAP option numbers" in CoAP defines).
  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_send() 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 state field of the memo callback parameter (memo->state). 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.

It is suggested that a server adds the 'obs' attribute to resources that are useful for observation (i.e. will produce notifications) as a hint. Keep in mind that this is not mandatory in order to enable the mechanism in RIOT, nor will it prevent a client from observing a resource that does not have this attribute in the link description. See the "Resource list creation" section above for how the gcoap example app publishes the obs attribute.

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. Options must be written in order by option number (see "CoAP option numbers" in CoAP defines).
  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 CONFIG_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.

Block Operation

gcoap provides for both server side and client side blockwise messaging for requests and responses. This section outlines how to write a message for each situation.

CoAP server GET handling

The server must slice the full response body into smaller payloads, and identify the slice with a Block2 option. This implementation toggles the actual writing of data as it passes over the code for the full response body. See the _riot_block2_handler() example in gcoap-block-server, which implements the sequence described below.

CoAP server PUT/POST handling

The server must ack each blockwise portion of the response body received from the client by writing a Block1 option in the response. See the _sha256_handler() example in gcoap-block-server, which implements the sequence described below.

CoAP client GET request

The client requests a specific blockwise payload from the overall body by writing a Block2 option in the request. See _resp_handler() in the gcoap example in the RIOT distribution, which implements the sequence described below.

CoAP client PUT/POST request

The client pushes a specific blockwise payload from the overall body to the server by writing a Block1 option in the request. See _do_block_post() in the gcoap-block-client example, which implements the sequence described below.

Proxy Operation

A CoAP proxy forwards incoming requests to an origin server, or again to another proxy server.

Proxy Client Handling

The current implementation only allows the use of Proxy-Uri to specify the absolute URI for the origin server and resource. A request that includes a Proxy-Uri option must not contain any of the Uri-* options. An example:

// endpoint for the proxy server
sock_udp_ep_t *proxy_remote = ...;
// absolute URI for the origin server and resource
char *uri = "coap://[2001:db8::1]:5683/.well-known/core";
unsigned len = coap_opt_finish(&pdu, COAP_OPT_FINISH_NONE);
gcoap_req_send((uint8_t *) pdu->hdr, len, proxy_remote, NULL, _resp_handler, NULL,
@ COAP_METHOD_GET
GET request (no paylod)
Definition coap.h:172
#define CONFIG_GCOAP_PDU_BUF_SIZE
Size of the buffer used to build a CoAP request or response.
Definition gcoap.h:464
static 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.
Definition gcoap.h:969
ssize_t gcoap_req_send(const uint8_t *buf, size_t len, const sock_udp_ep_t *remote, const sock_udp_ep_t *local, gcoap_resp_handler_t resp_handler, void *context, gcoap_socket_type_t tl_type)
Sends a buffer containing a CoAP request to the provided endpoint.
@ GCOAP_SOCKET_TYPE_UNDEF
undefined
Definition gcoap.h:751
#define COAP_OPT_FINISH_NONE
no special handling required
Definition nanocoap.h:193
ssize_t coap_opt_add_proxy_uri(coap_pkt_t *pkt, const char *uri)
Adds a single Proxy-URI option into pkt.
ssize_t coap_opt_finish(coap_pkt_t *pkt, uint16_t flags)
Finalizes options as required and prepares for payload.
Common IP-based transport layer end point.
Definition sock.h:215

See the gcoap example for a sample implementation.

Proxy Server Handling

Not implemented yet.

DTLS as transport security

GCoAP allows to use DTLS for transport security by using the DTLS sock API. Using the module gcoap_dtls enables the support. GCoAP listens for requests on CONFIG_GCOAPS_PORT, 5684 by default when DTLS is enabled.

Credentials have to been configured before use. See Credman and DTLS sock credentials API for credential managing. Access to the DTLS socket is provided by gcoap_get_sock_dtls().

GCoAP includes a DTLS session management component that stores active sessions. By default, it tries to have CONFIG_GCOAP_DTLS_MINIMUM_AVAILABLE_SESSIONS session slots available to keep the server responsive. If not enough sessions are available the server destroys the session that has not been used for the longest time after CONFIG_GCOAP_DTLS_MINIMUM_AVAILABLE_SESSIONS_TIMEOUT_USEC.

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

 DNS over CoAP client implementation
 A DNS over CoAP client prototype based on gCoAP.
 
 GCoAP Forward Proxy
 Forward proxy implementation for GCoAP.
 
 GCoAP Forward Proxy Thread
 Forward proxy thread implementation for GCoAP.
 
 GCoAP compile configurations
 

Files

file  gcoap.h
 gcoap definition
 

Data Structures

struct  coap_link_encoder_ctx_t
 Context information required to write a resource link. More...
 
struct  gcoap_socket_t
 CoAP socket to handle multiple transport types. More...
 
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
 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.
 

Typedefs

typedef ssize_t(* gcoap_link_encoder_t) (const coap_resource_t *resource, char *buf, size_t maxlen, coap_link_encoder_ctx_t *context)
 Handler function to write a resource link.
 
typedef struct gcoap_listener gcoap_listener_t
 Forward declaration of the gcoap listener state container.
 
typedef int(* gcoap_request_matcher_t) (gcoap_listener_t *listener, const coap_resource_t **resource, coap_pkt_t *pdu)
 Handler function for the request matcher strategy.
 
typedef struct gcoap_request_memo gcoap_request_memo_t
 Forward declaration of the request memo type.
 
typedef void(* gcoap_resp_handler_t) (const gcoap_request_memo_t *memo, coap_pkt_t *pdu, const sock_udp_ep_t *remote)
 Handler function for a server response, including the state for the originating request.
 

Enumerations

enum  gcoap_socket_type_t { GCOAP_SOCKET_TYPE_UNDEF = 0x0 , GCOAP_SOCKET_TYPE_UDP = 0x1 , GCOAP_SOCKET_TYPE_DTLS = 0x2 }
 CoAP socket types. More...
 

Functions

kernel_pid_t gcoap_init (void)
 Initializes the gcoap thread and device.
 
void gcoap_register_listener (gcoap_listener_t *listener)
 Starts listening for resource paths.
 
const coap_resource_tgcoap_get_resource_by_path_iterator (const gcoap_listener_t **last_listener, const coap_resource_t *last_resource, const char *uri_path)
 Iterate through all registered listeners and check for a resource, matching by uri_path.
 
int gcoap_req_init_path_buffer (coap_pkt_t *pdu, uint8_t *buf, size_t len, unsigned code, const char *path, size_t path_len)
 Initializes a CoAP request PDU on a buffer.
 
static 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.
 
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.
 
ssize_t gcoap_req_send (const uint8_t *buf, size_t len, const sock_udp_ep_t *remote, const sock_udp_ep_t *local, gcoap_resp_handler_t resp_handler, void *context, gcoap_socket_type_t tl_type)
 Sends a buffer containing a CoAP request to the provided endpoint.
 
static ssize_t gcoap_req_send_tl (const uint8_t *buf, size_t len, const sock_udp_ep_t *remote, gcoap_resp_handler_t resp_handler, void *context, gcoap_socket_type_t tl_type)
 Sends a buffer containing a CoAP request to the provided endpoint.
 
int gcoap_resp_init (coap_pkt_t *pdu, uint8_t *buf, size_t len, unsigned code)
 Initializes a CoAP response packet on a buffer.
 
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.
 
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.
 
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.
 
int gcoap_obs_req_forget (const sock_udp_ep_t *remote, const uint8_t *token, size_t tokenlen)
 Forgets (invalidates) an existing observe request.
 
uint8_t gcoap_op_state (void)
 Provides important operational statistics.
 
int gcoap_get_resource_list (void *buf, size_t maxlen, uint8_t cf, gcoap_socket_type_t tl_type)
 Get the resource list, currently only CoRE Link Format (COAP_FORMAT_LINK) supported.
 
ssize_t gcoap_encode_link (const coap_resource_t *resource, char *buf, size_t maxlen, coap_link_encoder_ctx_t *context)
 Writes a resource in CoRE Link Format to a provided buffer.
 
sock_dtls_tgcoap_get_sock_dtls (void)
 Get the underlying DTLS socket of gcoap.
 
static coap_hdr_tgcoap_request_memo_get_hdr (const gcoap_request_memo_t *memo)
 Get the header of a request from a gcoap_request_memo_t.
 

States for the memo used to track waiting for a response

#define GCOAP_MEMO_UNUSED   (0)
 This memo is unused.
 
#define GCOAP_MEMO_RETRANSMIT   (1)
 Request sent, retransmitting until response arrives.
 
#define GCOAP_MEMO_WAIT   (2)
 Request sent; awaiting response.
 
#define GCOAP_MEMO_RESP   (3)
 Got response.
 
#define GCOAP_MEMO_TIMEOUT   (4)
 Timeout waiting for response.
 
#define GCOAP_MEMO_ERR   (5)
 Error processing response packet.
 
#define GCOAP_MEMO_RESP_TRUNC   (6)
 Got response, but it got truncated into the receive buffer that is now incomplete.
 

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()

See CONFIG_GCOAP_OBS_VALUE_WIDTH

#define GCOAP_OBS_INIT_OK   (0)
 
#define GCOAP_OBS_INIT_ERR   (-1)
 
#define GCOAP_OBS_INIT_UNUSED   (-2)
 
#define GCOAP_DTLS_EXTRA_STACKSIZE   (0)
 Stack size for module thread.
 
#define GCOAP_VFS_EXTRA_STACKSIZE   (0)
 Extra stack for VFS operations.
 
#define GCOAP_STACK_SIZE
 

Bitwise positional flags for encoding resource links

#define COAP_LINK_FLAG_INIT_RESLIST   (1)
 initialize as for first resource in a list
 

Return values for resource related operations

#define GCOAP_RESOURCE_FOUND   (0)
 
#define GCOAP_RESOURCE_WRONG_METHOD   (1)
 
#define GCOAP_RESOURCE_NO_PATH   (2)
 
#define GCOAP_RESOURCE_ERROR   (3)
 

Macro Definition Documentation

◆ COAP_LINK_FLAG_INIT_RESLIST

#define COAP_LINK_FLAG_INIT_RESLIST   (1)

initialize as for first resource in a list

Definition at line 685 of file gcoap.h.

◆ GCOAP_DTLS_EXTRA_STACKSIZE

#define GCOAP_DTLS_EXTRA_STACKSIZE   (0)

Stack size for module thread.

Definition at line 650 of file gcoap.h.

◆ GCOAP_HEADER_MAXLEN

#define GCOAP_HEADER_MAXLEN   (sizeof(coap_hdr_t) + GCOAP_TOKENLEN_MAX)

Maximum length in bytes for a header, including the token.

Definition at line 483 of file gcoap.h.

◆ GCOAP_MEMO_ERR

#define GCOAP_MEMO_ERR   (5)

Error processing response packet.

Definition at line 519 of file gcoap.h.

◆ GCOAP_MEMO_RESP

#define GCOAP_MEMO_RESP   (3)

Got response.

Definition at line 517 of file gcoap.h.

◆ GCOAP_MEMO_RESP_TRUNC

#define GCOAP_MEMO_RESP_TRUNC   (6)

Got response, but it got truncated into the receive buffer that is now incomplete.

Definition at line 521 of file gcoap.h.

◆ GCOAP_MEMO_RETRANSMIT

#define GCOAP_MEMO_RETRANSMIT   (1)

Request sent, retransmitting until response arrives.

Definition at line 515 of file gcoap.h.

◆ GCOAP_MEMO_TIMEOUT

#define GCOAP_MEMO_TIMEOUT   (4)

Timeout waiting for response.

Definition at line 518 of file gcoap.h.

◆ GCOAP_MEMO_UNUSED

#define GCOAP_MEMO_UNUSED   (0)

This memo is unused.

Definition at line 514 of file gcoap.h.

◆ GCOAP_MEMO_WAIT

#define GCOAP_MEMO_WAIT   (2)

Request sent; awaiting response.

Definition at line 516 of file gcoap.h.

◆ GCOAP_OBS_INIT_ERR

#define GCOAP_OBS_INIT_ERR   (-1)

Definition at line 638 of file gcoap.h.

◆ GCOAP_OBS_INIT_OK

#define GCOAP_OBS_INIT_OK   (0)

Definition at line 637 of file gcoap.h.

◆ GCOAP_OBS_INIT_UNUSED

#define GCOAP_OBS_INIT_UNUSED   (-2)

Definition at line 639 of file gcoap.h.

◆ GCOAP_OBS_MEMO_IDLE

#define GCOAP_OBS_MEMO_IDLE   (1)

Registration OK; no current activity.

Definition at line 594 of file gcoap.h.

◆ GCOAP_OBS_MEMO_PENDING

#define GCOAP_OBS_MEMO_PENDING   (2)

Resource changed; notification pending.

Definition at line 595 of file gcoap.h.

◆ GCOAP_OBS_MEMO_UNUSED

#define GCOAP_OBS_MEMO_UNUSED   (0)

This memo is unused.

Definition at line 593 of file gcoap.h.

◆ GCOAP_PAYLOAD_MARKER

#define GCOAP_PAYLOAD_MARKER   (0xFF)

Marks the boundary between header and payload.

Definition at line 498 of file gcoap.h.

◆ GCOAP_RESOURCE_ERROR

#define GCOAP_RESOURCE_ERROR   (3)

Definition at line 720 of file gcoap.h.

◆ GCOAP_RESOURCE_FOUND

#define GCOAP_RESOURCE_FOUND   (0)

Definition at line 717 of file gcoap.h.

◆ GCOAP_RESOURCE_NO_PATH

#define GCOAP_RESOURCE_NO_PATH   (2)

Definition at line 719 of file gcoap.h.

◆ GCOAP_RESOURCE_WRONG_METHOD

#define GCOAP_RESOURCE_WRONG_METHOD   (1)

Definition at line 718 of file gcoap.h.

◆ GCOAP_SEND_LIMIT_NON

#define GCOAP_SEND_LIMIT_NON   (-1)

Value for send_limit in request memo when non-confirmable type.

Definition at line 527 of file gcoap.h.

◆ GCOAP_STACK_SIZE

#define GCOAP_STACK_SIZE
Value:
#define DEBUG_EXTRA_STACKSIZE
Extra stacksize needed when ENABLE_DEBUG==1.
Definition debug.h:135
#define GCOAP_DTLS_EXTRA_STACKSIZE
Stack size for module thread.
Definition gcoap.h:650
#define GCOAP_VFS_EXTRA_STACKSIZE
Extra stack for VFS operations.
Definition gcoap.h:661
CoAP PDU parsing context structure.
Definition nanocoap.h:232
#define THREAD_STACKSIZE_DEFAULT
A reasonable default stack size that will suffice most smaller tasks.

Definition at line 665 of file gcoap.h.

◆ GCOAP_TOKENLEN_MAX

#define GCOAP_TOKENLEN_MAX   (8)

Maximum length in bytes for a token.

Definition at line 478 of file gcoap.h.

◆ GCOAP_VFS_EXTRA_STACKSIZE

#define GCOAP_VFS_EXTRA_STACKSIZE   (0)

Extra stack for VFS operations.

Definition at line 661 of file gcoap.h.

Typedef Documentation

◆ gcoap_link_encoder_t

typedef ssize_t(* gcoap_link_encoder_t) (const coap_resource_t *resource, char *buf, size_t maxlen, coap_link_encoder_ctx_t *context)

Handler function to write a resource link.

Parameters
[in]resourceResource for link
[out]bufBuffer on which to write; may be null
[in]maxlenRemaining length for buf
[in]contextContextual information on what/how to write
Returns
count of bytes written to buf (or writable if buf is null)
-1 on error

Definition at line 710 of file gcoap.h.

◆ gcoap_listener_t

Forward declaration of the gcoap listener state container.

Definition at line 726 of file gcoap.h.

◆ gcoap_request_matcher_t

typedef int(* gcoap_request_matcher_t) (gcoap_listener_t *listener, const coap_resource_t **resource, coap_pkt_t *pdu)

Handler function for the request matcher strategy.

Parameters
[in]listenerListener context
[out]resourceMatching resource
[in]pduPointer to the PDU
Returns
GCOAP_RESOURCE_FOUND on resource match
GCOAP_RESOURCE_NO_PATH on no path found in resource that matches pdu
GCOAP_RESOURCE_ERROR on processing failure of the request

Definition at line 740 of file gcoap.h.

◆ gcoap_request_memo_t

Forward declaration of the request memo type.

Definition at line 809 of file gcoap.h.

◆ gcoap_resp_handler_t

typedef void(* gcoap_resp_handler_t) (const gcoap_request_memo_t *memo, coap_pkt_t *pdu, const 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 817 of file gcoap.h.

Enumeration Type Documentation

◆ gcoap_socket_type_t

CoAP socket types.

May be used as flags for gcoap_listener_t, but must be used numerically with gcoap_req_send().

Enumerator
GCOAP_SOCKET_TYPE_UNDEF 

undefined

GCOAP_SOCKET_TYPE_UDP 

Unencrypted UDP transport.

GCOAP_SOCKET_TYPE_DTLS 

DTLS-over-UDP transport.

Definition at line 750 of file gcoap.h.

Function Documentation

◆ gcoap_encode_link()

ssize_t gcoap_encode_link ( const coap_resource_t resource,
char *  buf,
size_t  maxlen,
coap_link_encoder_ctx_t context 
)

Writes a resource in CoRE Link Format to a provided buffer.

This default implementation only writes the resource path.

Parameters
[in]resourceresource to write
[out]bufoutput buffer to write link into, may be null
[in]maxlenlength of buf, ignored if buf is NULL
[in]contextother parameters that affect how link is written
Returns
count of bytes written to buf (or writable if buf is null)
-1 on error

◆ gcoap_get_resource_by_path_iterator()

const coap_resource_t * gcoap_get_resource_by_path_iterator ( const gcoap_listener_t **  last_listener,
const coap_resource_t last_resource,
const char *  uri_path 
)

Iterate through all registered listeners and check for a resource, matching by uri_path.

This functions returns resources matching a subpath

See also
COAP_MATCH_SUBTREE. If an exact match is required, check with strncmp().
Parameters
[in,out]last_listenerA pointer to NULL for the first call, otherwise the last returned listener
[in]last_resourceNULL for the first call, otherwise the last returned resource
[in]uri_pathThe URI path to search for
Returns
The resource that matches the URI path

◆ gcoap_get_resource_list()

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

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
[in]tl_typeTransport type to get the list for. GCOAP_SOCKET_TYPE_UNDEF for all transport types. If non of the transports beyond UDP are compiled in (i.e. usage of modules no gcoap_dtls, ...) this will be ignored and GCOAP_SOCKET_TYPE_UDP assumed.
Todo:
add support for CoRAL once it is done
Returns
the number of bytes written to buf
-1 on error

◆ gcoap_get_sock_dtls()

sock_dtls_t * gcoap_get_sock_dtls ( void  )

Get the underlying DTLS socket of gcoap.

Useful for managing credentials of gcoap.

Returns
pointer to the sock_dtls_t object

◆ 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.

Postcondition
If this function returns
See also
GCOAP_OBS_INIT_OK you have to call gcoap_obs_send() afterwards to release a mutex.
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_req_forget()

int gcoap_obs_req_forget ( const sock_udp_ep_t remote,
const uint8_t *  token,
size_t  tokenlen 
)

Forgets (invalidates) an existing observe request.

This invalidates the internal (local) observe request state without actually sending a deregistration request to the server. Ths mechanism may be referred to as passive deregistration, as it does not send a deregistration request. This is implemented according to the description in RFC 7641, Section 3.6 (Cancellation): 'A client that is no longer interested in receiving notifications for a resource can simply "forget" the observation.' Successfully invalidating the request by calling this function guarantees that the corresponding observe response handler will not be called anymore.

NOTE: There are cases were active deregistration is preferred instead. A server may continue sending notifications if it chooses to ignore the RST which is meant to indicate the client did not recognize the notification. For such server implementations this function must be called before sending an explicit deregister request (i.e., a GET request with the token of the registration and the observe option set to COAP_OBS_DEREGISTER). This will instruct the server to stop sending further notifications.

Parameters
[in]remoteremote endpoint that hosts the observed resource
[in]tokentoken of the original GET request used for registering an observe
[in]tokenlenthe length of the token in bytes
Returns
0 on success
< 0 on error

◆ 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.

Precondition
listener is a valid pointer to a single listener (that is, listener->next == NULL)
Note
If you are tempted to register a pre-linked chain of listeners, consider placing all their resources in the resources array of a single listener instead. In the few cases where this does not work (that is, when the resources need a different link_encoder or other fields of the listener struct), they can just be registered individually.
Parameters
[in]listenerListener containing the resources.

◆ gcoap_req_init()

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

Initializes a CoAP request PDU on a buffer.

If code is COAP_CODE_EMPTY, prepares a complete "CoAP ping" 4 byte empty message request, ready to send.

With module module `nanocoap_cache` an all-zero ETag option of length 8 which is updated with a value or removed in gcoap_req_send() / gcoap_req_send_tl() depending on existing cache entries for cache (re-)validation. If you do not use the given send functions or do not want cache entries to revalidated for any reason, remove that empty option using coap_opt_remove().

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

Definition at line 969 of file gcoap.h.

◆ gcoap_req_init_path_buffer()

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

Initializes a CoAP request PDU on a buffer.

If code is COAP_CODE_EMPTY, prepares a complete "CoAP ping" 4 byte empty message request, ready to send.

With module module `nanocoap_cache` an all-zero ETag option of length 8 which is updated with a value or removed in gcoap_req_send() / gcoap_req_send_tl() depending on existing cache entries for cache (re-)validation. If you do not use the given send functions or do not want cache entries to revalidated for any reason, remove that empty option using coap_opt_remove().

Parameters
[out]pduRequest metadata
[out]bufBuffer containing the PDU
[in]lenLength of the buffer
[in]codeRequest code, one of COAP_METHOD_XXX or COAP_CODE_EMPTY to ping
[in]pathResource path, may be NULL. path_len will be ignored in that case.
[in]path_lenLength of path.
Precondition
path must start with / if not NULL
Returns
0 on success
< 0 on error

◆ gcoap_req_send()

ssize_t gcoap_req_send ( const uint8_t *  buf,
size_t  len,
const sock_udp_ep_t remote,
const sock_udp_ep_t local,
gcoap_resp_handler_t  resp_handler,
void *  context,
gcoap_socket_type_t  tl_type 
)

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]localLocal endpoint to send from, may be NULL
[in]resp_handlerCallback when response received, may be NULL
[in]contextUser defined context passed to the response handler
[in]tl_typeThe transport type to use for send. When GCOAP_SOCKET_TYPE_UNDEF is selected, the highest available (by value) will be selected. Only single types are allowed, not a combination of them.
Note
The highest supported (by value) gcoap_socket_type_t will be selected as transport type.
Returns
length of the packet
-ENOTCONN, if DTLS was used and session establishment failed
-EINVAL, if tl_type is is not supported
0 if cannot send

◆ gcoap_req_send_tl()

static ssize_t gcoap_req_send_tl ( const uint8_t *  buf,
size_t  len,
const sock_udp_ep_t remote,
gcoap_resp_handler_t  resp_handler,
void *  context,
gcoap_socket_type_t  tl_type 
)
inlinestatic

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

Deprecated:
Will be removed after the 2023.10 release. Use alias gcoap_req_send() instead.
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
[in]contextUser defined context passed to the response handler
[in]tl_typeThe transport type to use for send. When GCOAP_SOCKET_TYPE_UNDEF is selected, the highest available (by value) will be selected. Only single types are allowed, not a combination of them.
Returns
length of the packet
-ENOTCONN, if DTLS was used and session establishment failed
-EINVAL, if tl_type is is not supported
0 if cannot send

Definition at line 1048 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 988 of file gcoap.h.

◆ gcoap_request_memo_get_hdr()

static coap_hdr_t * gcoap_request_memo_get_hdr ( const gcoap_request_memo_t memo)
inlinestatic

Get the header of a request from a gcoap_request_memo_t.

Parameters
[in]memoA request memo. Must not be NULL.
Returns
The request header for the given request memo.

Definition at line 1226 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 1082 of file gcoap.h.