nRF5 IoT SDK  v0.9.0
 All Data Structures Functions Variables Typedefs Enumerations Enumerator Groups Pages
CoAP Block

The CoAP block library supports encoding and decoding of block1 options (request messages) in CoAP. The application has to handle all decision making in a block transfer as the library only handles encoding and decoding of the options values into structures.

Decode block1 option

Below is an example on how to locate the option index of the block1 option, followed by decoding of the block1 option into a block1 option structure using the coap_block_opt_block1_decode function.

uint32_t err_code;
uint8_t option_index;
uint32_t block1_opt_value_raw;
coap_block_opt_block1_t block1_request;
// Locate the index of the COAP_OPT_BLOCK1 option in the request.
err_code = coap_message_opt_index_get(&option_index, p_request, COAP_OPT_BLOCK1)
if (err_code == NRF_SUCCESS)
{
// Fetch the option by index.
coap_option_t * p_block1_opt = &p_request->options[option_index];
// Convert the option into a uint32_t.
err_code = coap_opt_uint_decode(&block1_opt_value_raw,
p_block1_opt->length,
p_block1_opt->p_data);
APP_ERROR_CHECK(err_code);
// Decode the uint32_t value into block1 option structure using the CoAP block API.
err_code = coap_block_opt_block1_decode(&block1_request, block1_opt_value_raw);
APP_ERROR_CHECK(err_code);
...
}

Encode block1 option

The example below shows how to encode a block1 structure into a uint32_t using the coap_block_opt_block1_encode function, then how to add it to the message and set the correct CoAP message code. The CoAP code will depend on whether the transaction is completed or not. In the case of a complete transaction, the more bit should also be 0 in addition to COAP_CODE_204_CHANGED CoAP message code.

uint32_t err_code;
uint32_t block1_response_encoded;
// Set up block1 response option values.
coap_block_opt_block1_t block1_response =
{
.number = 0, // Block number 0.
.more = 1, // There is more to come.
.size = 64 // Block size of 64
};
// Encode the block1 option into a uint32_t.
err_code = coap_block_opt_block1_encode(&block1_response_encoded, &block1_response);
APP_ERROR_CHECK(err_code);
// Add block1 option to the coap response message.
err_code = coap_message_opt_uint_add(p_response, COAP_OPT_BLOCK1, block1_response_encoded);
APP_ERROR_CHECK(err_code);
// Set response code according to signal if we are done, or want to continue.
{
// More blocks to come.
p_response->header.code = COAP_CODE_231_CONTINUE;
}
else
{
// Final block.
p_response->header.code = COAP_CODE_204_CHANGED;
}

Limitations

  • Encoding and decoding functions for Block2 options (response messages) are not supported by the current implementation.

References