ProsecCoAP 🥂
 
Loading...
Searching...
No Matches
Coap::Message Class Reference

A CoAP message. More...

#include <ProsecCoAP.h>

Public Member Functions

void setId (uint16_t id)
 Set the message ID.
 
 Message ()
 Builds a default CoAP message.
 
 Message (MessageType type, MessageCode code)
 Builds a CoAP message with the given type and code.
 
 Message (MessageType type, MessageCode code, uint16_t id)
 Builds a CoAP message explictly specifying type, code and message ID.
 
const uint8_t * asRaw () const
 Get the raw binary representation of the message.
 
ErrorCode intoResponse (const Message &request, MessageCode code, MessageType type)
 Convert the message into a response to the given request.
 
ErrorCode intoResponse (const Message &request, MessageCode code)
 Convert the message into an ACK response to the given request.
 
uint8_t getVersion () const
 Get the CoAP version of this message.
 
size_t getLength () const
 Get the message length.
 
void setType (MessageType type)
 Set the message type.
 
MessageType getType () const
 Get the message type.
 
void setCode (MessageCode code)
 Set the message code.
 
MessageCode getCode () const
 Get the message code.
 
uint16_t getId () const
 Get the message ID.
 
size_t getTokenLength () const
 Get the current token length.
 
ErrorCode setToken (const uint8_t *token, size_t length)
 Sets the token of the message with the given value and length.
 
ErrorCode addRandomToken (size_t length)
 Add a token of the given length to the message.
 
const uint8_t * getToken () const
 Get the pointer to the current token.
 
bool matchesToken (const uint8_t *token, size_t length) const
 Check if the message token matches the given token and length.
 
OptionIterator getOptionIterator () const
 Return an iterator over the message options.
 
ErrorCode getOption (OptionNumber number, Option &option) const
 Return the first occurrence of the specified option.
 
ErrorCode addOption (OptionNumber number, const uint8_t *value, size_t length)
 Add an option to the message.
 
ErrorCode addOption (Option option)
 Add an option to the message.
 
ErrorCode addHost (IPAddress ip)
 Add the Uri-Host option to the message.
 
ErrorCode addPort (uint16_t port)
 Add the Uri-Port option to the message.
 
ErrorCode addPath (const char *path)
 Add the URI path and query to the message.
 
ErrorCode getPath (String &path) const
 Retrieve all the URI path and URI query options from the message and concatenate them into a single string.
 
ErrorCode getPayload (const uint8_t *&payload, size_t &length) const
 Get the payload from the message.
 
ErrorCode addPayload (const uint8_t *payload, size_t length)
 Add a payload to the message.
 
ErrorCode addPayload (const uint8_t *payload, size_t length, ContentFormat format)
 Add a payload and the Content-Format option to the message.
 
ErrorCode getObserveValue (uint32_t &observeValue)
 Extract the Observe option value, if present.
 
ErrorCode getMaxAge (uint32_t &age)
 Get the MAX_AGE option value from the message.
 
ErrorCode setMaxAge (uint32_t age)
 Add the MAX_AGE option to the message.
 
bool isObserveRegister ()
 Check if the message is an Observe register GET request.
 
bool isObserveDeregister ()
 Check if the message is an Observe deregister GET request.
 
ErrorCode intoNotification (Observer &observer)
 Convert the message into a notification message for the given observer.
 

Static Public Member Functions

static ErrorCode fromUdp (UDP *udp, Message &message)
 Build a CoAP message reading from a UDP instance.
 

Detailed Description

A CoAP message.

This is a view on the binary representation of a CoAP message. The intended use is to build a CoAP message to be sent, or to parse a received CoAP message.

As a minimum, a Message instance has a valid header.

See https://datatracker.ietf.org/doc/html/rfc7252#section-3

Constructor & Destructor Documentation

◆ Message() [1/3]

Coap::Message::Message ( )
inline

Builds a default CoAP message.

The version is set to COAP_VERSION. The type is set to COAP_NON. The code is set to COAP_EMPTY. The token length is set to 0. The message ID is assigned automatically.

◆ Message() [2/3]

Coap::Message::Message ( MessageType type,
MessageCode code )
inline

