CoAP - embed data into header option #3


I’d like to embed some numeric data (a counter) into CoAP header option-#3 (URI HOST) so at each iteration the application server can extract such information and display it accordingly.

Can anyone show how to set allocate “coap_res_ptr->options_list_ptr” so that it maps the URI HOST, the counter’s length and counter’s value ?

Below you can see my current code where “counter” is used both as msg_id as well as CoAP payload (“Message #%d”). I’d like to get rid of the CoAP payload and have the counter shown in CoAP header instead.

Any hint/suggestion is really appreciated!

Thank you,


// Initialize the CoAP protocol handle, pointing to local implementations on malloc/free/tx/rx functions
coapHandle = sn_coap_protocol_init(&coap_malloc, &coap_free, &coap_tx_cb, &coap_rx_cb);

// Path to the resource we want to retrieve
const char* coap_uri_path = "/hello";

int counter =1;
char buffer[50];

// See ns_coap_header.h
sn_coap_hdr_s *coap_res_ptr = (sn_coap_hdr_s*)calloc(sizeof(sn_coap_hdr_s), 1);
coap_res_ptr->uri_path_ptr = (uint8_t*)coap_uri_path;       // Path
coap_res_ptr->uri_path_len = strlen(coap_uri_path);
coap_res_ptr->msg_code = COAP_MSG_CODE_REQUEST_POST;         // CoAP method
coap_res_ptr->content_format = COAP_CT_TEXT_PLAIN;          // CoAP content type
// coap_res_ptr->payload_len = 0;                           // Body length is now set in the do loop below because our message changes each time.
coap_res_ptr->payload_ptr = (uint8_t*)buffer;               // set the pointer to our message buffer
coap_res_ptr->options_list_ptr = 0;                         // Optional: options list
coap_res_ptr->msg_type = COAP_MSG_TYPE_NON_CONFIRMABLE;

do {

    // Message ID is used to track request->response patterns, because we're using UDP (so everything is unconfirmed).
    // See the receive code to verify that we get the same message ID back
    coap_res_ptr->msg_id = counter;

    // create our message with counter value
    int n = sprintf(buffer, "Message #%d", counter++);
    // int n = sprintf(buffer, "{ '$type': 'number', '?value': %d }", counter++);

    // update the payload length
    coap_res_ptr->payload_len = n;

    // Calculate the CoAP message size, allocate the memory and build the message
    uint16_t message_len = sn_coap_builder_calc_needed_packet_data_size(coap_res_ptr);
    printf("Calculated message length: %d bytes\n", message_len);

    uint8_t* message_ptr = (uint8_t*)malloc(message_len);
    sn_coap_builder(message_ptr, coap_res_ptr);

    // Use the SendTo UDP command to send the CoAP message

    // int scount = socket.sendto("", 5683, message_ptr, message_len);
    // printf("Sent %d bytes to coap:// (body=%s)\n", scount, buffer);
    int scount = socket.sendto("", 5683, message_ptr, message_len);
    printf("Sent %d bytes to coap:// (body=%s)\n", scount, buffer);

    // we've sent this message so free the memory

} while(true);