CoAP

Overview

The Constrained Application Protocol (CoAP) is a specialized web transfer protocol for use with constrained nodes and constrained (e.g., low-power, lossy) networks. It provides a convenient API for RESTful Web services that support CoAP’s features. For more information about the protocol itself, see IETF RFC7252 The Constrained Application Protocol.

Zephyr provides a CoAP library which supports client and server roles. The library can be enabled with CONFIG_COAP Kconfig option and is configurable as per user needs. The Zephyr CoAP library is implemented using plain buffers. Users of the API create sockets for communication and pass the buffer to the library for parsing and other purposes. The library itself doesn’t create any sockets for users.

On top of CoAP, Zephyr has support for LWM2M “Lightweight Machine 2 Machine” protocol, a simple, low-cost remote management and service enablement mechanism. See Lightweight M2M (LWM2M) for more information.

Supported RFCs:

Note

Not all parts of these RFCs are supported. Features are supported based on Zephyr requirements.

Sample Usage

CoAP Server

Note

A CoAP server subsystem is available, the following is for creating a custom server implementation.

To create a CoAP server, resources for the server need to be defined. The .well-known/core resource should be added before all other resources that should be included in the responses of the .well-known/core resource.

static struct coap_resource resources[] = {
    { .get = well_known_core_get,
      .path = COAP_WELL_KNOWN_CORE_PATH,
    },
    { .get  = sample_get,
      .post = sample_post,
      .del  = sample_del,
      .put  = sample_put,
      .path = sample_path
    },
    { },
};

An application reads data from the socket and passes the buffer to the CoAP library to parse the message. If the CoAP message is proper, the library uses the buffer along with resources defined above to call the correct callback function to handle the CoAP request from the client. It’s the callback function’s responsibility to either reply or act according to CoAP request.

coap_packet_parse(&request, data, data_len, options, opt_num);
...
coap_handle_request(&request, resources, options, opt_num,
                    client_addr, client_addr_len);

If CONFIG_COAP_URI_WILDCARD enabled, server may accept multiple resources using MQTT-like wildcard style:

  • the plus symbol represents a single-level wild card in the path;

  • the hash symbol represents the multi-level wild card in the path.

static const char * const led_set[] = { "led","+","set", NULL };
static const char * const btn_get[] = { "button","#", NULL };
static const char * const no_wc[] = { "test","+1", NULL };

It accepts /led/0/set, led/1234/set, led/any/set, /button/door/1, /test/+1, but returns -ENOENT for /led/1, /test/21, /test/1.

This option is enabled by default, disable it to avoid unexpected behaviour with resource path like ‘/some_resource/+/#’.

CoAP Client

Note

A CoAP client subsystem is available, the following is for creating a custom client implementation.

If the CoAP client knows about resources in the CoAP server, the client can start prepare CoAP requests and wait for responses. If the client doesn’t know about resources in the CoAP server, it can request resources through the .well-known/core CoAP message.

/* Initialize the CoAP message */
char *path = "test";
struct coap_packet request;
uint8_t data[100];
uint8_t payload[20];

coap_packet_init(&request, data, sizeof(data),
                 1, COAP_TYPE_CON, 8, coap_next_token(),
                 COAP_METHOD_GET, coap_next_id());

/* Append options */
coap_packet_append_option(&request, COAP_OPTION_URI_PATH,
                          path, strlen(path));

/* Append Payload marker if you are going to add payload */
coap_packet_append_payload_marker(&request);

/* Append payload */
coap_packet_append_payload(&request, (uint8_t *)payload,
                           sizeof(payload) - 1);

/* send over sockets */

Testing

There are various ways to test Zephyr CoAP library.

libcoap

libcoap implements a lightweight application-protocol for devices that are resource constrained, such as by computing power, RF range, memory, bandwidth, or network packet sizes. Sources can be found here libcoap. libcoap has a script (examples/etsi_coaptest.sh) to test coap-server functionality in Zephyr.

See the net-tools project for more details

The CoAP service sample can be built and executed on QEMU as described in Networking with QEMU.

Use this command on the host to run the libcoap implementation of the ETSI test cases:

sudo ./libcoap/examples/etsi_coaptest.sh -i tap0 2001:db8::1

TTCN3

Eclipse has TTCN3 based tests to run against CoAP implementations.

Install eclipse-titan and set symbolic links for titan tools

sudo apt-get install eclipse-titan

cd /usr/share/titan

sudo ln -s /usr/bin bin
sudo ln /usr/bin/titanver bin
sudo ln -s /usr/bin/mctr_cli bin
sudo ln -s /usr/include/titan include
sudo ln -s /usr/lib/titan lib

export TTCN3_DIR=/usr/share/titan

git clone https://gitlab.eclipse.org/eclipse/titan/titan.misc.git

cd titan.misc

Follow the instruction to setup CoAP test suite from here:

After the build is complete, the CoAP service sample can be built and executed on QEMU as described in Networking with QEMU.

Change the client (test suite) and server (Zephyr coap-server sample) addresses in coap.cfg file as per your setup.

Execute the test cases with following command.

