Loading...
Searching...
No Matches

Send CoAP requests synchronously or asynchronously. More...

Detailed Description

Send CoAP requests synchronously or asynchronously.

Module. Specify USEMODULE += unicoap_client in your application's Makefile.

Constructing a request

Begin by constructing a message to send to the server.

unicoap_request_init_empty(&request, UNICOAP_METHOD_GET);
@ UNICOAP_METHOD_GET
GET request (no paylod)
Definition constants.h:141
Generic CoAP message.
Definition message.h:72

unicoap supports multiple ways of addressing a server. unicoap_destination_t supports Uniform Resource Identifiers (URIs) and sock endpoints. To use URI and DNS functionality in unicoap, import URI Client Support.

/* Set destination to URI passed over CLI. */
unicoap_destination_t destination =
unicoap_destination_uri_string("coap://example.arpa/foo/bar?flag=1&x=X");
unicoap_endpoint_t endpoint = {
.udp_ep = {
.family = AF_INET6,
.addr.ipv6 = { 0xfe, 0x80, /* ... */ }
}
};
unicoap_destination_t destination =
unicoap_destination_endpoint(&endpoint);
#define AF_INET6
internetwork address family with IPv6: UDP, TCP, etc.
Definition af.h:37
#define UNICOAP_DEFAULT_COAP_PORT
Default CoAP port.
Definition config.h:85
@ UNICOAP_PROTO_UDP
CoAP over UDP endpoint.
Definition transport.h:144
A type abstracting over CoAP resource identifiers.
Definition transport.h:421
A CoAP endpoint.
Definition transport.h:204
Attention
If you are using CoAP over DTLS Driver and are sending a request over DTLS (coaps://): Due to the current DTLS implementation, TinyDTLS for RIOT, unicoap must set a network interface (netif) identifier to make sure the DTLS session handshake works. If your RIOT instance has only a single netif (you can check this by running ifconfig in the examples/basic/default shell), unicoap will experimentally assume this interface. **If there're two or more interfaces, you MUST provide a netif, either as a zone identifier in the URI (e.g., %7 if 7 is the netif id), or by setting unicoap_endpoint_t .udp_ep.netif if you are using unicoap_destination_t::unicoap_destination_endpoint.

Sending requests and handling responses

You will also need to define a response handler.

static int my_response_handler(
const unicoap_message_t* response,
const unicoap_aux_t* aux, int error, void* arg
) {
/* Check if success or failure. Only proceed if no error occurred. */
if (error) {
return error;
}
/* Handle response */
return 0;
}
Auxiliary exchange information.
Definition transport.h:808

Then, send a request. You can choose between several versions:

You should generally aim to use unicoap_send_request_async in most instances, and only fall back to unicoap_send_request_sync if your application is really unable to make any progress until the response has come in (or an error occurred). Both callback-based versions also call the callback if the request fails. Use the aux parameter to obtain additional info about endpoints and messaging-layer properties (e.g., token and RFC 7252 message ID).

&request, &destination, my_response_handler,
/* params: */ NULL,
)) < 0) {
return res;
}
int unicoap_send_request_async(unicoap_message_t *request, unicoap_destination_t *destination, unicoap_response_callback_t callback, unicoap_request_parameters_t *parameters, unicoap_request_flags_t flags)
Sends a request asynchronously.
@ UNICOAP_REQUEST_FLAG_RELIABLE
Sets the type of the message to confirmable (CON), if the endpoint uses a non-reliable transport such...
Definition client.h:58

Customizing request behavior

The client API provides two ways of customizing timing, reliability, etc. Use the flags parameter to toggle boolean switches: At the moment, only UNICOAP_REQUEST_FLAG_RELIABLE is supported, which instructs the messaging layer to use its reliable transmission mode while sending the request. If the transport layer is already inherently reliably, this flag has no effect; but over UDP/DTLS, the RFC 7252 messaging implementation will use a confirmable (CON) message rather than a non-confirmable (NON).

unicoap_request_parameters_t are optional parameters. Set unicoap_request_parameters_t::timeout_ms to set a custom timeout for the request that differs from CONFIG_UNICOAP_TIMEOUT_CLIENT_RESPONSE_MS. You can also pass a custom argument to the response handler using unicoap_request_parameters_t::callback_arg to provide additional context, e.g., when you use the response handler across multiple requests.

Requests will be sent from the same default port the server uses (CONFIG_UNICOAP_UDP_PORT and CONFIG_UNICOAP_DTLS_PORT). Client and server can be used simultaneously, and will by default use the same port. In the future, we add the ability to specify the local endpoint the request will be sent from. If you do have such a use case, please file an issue.

Cancelling a request

You can cancel pending requests. Refer to Request cancellation.

Topics

 Request cancellation
 Cancel pending requests.
 
 URI Client Support
 Use Uniform Resource Identifiers (URIs) to address remote CoAP resources.
 
 Writing a Client Application
 Learn to write a simple client application with unicoap
 

Files

file  client.h
 Client APIs.
 

Data Structures

struct  unicoap_request_parameters_t
 Additional parameters to customize request behavior. More...
 

Customizing request behavior

enum  unicoap_request_flags_t { UNICOAP_REQUEST_FLAG_RELIABLE = 0x0001 }
 Flags for enabling advanced features in client exchanges. More...
 
void unicoap_print_request_flags (unicoap_request_flags_t flags)
 Prints request flags.
 

Sending a request

typedef int(* unicoap_response_callback_t) (const unicoap_message_t *response, const unicoap_aux_t *aux, int error, void *arg)
 Response or error callback.
 
int unicoap_send_request_async (unicoap_message_t *request, unicoap_destination_t *destination, unicoap_response_callback_t callback, unicoap_request_parameters_t *parameters, unicoap_request_flags_t flags)
 Sends a request asynchronously.
 
int unicoap_send_request_sync (unicoap_message_t *request, unicoap_destination_t *destination, unicoap_response_callback_t callback, unicoap_request_parameters_t *parameters, unicoap_request_flags_t flags)
 Sends a request synchronously.
 
int unicoap_send_request_sync_copy (unicoap_message_t *request, unicoap_destination_t *destination, unicoap_message_t *response, unicoap_request_parameters_t *parameters, unicoap_request_flags_t flags, unicoap_aux_t *aux)
 Sends a request synchronously and copies the request to the given buffer.
 

Typedef Documentation

◆ unicoap_response_callback_t

typedef int(* unicoap_response_callback_t) (const unicoap_message_t *response, const unicoap_aux_t *aux, int error, void *arg)

Response or error callback.

Called synchronously or asynchronously for unicoap_send_request_sync or unicoap_send_request_async, respectively.

static on_response(const unicoap_message_t* response, const unicoap_aux_t* aux, int error, void* arg) {
if (error) {
printf("Something went wrong, error %i (%s)\n", error, strerror(-error));
return error;
}
unicoap_status_t status = unicoap_response_get_status(response);
printf("Received response, status %s", unicoap_string_from_status(status));
return 0;
}
#define printf(...)
A wrapper for the printf() function that passes arguments through unmodified, but fails to compile if...
Definition stdio.h:57
const char * unicoap_string_from_status(unicoap_status_t status)
Generates short descriptive label from CoAP status code.
unicoap_status_t
CoAP response status codes.
Definition constants.h:213
Remarks
Always check the error parameter first.
Parameters
[in]responseResponse message
[in]auxAuxiliary response information
errorError if negative, zero if successful
[in,out]argArgument supplied to the initial send_request function
Returns
Zero on success or negative integer indicating error

Definition at line 118 of file client.h.

Enumeration Type Documentation

◆ unicoap_request_flags_t

Flags for enabling advanced features in client exchanges.

Pass these flags to one of the unicoap_send_request functions to modify transmission, block-wise, or resource observation behavior.

Enumerator
UNICOAP_REQUEST_FLAG_RELIABLE 

Sets the type of the message to confirmable (CON), if the endpoint uses a non-reliable transport such as UDP or DTLS.

This flag is ignored with reliable transports. For unreliable transports, a message sent with this flag will require an acknowledgement to be sent from the CoAP peer.

Default: disabled

Definition at line 47 of file client.h.

Function Documentation

◆ unicoap_send_request_async()

int unicoap_send_request_async ( unicoap_message_t * request,
unicoap_destination_t * destination,
unicoap_response_callback_t callback,
unicoap_request_parameters_t * parameters,
unicoap_request_flags_t flags )

Sends a request asynchronously.

The callback will be executed on the internal CoAP thread. You are in charge of ensuring thread-safety. If your application cannot continue running without a result, consider using unicoap_send_request_sync or unicoap_send_request_sync_copy instead to avoid nesting your application code in callbacks.

Consumes request.

Transmission behavior

If you want to send a request to an UDP or DTLS CoAP endpoint reliably, pass in UNICOAP_REQUEST_FLAG_RELIABLE. This will result in a confirmable request message being sent rather than a non-confirmable message.

Parameters
[in,out]requestInitialized request message to send
[in]destinationURI or endpoint. Use unicoap_destination_t::unicoap_destination_uri_string or unicoap_destination_t::unicoap_destination_endpoint
callbackFunction executed when the entire response is available or if an error occurred
parametersOptional parameters (nullable)
flagsRequest flags
Returns
Zero on success or positive refno if cancellable requests are enabled
Negative integer on failure

◆ unicoap_send_request_sync()

int unicoap_send_request_sync ( unicoap_message_t * request,
unicoap_destination_t * destination,
unicoap_response_callback_t callback,
unicoap_request_parameters_t * parameters,
unicoap_request_flags_t flags )

Sends a request synchronously.

This client method will not return until either an error is thrown or the response is available. If blocking the current thread is unacceptable in your scenario, consider switching to unicoap_send_request_async.

Consumes request .

Transmission behavior

If you want to send a request to an UDP or DTLS CoAP endpoint reliably, pass in UNICOAP_REQUEST_FLAG_RELIABLE. This will result in a confirmable request message being sent rather than a non-confirmable message.

Parameters
[in,out]requestInitialized request message to send
[in]destinationURI or endpoint. Use unicoap_destination_t::unicoap_destination_uri_string or unicoap_destination_t::unicoap_destination_endpoint
callbackFunction executed when the entire response is available or if an error occurred
parametersOptional parameters (nullable)
flagsRequest flags
Returns
Zero on success
Negative integer on failure

◆ unicoap_send_request_sync_copy()

int unicoap_send_request_sync_copy ( unicoap_message_t * request,
unicoap_destination_t * destination,
unicoap_message_t * response,
unicoap_request_parameters_t * parameters,
unicoap_request_flags_t flags,
unicoap_aux_t * aux )

Sends a request synchronously and copies the request to the given buffer.

This client method will not return until either an error is thrown or the response is available. If blocking the current thread is unacceptable in your scenario, consider switching to unicoap_send_request_async. When the entire response is available, it will be copied into the buffer. If the buffer capacity provided by you is too small for the response, this method will fail with -ENOBUFS. Once the method returns zero, you can start reading from response and aux.

You must pass a pre-allocated response struct to this function. To receive response options, pre-allocate options using UNICOAP_OPTIONS_ALLOC or UNICOAP_OPTIONS_ALLOC_STATIC and set unicoap_message_t::options accordingly. To read from the response payload, allocate a a buffer and set unicoap_message_t::payload, unicoap_message_t::payload_size, and unicoap_message_t::payload_representation to UNICOAP_PAYLOAD_CONTIGUOUS. Non-contiguous payload buffers are not supported by this function. When this function returns, the unicoap_message_t::payload_size property will have been updated to reflect the received payload length and options.

Consumes request.

Remarks
To avoid the overhead of copying the response from network-stack-internal memory, use unicoap_send_request_sync or unicoap_send_request_async.

Transmission behavior

If you want to send a request to an UDP or DTLS CoAP endpoint reliably, pass in UNICOAP_REQUEST_FLAG_RELIABLE. This will result in a confirmable request message being sent rather than a non-confirmable message.

Parameters
[in,out]requestInitialized request message to send
[in]destinationURI or endpoint. Use unicoap_destination_t::unicoap_destination_uri_string or unicoap_destination_t::unicoap_destination_endpoint
[in,out]responsePartially initialized response message
parametersOptional parameters (nullable)
flagsRequest flags
[in,out]auxPre-allocated auxiliary information structure, will be initialized when a response is received successfully
Returns
Zero on success or positive refno if cancellable requests are enabled
Negative integer on failure