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

A CoAP message. More...

#include <ProsecCoAP.h>

Public Member Functions

 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 buildResponse (MessageCode code, Message &response) const
 Build a response message based on a request message.
 
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 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.
 
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 buildNotification (Observer &observer, Message &notification) const
 Build 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 to add options. It does not perform validation of the option length. It is the caller's responsibility to ensure that the option is valid according to the CoAP specification.

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

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

Parameters
numberThe option number, as defined in the CoAP specification.
valueThe pointer to the option value.
lengthThe length 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).

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

◆ buildNotification()

ErrorCode Coap::Message::buildNotification ( Observer & observer,
Message & notification ) const

Build a notification message for the given observer.

The original message is not affected. It will be copied and used as base for the new notification. The notification will be a copy of the original message with the following modifications:

  • A new message ID.
  • Message type set to MessageType::NON by default (you can change it manually if needed).
  • Token and its length set as the token from the observer.
  • Observe option with the appropriate incremental value taken from the observer.
Note
This does not set any other field. Options like Uri-Host or Uri-Port should be set manually if necessary.

After building the notification, it can be sent as any other message using the Node::sendMessage method.

See also
https://datatracker.ietf.org/doc/html/rfc7641#section-3.5
Parameters
observerThe observer to notify. The observer incremental value will be updated accordingly.
[out]notificationThe base notification message to send to the observer.
Returns
An error code indicating success or failure. It returns ErrorCode::OK on success.

◆ buildResponse()

ErrorCode Coap::Message::buildResponse ( MessageCode code,
Message & response ) const

Build a response message based on a request message.

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. The rest of the message is initialized as per default constructor Message().

Parameters
requestThe request message to base the response on.
codeThe response message code.
[out]responseThe response message to populate.
Returns
An error code indicating success or failure. It returns ErrorCode::OK on success.

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

◆ getLength()

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

Get the message length.

Returns
The length of the message in bytes.

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

◆ 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]pathPointer to a 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:161
ErrorCode getPayload(const uint8_t *&payload, size_t &length) const
Get the payload from the message.
Definition ProsecCoAP.cpp:747

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

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

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

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