ttcn3_start coaptests coap.cfg

Sample output of ttcn3 tests looks like this.

Verdict statistics: 0 none (0.00 %), 10 pass (100.00 %), 0 inconc (0.00 %), 0 fail (0.00 %), 0 error (0.00 %).
Test execution summary: 10 test cases were executed. Overall verdict: pass

API Reference

group coap

COAP library.

Since

1.10

Version

0.8.0

Defines

COAP_MAKE_RESPONSE_CODE(class, det)

Utility macro to create a CoAP response code.

Parameters:
  • class – Class of the response code (ex. 2, 4, 5, …)

  • det – Detail of the response code

Returns:

Response code literal

COAP_WELL_KNOWN_CORE_PATH

This resource should be added before all other resources that should be included in the responses of the .well-known/core resource if is to be used with coap_well_known_core_get.

Typedefs

typedef int (*coap_method_t)(struct coap_resource *resource, struct coap_packet *request, struct sockaddr *addr, socklen_t addr_len)

Type of the callback being called when a resource’s method is invoked by the remote entity.

typedef void (*coap_notify_t)(struct coap_resource *resource, struct coap_observer *observer)

Type of the callback being called when a resource’s has observers to be informed when an update happens.

typedef int (*coap_reply_t)(const struct coap_packet *response, struct coap_reply *reply, const struct sockaddr *from)

Helper function to be called when a response matches the a pending request.

When sending blocks, the callback is only executed when the reply of the last block is received. i.e. it is not called when the code of the reply is ‘continue’ (2.31).

Enums

enum coap_option_num

Set of CoAP packet options we are aware of.

Users may add options other than these to their packets, provided they know how to format them correctly. The only restriction is that all options must be added to a packet in numeric order.

Refer to RFC 7252, section 12.2 for more information.

Values:

enumerator COAP_OPTION_IF_MATCH = 1

If-Match.

enumerator COAP_OPTION_URI_HOST = 3

Uri-Host.

enumerator COAP_OPTION_ETAG = 4

ETag.

enumerator COAP_OPTION_IF_NONE_MATCH = 5

If-None-Match.

enumerator COAP_OPTION_OBSERVE = 6

Observe (RFC 7641)

enumerator COAP_OPTION_URI_PORT = 7

Uri-Port.

enumerator COAP_OPTION_LOCATION_PATH = 8

Location-Path.

enumerator COAP_OPTION_URI_PATH = 11

Uri-Path.

enumerator COAP_OPTION_CONTENT_FORMAT = 12

Content-Format.

enumerator COAP_OPTION_MAX_AGE = 14

Max-Age.

enumerator COAP_OPTION_URI_QUERY = 15

Uri-Query.

enumerator COAP_OPTION_ACCEPT = 17

Accept.

enumerator COAP_OPTION_LOCATION_QUERY = 20

Location-Query.

enumerator COAP_OPTION_BLOCK2 = 23

Block2 (RFC 7959)

enumerator COAP_OPTION_BLOCK1 = 27

Block1 (RFC 7959)

enumerator COAP_OPTION_SIZE2 = 28

Size2 (RFC 7959)

enumerator COAP_OPTION_PROXY_URI = 35

Proxy-Uri.

enumerator COAP_OPTION_PROXY_SCHEME = 39

Proxy-Scheme.

enumerator COAP_OPTION_SIZE1 = 60

Size1.

enumerator COAP_OPTION_ECHO = 252

Echo (RFC 9175)

enumerator COAP_OPTION_REQUEST_TAG = 292

Request-Tag (RFC 9175)

enum coap_method

Available request methods.

To be used when creating a request or a response.

Values:

enumerator COAP_METHOD_GET = 1

GET.

enumerator COAP_METHOD_POST = 2

POST.

enumerator COAP_METHOD_PUT = 3

PUT.

enumerator COAP_METHOD_DELETE = 4

DELETE.

enumerator COAP_METHOD_FETCH = 5

FETCH.

enumerator COAP_METHOD_PATCH = 6

PATCH.

enumerator COAP_METHOD_IPATCH = 7

IPATCH.

enum coap_msgtype

CoAP packets may be of one of these types.

Values:

enumerator COAP_TYPE_CON = 0

Confirmable message.

The packet is a request or response the destination end-point must acknowledge.

enumerator COAP_TYPE_NON_CON = 1

Non-confirmable message.

The packet is a request or response that doesn’t require acknowledgements.

enumerator COAP_TYPE_ACK = 2

Acknowledge.

Response to a confirmable message.

enumerator COAP_TYPE_RESET = 3

Reset.

Rejecting a packet for any reason is done by sending a message of this type.

enum coap_response_code

Set of response codes available for a response packet.

To be used when creating a response.

Values:

enumerator COAP_RESPONSE_CODE_OK = ((2 << 5) | (0))

2.00 - OK

enumerator COAP_RESPONSE_CODE_CREATED = ((2 << 5) | (1))

2.01 - Created

enumerator COAP_RESPONSE_CODE_DELETED = ((2 << 5) | (2))

2.02 - Deleted

enumerator COAP_RESPONSE_CODE_VALID = ((2 << 5) | (3))