Builds a CoAP message with the given type and code.

The version is set to COAP_VERSION. The token length is set to 0. The message ID is assigned automatically.

Parameters
typeThe message type.
codeThe message code.

◆ Message() [3/3]

Coap::Message::Message ( MessageType type,
MessageCode code,
uint16_t id )

Builds a CoAP message explictly specifying type, code and message ID.

The version is set to COAP_VERSION. The token length is set to 0.

Parameters
typeThe message type.
codeThe message code.
idThe message ID.

Member Function Documentation

◆ addHost()

ErrorCode Coap::Message::addHost ( IPAddress ip)

Add the Uri-Host option to the message.

It converts the given IP address to string format and adds it as the Uri-Host option, as per RFC 7252 Section 6.4. The Uri-Host option is not compulsory. As per Section 6.5, if not present, the the destination IP address where the message is being sent will be used.

See also
addOption
Parameters
ipThe IP address to set as the Uri-Host.
Returns
An error code indicating success or failure.

◆ addOption() [1/2]

ErrorCode Coap::Message::addOption ( Option option)
inline

◆ addOption() [2/2]

ErrorCode Coap::Message::addOption ( OptionNumber number,
const uint8_t * value,
size_t length )

Add an option to the message.

The option is added according to the CoAP option encoding rules. For options that can be added at most once, this function follows a "first add wins" policy. Any subsequent addition of the same option number will return ErrorCode::NOT_SUPPORTED. For options that can appear multiple times, this function appends the new option to the existing ones.

If adding the option will result in exceeding the limits specified by RFC 7252 Section 5.10, the error code ErrorCode::NOT_SUPPORTED is returned. For options that can appear multiple times, the option is appended after the existing ones.

Warning
This is a low-level method. Caller has the responsibility to produce a valid option according to the CoAP specification. Avoid overflows by validating the option length.

Prefer using specialized methods for common options like COAP_CONTENT_FORMAT, COAP_URI_PATH, or COAP_URI_QUERY when available.

Parameters
numberOption number, as defined in the CoAP specification.
valuePointer to the option value.
lengthLength of the option value.
Returns
An error code indicating success or failure. ErrorCode::NOT_SUPPORTED is returned if adding the option would exceed the maximum number of allowed options for that number. An ErrorCode::MESSAGE_TOO_LARGE is returned if adding the option would exceed the maximum message size (COAP_MAX_MESSAGE_SIZE).
See also
https://datatracker.ietf.org/doc/html/rfc7252#section-3.1
Option value format https://datatracker.ietf.org/doc/html/rfc7252#section-3.2

◆ addPath()

ErrorCode Coap::Message::addPath ( const char * path)

Add the URI path and query to the message.

It follows section "Decomposing URIs into Options" https://datatracker.ietf.org/doc/html/rfc7252#section-6.4 to encode the path into the necessary Uri-Path and Uri-Query options.