2.03 - Valid

enumerator COAP_RESPONSE_CODE_CHANGED = ((2 << 5) | (4))

2.04 - Changed

enumerator COAP_RESPONSE_CODE_CONTENT = ((2 << 5) | (5))

2.05 - Content

enumerator COAP_RESPONSE_CODE_CONTINUE = ((2 << 5) | (31))

2.31 - Continue

enumerator COAP_RESPONSE_CODE_BAD_REQUEST = ((4 << 5) | (0))

4.00 - Bad Request

enumerator COAP_RESPONSE_CODE_UNAUTHORIZED = ((4 << 5) | (1))

4.01 - Unauthorized

enumerator COAP_RESPONSE_CODE_BAD_OPTION = ((4 << 5) | (2))

4.02 - Bad Option

enumerator COAP_RESPONSE_CODE_FORBIDDEN = ((4 << 5) | (3))

4.03 - Forbidden

enumerator COAP_RESPONSE_CODE_NOT_FOUND = ((4 << 5) | (4))

4.04 - Not Found

enumerator COAP_RESPONSE_CODE_NOT_ALLOWED = ((4 << 5) | (5))

4.05 - Method Not Allowed

enumerator COAP_RESPONSE_CODE_NOT_ACCEPTABLE = ((4 << 5) | (6))

4.06 - Not Acceptable

enumerator COAP_RESPONSE_CODE_INCOMPLETE = ((4 << 5) | (8))

4.08 - Request Entity Incomplete

enumerator COAP_RESPONSE_CODE_CONFLICT = ((4 << 5) | (9))

4.12 - Precondition Failed

enumerator COAP_RESPONSE_CODE_PRECONDITION_FAILED = ((4 << 5) | (12))

4.12 - Precondition Failed

enumerator COAP_RESPONSE_CODE_REQUEST_TOO_LARGE = ((4 << 5) | (13))

4.13 - Request Entity Too Large

enumerator COAP_RESPONSE_CODE_UNSUPPORTED_CONTENT_FORMAT = ((4 << 5) | (15))

4.15 - Unsupported Content-Format

enumerator COAP_RESPONSE_CODE_UNPROCESSABLE_ENTITY = ((4 << 5) | (22))

4.22 - Unprocessable Entity

enumerator COAP_RESPONSE_CODE_TOO_MANY_REQUESTS = ((4 << 5) | (29))

4.29 - Too Many Requests

enumerator COAP_RESPONSE_CODE_INTERNAL_ERROR = ((5 << 5) | (0))

5.00 - Internal Server Error

enumerator COAP_RESPONSE_CODE_NOT_IMPLEMENTED = ((5 << 5) | (1))

5.01 - Not Implemented

enumerator COAP_RESPONSE_CODE_BAD_GATEWAY = ((5 << 5) | (2))

5.02 - Bad Gateway

enumerator COAP_RESPONSE_CODE_SERVICE_UNAVAILABLE = ((5 << 5) | (3))

5.03 - Service Unavailable

enumerator COAP_RESPONSE_CODE_GATEWAY_TIMEOUT = ((5 << 5) | (4))

5.04 - Gateway Timeout

enumerator COAP_RESPONSE_CODE_PROXYING_NOT_SUPPORTED = ((5 << 5) | (5))

5.05 - Proxying Not Supported

enum coap_content_format

Set of Content-Format option values for CoAP.

To be used when encoding or decoding a Content-Format option.

Values:

enumerator COAP_CONTENT_FORMAT_TEXT_PLAIN = 0

text/plain;charset=utf-8

application/link-format

enumerator COAP_CONTENT_FORMAT_APP_XML = 41

application/xml

enumerator COAP_CONTENT_FORMAT_APP_OCTET_STREAM = 42

application/octet-stream

enumerator COAP_CONTENT_FORMAT_APP_EXI = 47

application/exi

enumerator COAP_CONTENT_FORMAT_APP_JSON = 50

application/json

enumerator COAP_CONTENT_FORMAT_APP_JSON_PATCH_JSON = 51

application/json-patch+json

enumerator COAP_CONTENT_FORMAT_APP_MERGE_PATCH_JSON = 52

application/merge-patch+json

enumerator COAP_CONTENT_FORMAT_APP_CBOR = 60

application/cbor

enum coap_block_size

Represents the size of each block that will be transferred using block-wise transfers [RFC7959]:

Each entry maps directly to the value that is used in the wire.

https://tools.ietf.org/html/rfc7959

Values:

enumerator COAP_BLOCK_16

16-byte block size

enumerator COAP_BLOCK_32

32-byte block size

enumerator COAP_BLOCK_64

64-byte block size

enumerator COAP_BLOCK_128

128-byte block size

enumerator COAP_BLOCK_256

256-byte block size

enumerator COAP_BLOCK_512

512-byte block size

enumerator COAP_BLOCK_1024

1024-byte block size

Functions

uint8_t coap_header_get_version(const struct coap_packet *cpkt)

Returns the version present in a CoAP packet.

Parameters:
  • cpkt – CoAP packet representation

Returns:

the CoAP version in packet

uint8_t coap_header_get_type(const struct coap_packet *cpkt)

Returns the type of the CoAP packet.

Parameters:
  • cpkt – CoAP packet representation

Returns:

the type of the packet

uint8_t coap_header_get_token(const struct coap_packet *cpkt, uint8_t *token)

Returns the token (if any) in the CoAP packet.

Parameters:
  • cpkt – CoAP packet representation

  • token – Where to store the token, must point to a buffer containing at least COAP_TOKEN_MAX_LEN bytes

Returns:

Token length in the CoAP packet (0 - COAP_TOKEN_MAX_LEN).

uint8_t coap_header_get_code(const struct coap_packet *cpkt)

Returns the code of the CoAP packet.

Parameters:
  • cpkt – CoAP packet representation

Returns:

the code present in the packet

int coap_header_set_code(const struct coap_packet *cpkt, uint8_t code)

Modifies the code of the CoAP packet.

Parameters:
  • cpkt – CoAP packet representation

  • code – CoAP code

Returns:

0 on success, -EINVAL on failure

uint16_t coap_header_get_id(const struct coap_packet *cpkt)

Returns the message id associated with the CoAP packet.

Parameters:
  • cpkt – CoAP packet representation

Returns:

the message id present in the packet

const uint8_t *coap_packet_get_payload(const struct coap_packet *cpkt, uint16_t *len)

Returns the data pointer and length of the CoAP packet.

Parameters:
  • cpkt – CoAP packet representation

  • len – Total length of CoAP payload

Returns:

data pointer and length if payload exists NULL pointer and length set to 0 in case there is no payload

bool coap_uri_path_match(const char *const *path, struct coap_option *options, uint8_t opt_num)

Verify if CoAP URI path matches with provided options.

Parameters:
  • path – Null-terminated array of strings.

  • options – Parsed options from coap_packet_parse()

  • opt_num – Number of options

Returns:

true if the CoAP URI path matches, false otherwise.

int coap_packet_parse(struct coap_packet *cpkt, uint8_t *data, uint16_t len, struct coap_option *options, uint8_t opt_num)

Parses the CoAP packet in data, validating it and initializing cpkt.

data must remain valid while cpkt is used.

Parameters:
  • cpkt – Packet to be initialized from received data.

  • data – Data containing a CoAP packet, its data pointer is positioned on the start of the CoAP packet.

  • len – Length of the data

  • options – Parse options and cache its details.

  • opt_num – Number of options

Return values:
  • 0 – in case of success.

  • -EINVAL – in case of invalid input args.

  • -EBADMSG – in case of malformed coap packet header.

  • -EILSEQ – in case of malformed coap options.

int coap_packet_set_path(struct coap_packet *cpkt, const char *path)

Parses provided coap path (with/without query) or query and appends that as options to the cpkt.

Parameters:
  • cpkt – Packet to append path and query options for.

  • path – Null-terminated string of coap path, query or both.

Return values:

0 – in case of success or negative in case of error.

int coap_packet_init(struct coap_packet *cpkt, uint8_t *data, uint16_t max_len, uint8_t ver, uint8_t type, uint8_t token_len, const uint8_t *token, uint8_t code, uint16_t id)

Creates a new CoAP Packet from input data.

Parameters:
  • cpkt – New packet to be initialized using the storage from data.

  • data – Data that will contain a CoAP packet information

  • max_len – Maximum allowable length of data

  • ver – CoAP header version

  • type – CoAP header type

  • token_len – CoAP header token length

  • token – CoAP header token

  • code – CoAP header code

  • id – CoAP header message id

Returns:

0 in case of success or negative in case of error.

int coap_ack_init(struct coap_packet *cpkt, const struct coap_packet *req, uint8_t *data, uint16_t max_len, uint8_t code)

Create a new CoAP Acknowledgment message for given request.

This function works like coap_packet_init, filling CoAP header type, CoAP header token, and CoAP header message id fields according to acknowledgment rules.

Parameters:
  • cpkt – New packet to be initialized using the storage from data.

  • req – CoAP request packet that is being acknowledged

  • data – Data that will contain a CoAP packet information

  • max_len – Maximum allowable length of data

  • code – CoAP header code

Returns:

0 in case of success or negative in case of error.

uint8_t *coap_next_token(void)

Returns a randomly generated array of 8 bytes, that can be used as a message’s token.

Returns:

a 8-byte pseudo-random token.

uint16_t coap_next_id(void)

Helper to generate message ids.

Returns:

a new message id

int coap_find_options(const struct coap_packet *cpkt, uint16_t code, struct coap_option *options, uint16_t veclen)

Return the values associated with the option of value code.

Parameters:
  • cpkt – CoAP packet representation

  • code – Option number to look for

  • options – Array of coap_option where to store the value of the options found

  • veclen – Number of elements in the options array

Returns:

The number of options found in packet matching code, negative on error.

int coap_packet_append_option(struct coap_packet *cpkt, uint16_t code, const uint8_t *value, uint16_t len)

Appends an option to the packet.

Note: options can be added out of numeric order of their codes. But it’s more efficient to add them in order.

Parameters:
  • cpkt – Packet to be updated

  • code – Option code to add to the packet, see coap_option_num

  • value – Pointer to the value of the option, will be copied to the packet

  • len – Size of the data to be added

Returns:

0 in case of success or negative in case of error.

int coap_packet_remove_option(struct coap_packet *cpkt, uint16_t code)

Remove an option from the packet.

Parameters:
  • cpkt – Packet to be updated

  • code – Option code to remove from the packet, see coap_option_num

Returns:

0 in case of success or negative in case of error.

unsigned int coap_option_value_to_int(const struct coap_option *option)

Converts an option to its integer representation.

Assumes that the number is encoded in the network byte order in the option.

Parameters:
Returns:

The integer representation of the option

int coap_append_option_int(struct coap_packet *cpkt, uint16_t code, unsigned int val)

Appends an integer value option to the packet.

The option must be added in numeric order of their codes, and the least amount of bytes will be used to encode the value.

Parameters:
  • cpkt – Packet to be updated

  • code – Option code to add to the packet, see coap_option_num

  • val – Integer value to be added

Returns:

0 in case of success or negative in case of error.

int coap_packet_append_payload_marker(struct coap_packet *cpkt)

Append payload marker to CoAP packet.

Parameters:
  • cpkt – Packet to append the payload marker (0xFF)

Returns:

0 in case of success or negative in case of error.

int coap_packet_append_payload(struct coap_packet *cpkt, const uint8_t *payload, uint16_t payload_len)

Append payload to CoAP packet.

Parameters:
  • cpkt – Packet to append the payload

  • payload – CoAP packet payload

  • payload_len – CoAP packet payload len

Returns:

0 in case of success or negative in case of error.

bool coap_packet_is_request(const struct coap_packet *cpkt)

Check if a CoAP packet is a CoAP request.

Parameters:
  • cpkt – Packet to be checked.

Returns:

true if the packet is a request, false otherwise.

int coap_handle_request_len(struct coap_packet *cpkt, struct coap_resource *resources, size_t resources_len, struct coap_option *options, uint8_t opt_num, struct sockaddr *addr, socklen_t addr_len)

When a request is received, call the appropriate methods of the matching resources.

Parameters:
  • cpkt – Packet received

  • resources – Array of known resources

  • resources_len – Number of resources in the array

  • options – Parsed options from coap_packet_parse()

  • opt_num – Number of options

  • addr – Peer address

  • addr_len – Peer address length

Return values:
  • >= – 0 in case of success.

  • -ENOTSUP – in case of invalid request code.

  • -EPERM – in case resource handler is not implemented.

  • -ENOENT – in case the resource is not found.

int coap_handle_request(struct coap_packet *cpkt, struct coap_resource *resources, struct coap_option *options, uint8_t opt_num, struct sockaddr *addr, socklen_t addr_len)

When a request is received, call the appropriate methods of the matching resources.

Parameters:
  • cpkt – Packet received

  • resources – Array of known resources (terminated with empty resource)

  • options – Parsed options from coap_packet_parse()

  • opt_num – Number of options

  • addr – Peer address

  • addr_len – Peer address length

Return values:
  • >= – 0 in case of success.

  • -ENOTSUP – in case of invalid request code.

  • -EPERM – in case resource handler is not implemented.

  • -ENOENT – in case the resource is not found.

static inline uint16_t coap_block_size_to_bytes(enum coap_block_size block_size)

Helper for converting the enumeration to the size expressed in bytes.

Parameters:
  • block_size – The block size to be converted

Returns:

The size in bytes that the block_size represents

static inline enum coap_block_size coap_bytes_to_block_size(uint16_t bytes)

Helper for converting block size in bytes to enumeration.

NOTE: Only valid CoAP block sizes map correctly.

Parameters:
  • bytes – CoAP block size in bytes.

Returns:

enum coap_block_size

int coap_block_transfer_init(struct coap_block_context *ctx, enum coap_block_size block_size, size_t total_size)

Initializes the context of a block-wise transfer.

Parameters:
  • ctx – The context to be initialized

  • block_size – The size of the block

  • total_size – The total size of the transfer, if known

Returns:

0 in case of success or negative in case of error.

int coap_append_descriptive_block_option(struct coap_packet *cpkt, struct coap_block_context *ctx)

Append BLOCK1 or BLOCK2 option to the packet.

If the CoAP packet is a request then BLOCK1 is appended otherwise BLOCK2 is appended.

Parameters:
  • cpkt – Packet to be updated

  • ctx – Block context from which to retrieve the information for the block option

Returns:

0 in case of success or negative in case of error.

bool coap_has_descriptive_block_option(struct coap_packet *cpkt)

Check if a descriptive block option is set in the packet.

If the CoAP packet is a request then an available BLOCK1 option would be checked otherwise a BLOCK2 option would be checked.

Parameters:
  • cpkt – Packet to be checked.

Returns:

true if the corresponding block option is set, false otherwise.

int coap_remove_descriptive_block_option(struct coap_packet *cpkt)

Remove BLOCK1 or BLOCK2 option from the packet.

If the CoAP packet is a request then BLOCK1 is removed otherwise BLOCK2 is removed.

Parameters:
  • cpkt – Packet to be updated.

Returns:

0 in case of success or negative in case of error.

bool coap_block_has_more(struct coap_packet *cpkt)

Check if BLOCK1 or BLOCK2 option has more flag set.

Parameters:
  • cpkt – Packet to be checked.

Returns:

true If more flag is set in BLOCK1 or BLOCK2

Returns:

false If MORE flag is not set or BLOCK header not found.

int coap_append_block1_option(struct coap_packet *cpkt, struct coap_block_context *ctx)

Append BLOCK1 option to the packet.

Parameters:
  • cpkt – Packet to be updated

  • ctx – Block context from which to retrieve the information for the Block1 option

Returns:

0 in case of success or negative in case of error.

int coap_append_block2_option(struct coap_packet *cpkt, struct coap_block_context *ctx)

Append BLOCK2 option to the packet.

Parameters:
  • cpkt – Packet to be updated

  • ctx – Block context from which to retrieve the information for the Block2 option

Returns:

0 in case of success or negative in case of error.

int coap_append_size1_option(struct coap_packet *cpkt, struct coap_block_context *ctx)

Append SIZE1 option to the packet.

Parameters:
  • cpkt – Packet to be updated

  • ctx – Block context from which to retrieve the information for the Size1 option

Returns:

0 in case of success or negative in case of error.

int coap_append_size2_option(struct coap_packet *cpkt, struct coap_block_context *ctx)

Append SIZE2 option to the packet.

Parameters:
  • cpkt – Packet to be updated

  • ctx – Block context from which to retrieve the information for the Size2 option

Returns:

0 in case of success or negative in case of error.

int coap_get_option_int(const struct coap_packet *cpkt, uint16_t code)

Get the integer representation of a CoAP option.

Parameters:
  • cpkt – Packet to be inspected

  • code – CoAP option code

Returns:

Integer value >= 0 in case of success or negative in case of error.

int coap_get_block1_option(const struct coap_packet *cpkt, bool *has_more, uint32_t *block_number)

Get the block size, more flag and block number from the CoAP block1 option.

Parameters:
  • cpkt – Packet to be inspected

  • has_more – Is set to the value of the more flag

  • block_number – Is set to the number of the block

Returns:

Integer value of the block size in case of success or negative in case of error.

int coap_get_block2_option(const struct coap_packet *cpkt, bool *has_more, uint32_t *block_number)

Get values from CoAP block2 option.

Decode block number, more flag and block size from option.

Parameters:
  • cpkt – Packet to be inspected

  • has_more – Is set to the value of the more flag

  • block_number – Is set to the number of the block

Returns:

Integer value of the block size in case of success or negative in case of error.

int coap_update_from_block(const struct coap_packet *cpkt, struct coap_block_context *ctx)

Retrieves BLOCK{1,2} and SIZE{1,2} from cpkt and updates ctx accordingly.

Parameters:
  • cpkt – Packet in which to look for block-wise transfers options

  • ctx – Block context to be updated

Returns:

0 in case of success or negative in case of error.

int coap_next_block_for_option(const struct coap_packet *cpkt, struct coap_block_context *ctx, enum coap_option_num option)

Updates ctx according to option set in cpkt so after this is called the current entry indicates the correct offset in the body of data being transferred.

Parameters:
  • cpkt – Packet in which to look for block-wise transfers options

  • ctx – Block context to be updated

  • option – Either COAP_OPTION_BLOCK1 or COAP_OPTION_BLOCK2

Returns:

The offset in the block-wise transfer, 0 if the transfer has finished or a negative value in case of an error.

size_t coap_next_block(const struct coap_packet *cpkt, struct coap_block_context *ctx)

Updates ctx so after this is called the current entry indicates the correct offset in the body of data being transferred.

Parameters:
  • cpkt – Packet in which to look for block-wise transfers options

  • ctx – Block context to be updated

Returns:

The offset in the block-wise transfer, 0 if the transfer has finished.

void coap_observer_init(struct coap_observer *observer, const struct coap_packet *request, const struct sockaddr *addr)

Indicates that the remote device referenced by addr, with request, wants to observe a resource.

Parameters:
  • observer – Observer to be initialized

  • request – Request on which the observer will be based

  • addr – Address of the remote device

bool coap_register_observer(struct coap_resource *resource, struct coap_observer *observer)

After the observer is initialized, associate the observer with an resource.

Parameters:
  • resource – Resource to add an observer

  • observer – Observer to be added

Returns:

true if this is the first observer added to this resource.

bool coap_remove_observer(struct coap_resource *resource, struct coap_observer *observer)

Remove this observer from the list of registered observers of that resource.

Parameters:
  • resource – Resource in which to remove the observer

  • observer – Observer to be removed

Returns:

true if the observer was found and removed.

struct coap_observer *coap_find_observer(struct coap_observer *observers, size_t len, const struct sockaddr *addr, const uint8_t *token, uint8_t token_len)

Returns the observer that matches address addr and has token token.

Parameters:
  • observers – Pointer to the array of observers

  • len – Size of the array of observers

  • addr – Address of the endpoint observing a resource

  • token – Pointer to the token

  • token_len – Length of valid bytes in the token

Returns:

A pointer to a observer if a match is found, NULL otherwise.

struct coap_observer *coap_find_observer_by_addr(struct coap_observer *observers, size_t len, const struct sockaddr *addr)

Returns the observer that matches address addr.

Note

The function coap_find_observer() should be preferred if both the observer’s address and token are known.

Parameters:
  • observers – Pointer to the array of observers

  • len – Size of the array of observers

  • addr – Address of the endpoint observing a resource

Returns:

A pointer to a observer if a match is found, NULL otherwise.

struct coap_observer *coap_find_observer_by_token(struct coap_observer *observers, size_t len, const uint8_t *token, uint8_t token_len)

Returns the observer that has token token.

Note

The function coap_find_observer() should be preferred if both the observer’s address and token are known.

Parameters:
  • observers – Pointer to the array of observers

  • len – Size of the array of observers

  • token – Pointer to the token

  • token_len – Length of valid bytes in the token

Returns:

A pointer to a observer if a match is found, NULL otherwise.

struct coap_observer *coap_observer_next_unused(struct coap_observer *observers, size_t len)

Returns the next available observer representation.

Parameters:
  • observers – Pointer to the array of observers

  • len – Size of the array of observers

Returns:

A pointer to a observer if there’s an available observer, NULL otherwise.

void coap_reply_init(struct coap_reply *reply, const struct coap_packet *request)

Indicates that a reply is expected for request.

Parameters:
  • reply – Reply structure to be initialized

  • request – Request from which reply will be based

int coap_pending_init(struct coap_pending *pending, const struct coap_packet *request, const struct sockaddr *addr, const struct coap_transmission_parameters *params)

Initialize a pending request with a request.

The request’s fields are copied into the pending struct, so request doesn’t have to live for as long as the pending struct lives, but “data” that needs to live for at least that long.

Parameters:
  • pending – Structure representing the waiting for a confirmation message, initialized with data from request

  • request – Message waiting for confirmation

  • addr – Address to send the retransmission

  • params – Pointer to the CoAP transmission parameters struct, or NULL to use default values

Returns:

0 in case of success or negative in case of error.

struct coap_pending *coap_pending_next_unused(struct coap_pending *pendings, size_t len)

Returns the next available pending struct, that can be used to track the retransmission status of a request.

Parameters:
Returns:

pointer to a free coap_pending structure, NULL in case none could be found.

struct coap_reply *coap_reply_next_unused(struct coap_reply *replies, size_t len)

Returns the next available reply struct, so it can be used to track replies and notifications received.

Parameters:
  • replies – Pointer to the array of coap_reply structures

  • len – Size of the array of coap_reply structures

Returns:

pointer to a free coap_reply structure, NULL in case none could be found.

struct coap_pending *coap_pending_received(const struct coap_packet *response, struct coap_pending *pendings, size_t len)

After a response is received, returns if there is any matching pending request exits.

User has to clear all pending retransmissions related to that response by calling coap_pending_clear().

Parameters:
  • response – The received response

  • pendings – Pointer to the array of coap_reply structures

  • len – Size of the array of coap_reply structures

Returns:

pointer to the associated coap_pending structure, NULL in case none could be found.

struct coap_reply *coap_response_received(const struct coap_packet *response, const struct sockaddr *from, struct coap_reply *replies, size_t len)

After a response is received, call coap_reply_t handler registered in coap_reply structure.

Parameters:
  • response – A response received

  • from – Address from which the response was received

  • replies – Pointer to the array of coap_reply structures

  • len – Size of the array of coap_reply structures

Returns:

Pointer to the reply matching the packet received, NULL if none could be found.

struct coap_pending *coap_pending_next_to_expire(struct coap_pending *pendings, size_t len)

Returns the next pending about to expire, pending->timeout informs how many ms to next expiration.

Parameters:
Returns:

The next coap_pending to expire, NULL if none is about to expire.

bool coap_pending_cycle(struct coap_pending *pending)

After a request is sent, user may want to cycle the pending retransmission so the timeout is updated.

Parameters:
  • pending – Pending representation to have its timeout updated

Returns:

false if this is the last retransmission.

void coap_pending_clear(struct coap_pending *pending)

Cancels the pending retransmission, so it again becomes available.

Parameters:
  • pending – Pending representation to be canceled

void coap_pendings_clear(struct coap_pending *pendings, size_t len)

Cancels all pending retransmissions, so they become available again.

Parameters:
size_t coap_pendings_count(struct coap_pending *pendings, size_t len)

Count number of pending requests.

Parameters:
  • len – Number of elements in array.

  • pendings – Array of pending requests.

Returns:

count of elements where timeout is not zero.

void coap_reply_clear(struct coap_reply *reply)

Cancels awaiting for this reply, so it becomes available again.

User responsibility to free the memory associated with data.

Parameters:
  • reply – The reply to be canceled

void coap_replies_clear(struct coap_reply *replies, size_t len)

Cancels all replies, so they become available again.

Parameters:
  • replies – Pointer to the array of coap_reply structures

  • len – Size of the array of coap_reply structures

int coap_resource_notify(struct coap_resource *resource)

Indicates that this resource was updated and that the notify callback should be called for every registered observer.

Parameters:
  • resource – Resource that was updated

Returns:

0 in case of success or negative in case of error.

bool coap_request_is_observe(const struct coap_packet *request)

Returns if this request is enabling observing a resource.

Parameters:
  • request – Request to be checked

Returns:

True if the request is enabling observing a resource, False otherwise

struct coap_transmission_parameters coap_get_transmission_parameters(void)

Get currently active CoAP transmission parameters.

Returns:

CoAP transmission parameters structure.

void coap_set_transmission_parameters(const struct coap_transmission_parameters *params)

Set CoAP transmission parameters.

Parameters:
  • params – Pointer to the transmission parameters structure.

int coap_well_known_core_get(struct coap_resource *resource, const struct coap_packet *request, struct coap_packet *response, uint8_t *data, uint16_t data_len)

Build a CoAP response for a .well-known/core CoAP request.

Parameters:
  • resource – Array of known resources, terminated with an empty resource

  • request – A pointer to the .well-known/core CoAP request

  • response – A pointer to a CoAP response, will be initialized

  • data – A data pointer to be used to build the CoAP response

  • data_len – The maximum length of the data buffer

Returns:

0 in case of success or negative in case of error.

int coap_well_known_core_get_len(struct coap_resource *resources, size_t resources_len, const struct coap_packet *request, struct coap_packet *response, uint8_t *data, uint16_t data_len)

Build a CoAP response for a .well-known/core CoAP request.

Parameters:
  • resources – Array of known resources

  • resources_len – Number of resources in the array

  • request – A pointer to the .well-known/core CoAP request

  • response – A pointer to a CoAP response, will be initialized

  • data – A data pointer to be used to build the CoAP response

  • data_len – The maximum length of the data buffer

Returns:

0 in case of success or negative in case of error.

struct coap_resource
#include <coap.h>

Description of CoAP resource.

CoAP servers often want to register resources, so that clients can act on them, by fetching their state or requesting updates to them.

Public Members

coap_method_t get

Which function to be called for each CoAP method.

coap_notify_t notify

Notify function to call.

const char *const *path

Resource path.

void *user_data

User specific opaque data.

sys_slist_t observers

List of resource observers.

int age

Resource age.

struct coap_observer
#include <coap.h>

Represents a remote device that is observing a local resource.

Public Members

sys_snode_t list

Observer list node.

struct sockaddr addr

Observer connection end point information.

uint8_t token[8]

Observer token.

uint8_t tkl

Extended token length.

struct coap_packet
#include <coap.h>

Representation of a CoAP Packet.

Public Members

uint8_t *data

User allocated buffer.

uint16_t offset

CoAP lib maintains offset while adding data.

uint16_t max_len

Max CoAP packet data length.

uint8_t hdr_len

CoAP header length.

uint16_t opt_len

Total options length (delta + len + value)

uint16_t delta

Used for delta calculation in CoAP packet.

struct coap_option
#include <coap.h>

Representation of a CoAP option.

Public Members

uint16_t delta

Option delta.

uint8_t len

Option length.

uint8_t value[12]

Option value.

struct coap_transmission_parameters
#include <coap.h>

CoAP transmission parameters.

Public Members

uint32_t ack_timeout

Initial ACK timeout.

Value is used as a base value to retry pending CoAP packets.

uint16_t coap_backoff_percent

Set CoAP retry backoff factor.

A value of 200 means a factor of 2.0.

uint8_t max_retransmission

Maximum number of retransmissions.

struct coap_pending
#include <coap.h>

Represents a request awaiting for an acknowledgment (ACK).

Public Members

struct sockaddr addr

Remote address.

int64_t t0

Time when the request was sent.

uint32_t timeout

Timeout in ms.

uint16_t id

Message id.

uint8_t *data

User allocated buffer.

uint16_t len

Length of the CoAP packet.

uint8_t retries

Number of times the request has been sent.

struct coap_transmission_parameters params

Transmission parameters.

struct coap_reply
#include <coap.h>

Represents the handler for the reply of a request, it is also used when observing resources.

Public Members

coap_reply_t reply

CoAP reply callback.

void *user_data

User specific opaque data.

int age

Reply age.

uint16_t id

Reply id.

uint8_t token[8]

Reply token.

uint8_t tkl

Extended token length.

struct coap_block_context
#include <coap.h>

Represents the current state of a block-wise transaction.

Public Members

size_t total_size

Total size of the block-wise transaction.

size_t current

Current size of the block-wise transaction.

enum coap_block_size block_size

Block size.

struct coap_core_metadata
#include <coap_link_format.h>

In case you want to add attributes to the resources included in the ‘well-known/core’ “virtual” resource, the ‘user_data’ field should point to a valid coap_core_metadata structure.

Public Members

const char *const *attributes

List of attributes to add.

void *user_data

User specific data.