Warning
Existing Uri-Path and Uri-Query options are not removed before adding the new ones. In general, this method should be called only once per message, as multiple calls may result in a malformed message.
Parameters
pathThe URI path + query associated with the recipient, null terminated. Initial and trailing slashes are ignored. Valid examples are: sensors/temp /sensors/temp?unit=celsius ` Individual Uri-Path and Uri-Query segments cannot exceed 255 bytes, as per specification.
Returns
An error code indicating success or failure.

◆ addPayload() [1/2]

ErrorCode Coap::Message::addPayload ( const uint8_t * payload,
size_t length )

Add a payload to the message.

If a payload is already present, this function will return an error.

Parameters
payloadPointer to the payload data.
lengthLength of the payload data.
formatThe content format of the payload.
Returns
An error code indicating success or failure. Returns ErrorCode::NOT_SUPPORTED if a payload is already present. Returns ErrorCode::INVALID_ARGUMENT if the provided payload is empty.
See also
addPayload(const uint8_t *payload, size_t length, ContentFormat format) for the variant that also adds the Content-Format option.

◆ addPayload() [2/2]

ErrorCode Coap::Message::addPayload ( const uint8_t * payload,
size_t length,
ContentFormat format )

Add a payload and the Content-Format option to the message.

If a payload or a Content-Format option are already present, this function will return an error.

Parameters
payloadPointer to the payload data.
lengthLength of the payload data.
formatThe content format of the payload.
Returns
An error code indicating success or failure.
See also
addPayload(const uint8_t *payload, size_t length) for the variant without Content-Format option.

◆ addPort()

ErrorCode Coap::Message::addPort ( uint16_t port)

Add the Uri-Port option to the message.

It adds the Uri-Port option as per RFC 7252 Section 6.4. The Uri-Port option is not compulsory. As per Section 6.5, if not present, the the default CoAP port COAP_DEFAULT_PORT will be used.

Any existing Uri-Port option is removed before adding the new one.

Parameters
portThe port number to set as the Uri-Port.
Returns
An error code indicating success or failure.

◆ addRandomToken()

ErrorCode Coap::Message::addRandomToken ( size_t length)

Add a token of the given length to the message.

A random token is generated and added to the message as per specifications. If present, the previous token is replaced.

The token is an optional field in a CoAP message. It is intended for use as a client-local identifier for differentiating between concurrent requests.

Parameters
lengthThe length (in bytes) of the token. The maximum length is COAP_MAX_TOKEN_LENGTH bytes.
Returns
An error code. ErrorCode::OK for success.

Example:

CoapMessage msg;
const uint8_t* token = msg.addRandomToken(4);

◆ asRaw()

const uint8_t * Coap::Message::asRaw ( ) const
inline

Get the raw binary representation of the message.

The returned pointer is valid as long as the message exists.

Returns
Pointer to the raw message data.

◆ fromUdp()

ErrorCode Coap::Message::fromUdp ( UDP * udp,
Message & message )
static

Build a CoAP message reading from a UDP instance.

Parameters
udpA pointer to the UDP instance containing the received message.
messageThe CoAP message to populate.
Returns
Returns ErrorCode::OK on success. Return ErrorCode::NOT_FOUND if no packet was found (a size < COAP_HEADER_SIZE is considered as such). It returns ErrorCode::NOT_SUPPORTED if the length of the received packet is > COAP_MAX_MESSAGE_SIZE. It returns ErrorCode::NETWORK if an error occurred while reading from UDP. It returns ErrorCode::NOT_SUPPORTED if the message version is not COAP_VERSION.

◆ getCode()

MessageCode Coap::Message::getCode ( ) const

Get the message code.

The code is always present in a CoAP message.

◆ getId()

uint16_t Coap::Message::getId ( ) const

Get the message ID.

The message ID is always present in a CoAP message.

Returns
The 16-bit message ID.
Note
The role of a message ID is to detect duplicate messages and handle reliability (ACK/RST, protocol level).

◆ getLength()

size_t Coap::Message::getLength ( ) const
inline

Get the message length.

Returns
The length of the message in bytes.

◆ getMaxAge()

ErrorCode Coap::Message::getMaxAge ( uint32_t & age)

Get the MAX_AGE option value from the message.

The MAX_AGE option indicates the maximum age of the resource representation in seconds, as per RFC 7252 Section 5.10.1. This is used for caching purposes.

If the MAX_AGE option is not present in the message, the default value of 60 seconds is returned, as per RFC 7252 Section 5.10.1: "If the Max-Age option is not present, the default value is 60 seconds."

Parameters
[out]ageThe output parameter to store the MAX_AGE option value in seconds.
Returns
An error code indicating success or failure. It returns ErrorCode::OK if the MAX_AGE option is present. It returns ErrorCode::NOT_FOUND if the MAX_AGE option is not present in the message (default value will be set). Other error codes may be returned in case of message parsing errors.
Note
The MAX_AGE option value is a 32-bit unsigned integer (0-4294967295 seconds, ~136 years). The default value of 60 seconds is set when the option is absent.

◆ getObserveValue()

ErrorCode Coap::Message::getObserveValue ( uint32_t & observeValue)

Extract the Observe option value, if present.

On a request, the observe value is either the register or deregister value, ObserveValue. On a notification, the observe value is a 24-bit sequential number that is incremented for each notification sent to an observer.

Parameters
[out]observeValueThe output parameter to store the Observe option value. The Observe option value is a 24-bit unsigned integer, but it is stored in a 32-bit variable. The value is valid only if the function returns ErrorCode::OK.
Returns
An error code indicating success or failure. It returns ErrorCode::OK if the Observe option is present and the value is successfully extracted. It returns ErrorCode::NOT_FOUND if the Observe option is not present in the message. Other error codes may be returned.

◆ getOption()

ErrorCode Coap::Message::getOption ( OptionNumber number,
Option & option ) const

Return the first occurrence of the specified option.

Parameters
numberThe option number to search for.
[out]optionThe output parameter to store the option if found.
Returns
Returns ErrorCode::OK if the option is found and stored in the output parameter, ErrorCode::NOT_FOUND if the option is not found, or other error codes in case of failure.
See also
getOptionIterator() for a more efficient way to iterate through all the options.
Note
Most options can appear at most once in a CoAP message. For such options, this method is sufficient to check for their presence and retrieve their value. For options that can appear multiple times, this method only retrieves the first occurrence. In such cases, it is recommended to use getOptionIterator() to iterate through all occurrences of the option.
See also
getPath() for a convenience method that retrieves all URI path and query options and concatenates them into a single string.

◆ getOptionIterator()

OptionIterator Coap::Message::getOptionIterator ( ) const

Return an iterator over the message options.

Returns
An option iterator, OptionIterator.

◆ getPath()

ErrorCode Coap::Message::getPath ( String & path) const

Retrieve all the URI path and URI query options from the message and concatenate them into a single string.

Parameters
[out]pathThe String object where the path (and query) will be stored.
Returns
An error code indicating success or failure.

Example usage:

String path;
path.reserve(100); // OPTIONAL: Reserve some space to avoid dynamic resizing during concatenation.
if (msg.getPath(path) == Coap::ErrorCode::OK)
{
Serial.println(path);
}

◆ getPayload()

ErrorCode Coap::Message::getPayload ( const uint8_t *& payload,
size_t & length ) const

Get the payload from the message.

The payload is a raw set of bytes. To interpret it, refer to the Content-Format option, if present.

Parameters
[out]payloadPointer to the payload within the message.
Warning
The pointer is valid as long as the message exists.
Parameters
[out]lengthThe payload length.
Returns
An error code. ErrorCode::OK for success.

Example:

const uint8_t *payload;
size_t length;
msg.getPayload(payload, length);
A CoAP message.
Definition ProsecCoAP.h:164
ErrorCode getPayload(const uint8_t *&payload, size_t &length) const
Get the payload from the message.
Definition ProsecCoAP.cpp:788

◆ getToken()

const uint8_t * Coap::Message::getToken ( ) const

Get the pointer to the current token.

See also
getTokenLength() to get the token length in bytes (which may also be zero).
Parameters
[out]bufferPointer to the token within the message.
Warning
The pointer is valid as long as the message exists.
Parameters
[out]lengthThe token length.
Returns
An error code. ErrorCode::OK for success.

Example:

const uint8_t *token;
size_t length;
msg.getToken(token, length);
const uint8_t * getToken() const
Get the pointer to the current token.
Definition ProsecCoAP.cpp:282

◆ getTokenLength()

size_t Coap::Message::getTokenLength ( ) const

Get the current token length.

Returns
The token length in bytes.

◆ getType()

MessageType Coap::Message::getType ( ) const

Get the message type.

The type is always present in a CoAP message.

◆ getVersion()

uint8_t Coap::Message::getVersion ( ) const
inline

Get the CoAP version of this message.

The version is always present in a CoAP message. Messages built with the library should always have version COAP_VERSION.

Returns
The 2-bit CoAP version as uint8_t.

◆ intoNotification()

ErrorCode Coap::Message::intoNotification ( Observer & observer)

Convert the message into a notification message for the given observer.

The message will be converted to notification, modifying:

  • Token and its length, set as the token from the observer (any existing token will be overwritten).
  • Observe option with the appropriate incremental value taken from the observer.
Parameters
observerThe observer to notify. The observer incremental value will be updated accordingly.
Returns
An error code indicating success or failure. It returns ErrorCode::OK on success.
Note
This does not set any other fields of the message, such as type, code, payload, etc. The caller is responsible for setting the notification as MessageType::NON or MessageType::CON. Please note that a server that transmits notifications mostly in non-confirmable messages MUST send a notification in a confirmable message instead of a non-confirmable message at least every 24 hours.
See also
https://datatracker.ietf.org/doc/html/rfc7641#section-3.5
https://datatracker.ietf.org/doc/html/rfc7641#section-4.2
https://datatracker.ietf.org/doc/html/rfc7641#section-4.5

◆ intoResponse() [1/2]

ErrorCode Coap::Message::intoResponse ( const Message & request,
MessageCode code )
inline

Convert the message into an ACK response to the given request.

Parameters
requestThe request message.
codeThe response message code.
Returns
An error code indicating success or failure. It returns ErrorCode::OK on success.
See also
intoResponse(const Message &request, MessageCode code, MessageType type) for a more general method that allows specifying the response type.

◆ intoResponse() [2/2]

ErrorCode Coap::Message::intoResponse ( const Message & request,
MessageCode code,
MessageType type )

Convert the message into a response to the given request.

The message ID is copied from the request. The type is set to MessageType::ACK. The response code is set to the given input code. If the request has a token, the same token is copied to the response.

Parameters
requestThe request message.
codeThe response message code.
typeThe response message type.
Returns
An error code indicating success or failure. It returns ErrorCode::OK on success.

◆ isObserveDeregister()

bool Coap::Message::isObserveDeregister ( )

Check if the message is an Observe deregister GET request.

A client may explicitly cancel an observation relationship by sending a GET request with the Observe option set to ObserveValue::DEREGISTER.

The caller has the responsibility to cancel the observer if all other conditions are met (e.g. Uri-Path, token, etc.).

Returns
True if the message is an Observe deregister request, false in all other cases.

◆ isObserveRegister()

bool Coap::Message::isObserveRegister ( )

Check if the message is an Observe register GET request.

As per https://datatracker.ietf.org/doc/html/rfc7641#section-3.1 an Observe register request is a GET request that includes the Observe option with the value ObserveValue::REGISTER.

The caller has the responsibility to register the observer to the specific resource.

Returns
True if the message is an Observe register request, false in all other cases.

◆ matchesToken()

bool Coap::Message::matchesToken ( const uint8_t * token,
size_t length ) const

Check if the message token matches the given token and length.

Parameters
tokenPointer to the token to match.
lengthLength of the token to match in bytes.
Returns
True if the message token matches the given token and length, false otherwise.
Note
Zero-length tokens are valid. Two messages with zero-length tokens are considered to match each other.

◆ setCode()

void Coap::Message::setCode ( MessageCode code)

Set the message code.

Parameters
codeThe message code to set.

◆ setId()

void Coap::Message::setId ( uint16_t id)

Set the message ID.

Writes on byte 2 and 3 of the message to set the message ID.

Parameters
idThe message ID to set.

◆ setMaxAge()

ErrorCode Coap::Message::setMaxAge ( uint32_t age)

Add the MAX_AGE option to the message.

The MAX_AGE option indicates the maximum age of the resource representation in seconds, as per RFC 7252 Section 5.10.1. This is used for caching purposes.

If a MAX_AGE option is already present, this function will return an error.

Parameters
ageThe maximum age value in seconds.
Returns
Returns ErrorCode::OK or other error code indicating specific failure.

◆ setToken()

ErrorCode Coap::Message::setToken ( const uint8_t * token,
size_t length )

Sets the token of the message with the given value and length.

Any existing token is removed before setting the new one.

Parameters
tokenPointer to the token data.
lengthLength of the token in bytes.
Returns
An error code indicating success or failure. Particularly, it returns ErrorCode::INVALID_ARGUMENT if the token length exceeds COAP_MAX_TOKEN_LENGTH.

The token matches the request to the response (application level).

See also
matchesToken(const uint8_t *token, size_t length) to check if the message token matches a given token.

◆ setType()

void Coap::Message::setType ( MessageType type)

Set the message type.

Parameters
typeThe message type to set.

The documentation for this class was generated from the following files: