Feedback
Feedback

If you are having issues with the exercises, please create a ticket on DevZone: devzone.nordicsemi.com
Click or drag files to this area to upload. You can upload up to 2 files.

Exercise 1

v2.8.x – v2.7.0

Connecting to a CoAP server

In this exercise, we will establish bidirectional communication between your board and another CoAP client through a CoAP server which enables you to control/monitor the board remotely from any CoAP client, running on a PC, tablet, or smartphone.

We will connect to a public sandbox CoAP server californium.eclipseprojects.io which is based on Eclipse Californium. When pressing button 1, the board will send a GET request to the resource CONFIG_COAP_RX_RESOURCE . Upon pressing button 2, the board will send a PUT request to the resource CONFIG_COAP_TX_RESOURCE.

Then you will configure your PC, tablet, or smartphone as a CoAP client that can send GET requests to CONFIG_COAP_TX_RESOURCE to read messages from the board and send PUT requests to CONFIG_COAP_RX_RESOURCE to send messages to the board.

Important

The sandbox CoAP server californium.eclipseprojects.io is used for testing and learning purposes only. For production, it’s highly recommended to set up a CoAP server and configure its resources to meet your end application needs.

Exercise Steps

1. In the GitHub repository for this course, go to the base code for this exercise, found in l5/l5_e1, of whichever version directory you are using.

2. Enable the CoAP library.

2.1 Enable the following Kconfig symbols in the prj.conf file.

CONFIG_COAP=y
Kconfig

2.2 Include the header file of the CoAP library in main.c.

#include <zephyr/net/coap.h>
C

3. Configure the CoAP configurations in prj.conf

The file Kconfig defines four CoAP-related configurations:

  • COAP_SERVER_HOSTNAME – The CoAP server hostname, defaults to californium.eclipseprojects.io
  • COAP_SERVER_PORT – The CoAP server port, defaults to 5683
  • COAP_TX_RESOURCE – The CoAP resource name for the TX channel (of the board), no default value
  • COAP_RX_RESOURCE – The CoAP resource name for the RX channel (of the board), no default value

3.1 Configure the CoAP server hostname to point to the Eclipse Californium server.

CONFIG_COAP_SERVER_HOSTNAME="californium.eclipseprojects.io"
Kconfig

3.2 Set the resource names used for TX and RX communication.

CONFIG_COAP_TX_RESOURCE="large-update"
CONFIG_COAP_RX_RESOURCE="validate"
Kconfig

4. Define the macros for the message from the board, the CoAP version, and the CoAP message length.

4.1 Define the macro for the message from the board

#define MESSAGE_TO_SEND "Hi from nRF91 Series device"
C

4.2 Define the macros for the CoAP version and message length.

These will be used when initializing the CoAP packet, in coap_packet_init().

#define APP_COAP_VERSION 1
#define APP_COAP_MAX_MSG_LEN 1280
C

5. Declare the buffer coap_buf to receive the response.

static uint8_t coap_buf[APP_COAP_MAX_MSG_LEN];
C

6. Define and generate a random token to be used when creating CoAP messages

6.1 Declare the CoAP message token next_token.

static uint16_t next_token;
C

6.2 Generate a random token after the socket is connected.

In client_init(), after connect() has been called, use sys_rand32_get() to get a random 32-bit value assigned to next_token to be used in the CoAP messages.

next_token = sys_rand32_get();
C

7. Define the function client_get_send() to create, initialize and configure CoAP messages to be used in GET requests, and send them.

7.1 Create the CoAP message using the function coap_packet_init(), which has the following signature

  • type – In our case, we want a non-confirmable message, so we pass COAP_TYPE_NON_CON (see enum coap_msgtype).
  • code – In this case a GET request, so we pass COAP_METHOD_GET (see enum coap_method).
  • id – We use coap_next_id() to generate the message id.

Make sure to generating a new random next_token.

struct coap_packet request;

next_token = sys_rand32_get();

int err = coap_packet_init(&request, coap_buf, sizeof(coap_buf),
		       APP_COAP_VERSION, COAP_TYPE_NON_CON,
		       sizeof(next_token), (uint8_t *)&next_token,
		       COAP_METHOD_GET, coap_next_id());
if (err < 0) {
	LOG_ERR("Failed to create CoAP request, %d", err);
	return err;
}
C

7.2 We also want to add an option to the CoAP packet, specifying the resource we are requesting.

For this we use coap_packet_append_option() which has the following signature

  • code – In our case, we want to specify the URI to the resource we are requesting, so we pass COAP_OPTION_URI_PATH (see enum coap_option_num)
  • value – Recall that the resource we are requesting has been defined as CONFIG_COAP_RX_RESOURCE.
err = coap_packet_append_option(&request, COAP_OPTION_URI_PATH,
				(uint8_t *)CONFIG_COAP_RX_RESOURCE,
				strlen(CONFIG_COAP_RX_RESOURCE));
if (err < 0) {
	LOG_ERR("Failed to encode CoAP option, %d", err);
	return err;
}
C

7.3 Lastly, use send() to send the configured CoAP packet.

err = send(sock, request.data, request.offset, 0);
if (err < 0) {
	LOG_ERR("Failed to send CoAP request, %d", errno);
	return -errno;
}

LOG_INF("CoAP GET request sent: Token 0x%04x", next_token);
C

8. The function client_put_send() will create and initialize the CoAP messages to be used in the PUT requests.

8.1 The beginning is quite similar to client_get_send(). When creating the CoAP message, the header code is now COAP_METHOD_PUT. And when adding the resource path, make sure to use CONFIG_COAP_TX_RESOURCE.

err = coap_packet_init(&request, coap_buf, sizeof(coap_buf),
		       APP_COAP_VERSION, COAP_TYPE_NON_CON,
		       sizeof(next_token), (uint8_t *)&next_token,
		       COAP_METHOD_PUT, coap_next_id());
if (err < 0) {
	LOG_ERR("Failed to create CoAP request, %d", err);
	return err;
}

err = coap_packet_append_option(&request, COAP_OPTION_URI_PATH,
				(uint8_t *)CONFIG_COAP_TX_RESOURCE,
				strlen(CONFIG_COAP_TX_RESOURCE));
if (err < 0) {
	LOG_ERR("Failed to encode CoAP option, %d", err);
	return err;
}
C

8.2 In PUT messages, we also append the option COAP_OPTION_CONTENT_FORMAT to be of type COAP_CONTENT_FORMAT_TEXT_PLAIN.

const uint8_t text_plain = COAP_CONTENT_FORMAT_TEXT_PLAIN;
err = coap_packet_append_option(&request, COAP_OPTION_CONTENT_FORMAT,
				&text_plain,
				sizeof(text_plain));
C

8.3 Then we must add the payload to the message

First, we use coap_packet_append_payload_marker() to add a payload marker to the CoAP packet. Then coap_packet_append_payload() to add the payload (MESSAGE_TO_SEND that we defined earlier).

err = coap_packet_append_payload_marker(&request);
if (err < 0) {
	LOG_ERR("Failed to append payload marker, %d", err);
	return err;
}

err = coap_packet_append_payload(&request, (uint8_t *)MESSAGE_TO_SEND, sizeof(MESSAGE_TO_SEND));
if (err < 0) {
	LOG_ERR("Failed to append payload, %d", err);
	return err;
}
C

We will send the configured CoAP packet the same as we did in step 7.

9. Define the function client_handle_response(uint8_t *buf, int received) to handle the response from the CoAP server.

We want to parse the received packet to get a struct coap_packet, then use various helper functions available in the CoAP library to retrieve the token, payload and header code to log.

9.1 Parse the received CoAP packet buf using coap_packet_parse().

int err = coap_packet_parse(&reply, buf, received, NULL, 0);
if (err < 0) {
	LOG_ERR("Malformed response received: %d", err);
	return err;
}
C

9.2 Confirm that the token in the response matches the token sent in the request, next_token.

We use the function coap_header_get_token() to get the token of the CoAP packet. Then compare both the length and the contents of the retrieved token with next_token and return an error if they don’t match.

token_len = coap_header_get_token(&reply, token);
if ((token_len != sizeof(next_token)) ||
    (memcmp(&next_token, token, sizeof(next_token)) != 0)) {
	LOG_ERR("Invalid token received: 0x%02x%02x",
	       token[1], token[0]);
	return 0;
}
C

9.3 Retrieve the payload, confirm it’s nonzero, and copy the contents into a buffer temp_buf. The temp_buf is used to format the output string on the terminal

To get the payload from the CoAP packet, we use the function coap_packet_get_payload().

payload = coap_packet_get_payload(&reply, &payload_len);
if (payload_len > 0) {
	snprintf(temp_buf, MIN(payload_len+1, sizeof(temp_buf)), "%s", payload);
} else {
	strcpy(temp_buf, "EMPTY");
}
C

9.4 Print the header code, token, and payload of the response.

To print the header code we use the function coap_header_get_code().

LOG_INF("CoAP response: Code 0x%x, Token 0x%02x%02x, Payload: %s",
 coap_header_get_code(&reply), token[1], token[0], (char *)temp_buf);
C

10. The function button_handler(), which is triggered on button pushes, should call either client_get_send() or client_put_send() to send a GET request or a PUT request.

Since the nRF91 Series DK’s and the Thingy:91 have a different number of buttons, this code depends on which board you are using.

nRF91 Series DK

All the nRF91 Series DKs have at least two buttons, which we will use to indicate a GET request and a PUT request.

Add the following code in button_handler() so the application calls client_get_send() to send a GET request when button 1 is pressed, and calls client_put_send() to send a PUT request when button 2 is pressed.

if (has_changed & DK_BTN1_MSK && button_state & DK_BTN1_MSK) {
	client_get_send();
} else if (has_changed & DK_BTN2_MSK && button_state & DK_BTN2_MSK) {
	client_put_send();
}
C

THingy

Since the Thingy:91 and Thingy:91 X only has one button, the behavior will be a bit different.

The function of the button will change for each press, meaning the first press will send a GET request, then the next time you press the button it will send a PUT request, and so on.

static bool toogle = 1;
if (has_changed & DK_BTN1_MSK && button_state & DK_BTN1_MSK) {
	if (toogle == 1) {
		client_get_send();	
	} else {
		client_put_send();
	}
	toogle = !toogle;
} 
C

11. In the while-loop in main(), continuously call recv() to receive responses from the CoAP server.

Recall that recv() returns the number of bytes received, or -1 if an error has occurred. We break in the case of an error, and if the number of received bytes is zero we go to the next iteration. Note that recv() is a blocking function so if there is no data, the thread executing this function which is the main thread will go to sleep to let other threads run and then wake up if there is data to be read.

received = recv(sock, coap_buf, sizeof(coap_buf), 0);
if (received < 0) {
	LOG_ERR("Socket error: %d, exit", errno);
	break;
} if (received == 0) {
	LOG_INF("Empty datagram");
	continue;
}
C

12. Then call client_handle_response() to parse the received CoAP packet, found in coap_buf.

err = client_handle_response(coap_buf, received);
if (err < 0) {
	LOG_ERR("Invalid response, exit");
	break;
}
C

13. Build the exercise and flash it on your board.

Testing

14. Let’s first set up a CoAP Client to communicate with our board.

We will be testing on the PC using cf-browser. You will need Java Runtime Environment installed on your machine.

More on this

We have many options here. If you are using a PC, you could either download the desktop application cf-browser or you could use a chrome extension Copper for Chrome (Cu4Cr) CoAP. If you are using a tablet or smartphone, several Android and iOS apps are available that act as a CoAP client (for example CoAP Client).

14.1 Enter the CoAP server URL (set in CONFIG_COAP_SERVER_HOSTNAME step 3.1) and discover its resources as shown below.

14.2 Send a message from the CoAP client to the board.

Locate the CONFIG_COAP_RX_RESOURCE resource used by the board to receive data. In other words, this is the CoAP resource that you will use to send to the board. This was set in step 3.2 to validate . Type the message you want to send to the board and send it as a PUT request. You should see a response of ACK 2.04/CHANGED which means that the client has successfully modified the content of the resource.

On your board, press button 1, and the message should be displayed in the terminal.

*** Booting nRF Connect SDK 2.6.1-3758bcbfa5cd ***
[00:00:00.322,529] <inf> Lesson5_Exercise1: Initializing modem library
[00:00:00.622,528] <inf> Lesson5_Exercise1: Connecting to LTE network
[00:00:04.381,195] <inf> Lesson5_Exercise1: RRC mode: Connected
[00:00:05.521,118] <inf> Lesson5_Exercise1: Network registration status: Connected - roaming
[00:00:05.521,270] <inf> Lesson5_Exercise1: Connected to LTE network
[00:00:05.688,232] <inf> Lesson5_Exercise1: IPv4 Address found 20.47.97.44
[00:00:05.688,964] <inf> Lesson5_Exercise1: Successfully connected to server
[00:00:10.806,854] <inf> Lesson5_Exercise1: RRC mode: Idle
[00:00:19.563,446] <inf> Lesson5_Exercise1: CoAP GET request sent: Token 0x4a6c
[00:00:19.650,817] <inf> Lesson5_Exercise1: RRC mode: Connected
[00:00:19.802,947] <inf> Lesson5_Exercise1: CoAP response: Code 0x45, Token 0x4a6c, Payload: Hi from my PC!
[00:00:25.094,940] <inf> Lesson5_Exercise1: RRC mode: Idle
Terminal

The payload “Hi From my PC!” is the value stored in the CONFIG_COAP_RX_RESOURCE resource.

14.2 Send a message from your board to the CoAP client.

Press button 2 on your nRF91 Series DK, or button 1 twice on the Thingy:91. This will send a PUT request from your board to the CoAP server. The message sent is set in the macro MESSAGE_TO_SEND in STEP 4.1

[00:02:55.938,201] <inf> Lesson5_Exercise1: CoAP PUT request sent: Token 0x4a6d
[00:02:56.027,679] <inf> Lesson5_Exercise1: RRC mode: Connected
[00:02:56.207,336] <inf> Lesson5_Exercise1: CoAP response: Code 0x44, Token 0x4a6d, Payload: EMPTY
[00:03:01.572,784] <inf> Lesson5_Exercise1: RRC mode: Idle
Terminal

Notice that when sending a PUT request, the CoAP packet received back from the server has no payload.

On the CoAP client side, locate the CONFIG_COAP_TX_RESOURCE resource used by the board to send data. In other words, this is the CoAP resource that you will use to receive from the board. This was set in step 3.2 to large-update. Then issue a GET request. You should see the message in the response payload as shown below.

The payload “Hi from nRF91 Series device” is the value stored in the CONFIG_COAP_TX_RESOURCE resource.

The solution for this exercise can be found in the GitHub repository in l5/l5_e1_sol, of whichever version directory you are using.

v2.6.2 – v2.4.0

Connecting to a CoAP server

In this exercise, we will establish bidirectional communication between your board and another CoAP client through a CoAP server which enables you to control/monitor the board remotely from any CoAP client, running on a PC, tablet, or smartphone.

We will connect to a public sandbox CoAP server californium.eclipseprojects.io which is based on Eclipse Californium. When pressing button 1, the board will send a GET request to the resource CONFIG_COAP_RX_RESOURCE . Upon pressing button 2, the board will send a PUT request to the resource CONFIG_COAP_TX_RESOURCE.

Then you will configure your PC, tablet, or smartphone as a CoAP client that can send GET requests to CONFIG_COAP_TX_RESOURCE to read messages from the board and send PUT requests to CONFIG_COAP_RX_RESOURCE to send messages to the board.

Important

The sandbox CoAP server californium.eclipseprojects.io is used for testing and learning purposes only. For production, it’s highly recommended to set up a CoAP server and configure its resources to meet your end application needs.

Exercise Steps

1. In the GitHub repository for this course, go to the base code for this exercise, found in l5/l5_e1, of whichever version directory you are using.

2. Enable the CoAP library.

2.1 Enable the following Kconfig symbols in the prj.conf file.

CONFIG_COAP=y
Kconfig

2.2 Include the header file of the CoAP library in main.c.

#include <zephyr/net/coap.h>
C

3. Configure the CoAP configurations in prj.conf

The file Kconfig defines four CoAP-related configurations:

  • COAP_SERVER_HOSTNAME – The CoAP server hostname, defaults to californium.eclipseprojects.io
  • COAP_SERVER_PORT – The CoAP server port, defaults to 5683
  • COAP_TX_RESOURCE – The CoAP resource name for the TX channel (of the board), no default value
  • COAP_RX_RESOURCE – The CoAP resource name for the RX channel (of the board), no default value

3.1 Configure the CoAP server hostname to point to the Eclipse Californium server.

CONFIG_COAP_SERVER_HOSTNAME="californium.eclipseprojects.io"
Kconfig

3.2 Set the resource names used for TX and RX communication.

CONFIG_COAP_TX_RESOURCE="large-update"
CONFIG_COAP_RX_RESOURCE="validate"
Kconfig

4. Define the macros for the message from the board, the CoAP version, and the CoAP message length.

4.1 Define the macro for the message from the board

#define MESSAGE_TO_SEND "Hi from nRF91 Series device"
C

4.2 Define the macros for the CoAP version and message length.

These will be used when initializing the CoAP packet, in coap_packet_init().

#define APP_COAP_VERSION 1
#define APP_COAP_MAX_MSG_LEN 1280
C

5. Declare the buffer coap_buf to receive the response.

static uint8_t coap_buf[APP_COAP_MAX_MSG_LEN];
C

6. Define and generate a random token to be used when creating CoAP messages

6.1 Declare the CoAP message token next_token.

static uint16_t next_token;
C

6.2 Generate a random token after the socket is connected.

In client_init(), after connect() has been called, use sys_rand32_get() to get a random 32-bit value assigned to next_token to be used in the CoAP messages.

next_token = sys_rand32_get();
C

7. Define the function client_get_send() to create, initialize and configure CoAP messages to be used in GET requests, and send them.

7.1 Create the CoAP message using the function coap_packet_init(), which has the following signature

  • type – In our case, we want a non-confirmable message, so we pass COAP_TYPE_NON_CON (see enum coap_msgtype).
  • code – In this case a GET request, so we pass COAP_METHOD_GET (see enum coap_method).
  • id – We use coap_next_id() to generate the message id.

Make sure to generating a new random next_token.

struct coap_packet request;

next_token = sys_rand32_get();

int err = coap_packet_init(&request, coap_buf, sizeof(coap_buf),
		       APP_COAP_VERSION, COAP_TYPE_NON_CON,
		       sizeof(next_token), (uint8_t *)&next_token,
		       COAP_METHOD_GET, coap_next_id());
if (err < 0) {
	LOG_ERR("Failed to create CoAP request, %d", err);
	return err;
}
C

7.2 We also want to add an option to the CoAP packet, specifying the resource we are requesting.

For this we use coap_packet_append_option() which has the following signature

  • code – In our case, we want to specify the URI to the resource we are requesting, so we pass COAP_OPTION_URI_PATH (see enum coap_option_num)
  • value – Recall that the resource we are requesting has been defined as CONFIG_COAP_RX_RESOURCE.
err = coap_packet_append_option(&request, COAP_OPTION_URI_PATH,
				(uint8_t *)CONFIG_COAP_RX_RESOURCE,
				strlen(CONFIG_COAP_RX_RESOURCE));
if (err < 0) {
	LOG_ERR("Failed to encode CoAP option, %d", err);
	return err;
}
C

7.3 Lastly, use send() to send the configured CoAP packet.

err = send(sock, request.data, request.offset, 0);
if (err < 0) {
	LOG_ERR("Failed to send CoAP request, %d", errno);
	return -errno;
}

LOG_INF("CoAP GET request sent: Token 0x%04x", next_token);
C

8. The function client_put_send() will create and initialize the CoAP messages to be used in the PUT requests.

8.1 The beginning is quite similar to client_get_send(). When creating the CoAP message, the header code is now COAP_METHOD_PUT. And when adding the resource path, make sure to use CONFIG_COAP_TX_RESOURCE.

err = coap_packet_init(&request, coap_buf, sizeof(coap_buf),
		       APP_COAP_VERSION, COAP_TYPE_NON_CON,
		       sizeof(next_token), (uint8_t *)&next_token,
		       COAP_METHOD_PUT, coap_next_id());
if (err < 0) {
	LOG_ERR("Failed to create CoAP request, %d", err);
	return err;
}

err = coap_packet_append_option(&request, COAP_OPTION_URI_PATH,
				(uint8_t *)CONFIG_COAP_TX_RESOURCE,
				strlen(CONFIG_COAP_TX_RESOURCE));
if (err < 0) {
	LOG_ERR("Failed to encode CoAP option, %d", err);
	return err;
}
C

8.2 In PUT messages, we also append the option COAP_OPTION_CONTENT_FORMAT to be of type COAP_CONTENT_FORMAT_TEXT_PLAIN.

const uint8_t text_plain = COAP_CONTENT_FORMAT_TEXT_PLAIN;
err = coap_packet_append_option(&request, COAP_OPTION_CONTENT_FORMAT,
				&text_plain,
				sizeof(text_plain));
C

8.3 Then we must add the payload to the message

First, we use coap_packet_append_payload_marker() to add a payload marker to the CoAP packet. Then coap_packet_append_payload() to add the payload (MESSAGE_TO_SEND that we defined earlier).

err = coap_packet_append_payload_marker(&request);
if (err < 0) {
	LOG_ERR("Failed to append payload marker, %d", err);
	return err;
}

err = coap_packet_append_payload(&request, (uint8_t *)MESSAGE_TO_SEND, sizeof(MESSAGE_TO_SEND));
if (err < 0) {
	LOG_ERR("Failed to append payload, %d", err);
	return err;
}
C

We will send the configured CoAP packet the same as we did in step 7.

9. Define the function client_handle_response(uint8_t *buf, int received) to handle the response from the CoAP server.

We want to parse the received packet to get a struct coap_packet, then use various helper functions available in the CoAP library to retrieve the token, payload and header code to log.

9.1 Parse the received CoAP packet buf using coap_packet_parse().

int err = coap_packet_parse(&reply, buf, received, NULL, 0);
if (err < 0) {
	LOG_ERR("Malformed response received: %d", err);
	return err;
}
C

9.2 Confirm that the token in the response matches the token sent in the request, next_token.

We use the function coap_header_get_token() to get the token of the CoAP packet. Then compare both the length and the contents of the retrieved token with next_token and return an error if they don’t match.

token_len = coap_header_get_token(&reply, token);
if ((token_len != sizeof(next_token)) ||
    (memcmp(&next_token, token, sizeof(next_token)) != 0)) {
	LOG_ERR("Invalid token received: 0x%02x%02x",
	       token[1], token[0]);
	return 0;
}
C

9.3 Retrieve the payload, confirm it’s nonzero, and copy the contents into a buffer temp_buf. The temp_buf is used to format the output string on the terminal

To get the payload from the CoAP packet, we use the function coap_packet_get_payload().

payload = coap_packet_get_payload(&reply, &payload_len);
if (payload_len > 0) {
	snprintf(temp_buf, MIN(payload_len+1, sizeof(temp_buf)), "%s", payload);
} else {
	strcpy(temp_buf, "EMPTY");
}
C

9.4 Print the header code, token, and payload of the response.

To print the header code we use the function coap_header_get_code().

LOG_INF("CoAP response: Code 0x%x, Token 0x%02x%02x, Payload: %s",
 coap_header_get_code(&reply), token[1], token[0], (char *)temp_buf);
C

10. The function button_handler(), which is triggered on button pushes, should call either client_get_send() or client_put_send() to send a GET request or a PUT request.

Since the nRF91 Series DK’s and the Thingy:91 have a different number of buttons, this code depends on which board you are using.

nRF91 Series DK

All the nRF91 Series DKs have at least two buttons, which we will use to indicate a GET request and a PUT request.

Add the following code in button_handler() so the application calls client_get_send() to send a GET request when button 1 is pressed, and calls client_put_send() to send a PUT request when button 2 is pressed.

if (has_changed & DK_BTN1_MSK && button_state & DK_BTN1_MSK) {
	client_get_send();
} else if (has_changed & DK_BTN2_MSK && button_state & DK_BTN2_MSK) {
	client_put_send();
}
C

THingy

Since the Thingy:91 and Thingy:91 X only has one button, the behavior will be a bit different.

The function of the button will change for each press, meaning the first press will send a GET request, then the next time you press the button it will send a PUT request, and so on.

static bool toogle = 1;
if (has_changed & DK_BTN1_MSK && button_state & DK_BTN1_MSK) {
	if (toogle == 1) {
		client_get_send();	
	} else {
		client_put_send();
	}
	toogle = !toogle;
} 
C

11. In the while-loop in main(), continuously call recv() to receive responses from the CoAP server.

Recall that recv() returns the number of bytes received, or -1 if an error has occurred. We break in the case of an error, and if the number of received bytes is zero we go to the next iteration. Note that recv() is a blocking function so if there is no data, the thread executing this function which is the main thread will go to sleep to let other threads run and then wake up if there is data to be read.

received = recv(sock, coap_buf, sizeof(coap_buf), 0);
if (received < 0) {
	LOG_ERR("Socket error: %d, exit", errno);
	break;
} if (received == 0) {
	LOG_INF("Empty datagram");
	continue;
}
C

12. Then call client_handle_response() to parse the received CoAP packet, found in coap_buf.

err = client_handle_response(coap_buf, received);
if (err < 0) {
	LOG_ERR("Invalid response, exit");
	break;
}
C

13. Build the exercise and flash it on your board.

Testing

14. Let’s first set up a CoAP Client to communicate with our board.

We will be testing on the PC using cf-browser. You will need Java Runtime Environment installed on your machine.

More on this

We have many options here. If you are using a PC, you could either download the desktop application cf-browser or you could use a chrome extension Copper for Chrome (Cu4Cr) CoAP. If you are using a tablet or smartphone, several Android and iOS apps are available that act as a CoAP client (for example CoAP Client).

14.1 Enter the CoAP server URL (set in CONFIG_COAP_SERVER_HOSTNAME step 3.1) and discover its resources as shown below.

14.2 Send a message from the CoAP client to the board.

Locate the CONFIG_COAP_RX_RESOURCE resource used by the board to receive data. In other words, this is the CoAP resource that you will use to send to the board. This was set in step 3.2 to validate . Type the message you want to send to the board and send it as a PUT request. You should see a response of ACK 2.04/CHANGED which means that the client has successfully modified the content of the resource.

On your board, press button 1, and the message should be displayed in the terminal.

*** Booting nRF Connect SDK 2.6.1-3758bcbfa5cd ***
[00:00:00.322,529] <inf> Lesson5_Exercise1: Initializing modem library
[00:00:00.622,528] <inf> Lesson5_Exercise1: Connecting to LTE network
[00:00:04.381,195] <inf> Lesson5_Exercise1: RRC mode: Connected
[00:00:05.521,118] <inf> Lesson5_Exercise1: Network registration status: Connected - roaming
[00:00:05.521,270] <inf> Lesson5_Exercise1: Connected to LTE network
[00:00:05.688,232] <inf> Lesson5_Exercise1: IPv4 Address found 20.47.97.44
[00:00:05.688,964] <inf> Lesson5_Exercise1: Successfully connected to server
[00:00:10.806,854] <inf> Lesson5_Exercise1: RRC mode: Idle
[00:00:19.563,446] <inf> Lesson5_Exercise1: CoAP GET request sent: Token 0x4a6c
[00:00:19.650,817] <inf> Lesson5_Exercise1: RRC mode: Connected
[00:00:19.802,947] <inf> Lesson5_Exercise1: CoAP response: Code 0x45, Token 0x4a6c, Payload: Hi from my PC!
[00:00:25.094,940] <inf> Lesson5_Exercise1: RRC mode: Idle
Terminal

The payload “Hi From my PC!” is the value stored in the CONFIG_COAP_RX_RESOURCE resource.

14.2 Send a message from your board to the CoAP client.

Press button 2 on your nRF91 Series DK, or button 1 twice on the Thingy:91. This will send a PUT request from your board to the CoAP server. The message sent is set in the macro MESSAGE_TO_SEND in STEP 4.1

[00:02:55.938,201] <inf> Lesson5_Exercise1: CoAP PUT request sent: Token 0x4a6d
[00:02:56.027,679] <inf> Lesson5_Exercise1: RRC mode: Connected
[00:02:56.207,336] <inf> Lesson5_Exercise1: CoAP response: Code 0x44, Token 0x4a6d, Payload: EMPTY
[00:03:01.572,784] <inf> Lesson5_Exercise1: RRC mode: Idle
Terminal

Notice that when sending a PUT request, the CoAP packet received back from the server has no payload.

On the CoAP client side, locate the CONFIG_COAP_TX_RESOURCE resource used by the board to send data. In other words, this is the CoAP resource that you will use to receive from the board. This was set in step 3.2 to large-update. Then issue a GET request. You should see the message in the response payload as shown below.

The payload “Hi from nRF91 Series device” is the value stored in the CONFIG_COAP_TX_RESOURCE resource.

The solution for this exercise can be found in the GitHub repository in l5/l5_e1_sol, of whichever version directory you are using.

v2.3.0 – v2.2.0

Connecting to a CoAP server

In this exercise, we will establish bidirectional communication between your board and another CoAP client through a CoAP server which enables you to control/monitor the board remotely from any CoAP client, running on a PC, tablet, or smartphone.

We will connect to a public sandbox CoAP server californium.eclipseprojects.io which is based on Eclipse Californium. When pressing button 1, the board will send a GET request to the resource CONFIG_COAP_RX_RESOURCE . Upon pressing button 2, the board will send a PUT request to the resource CONFIG_COAP_TX_RESOURCE.

Then you will configure your PC, tablet, or smartphone as a CoAP client that can send GET requests to CONFIG_COAP_TX_RESOURCE to read messages from the board and send PUT requests to CONFIG_COAP_RX_RESOURCE to send messages to the board.

Important

The sandbox CoAP server californium.eclipseprojects.io is used for testing and learning purposes only. For production, it’s highly recommended to set up a CoAP server and configure its resources to meet your end application needs.

Exercise Steps

1. In the GitHub repository for this course, go to the base code for this exercise, found in l5/l5_e1, of whichever version directory you are using.

2. Enable the CoAP library.

2.1 Enable the following Kconfig symbols in the prj.conf file.

CONFIG_COAP=y
Kconfig

2.2 Include the header file of the CoAP library in main.c.

#include <zephyr/net/coap.h>
C

3. Configure the CoAP configurations in prj.conf

The file Kconfig defines four CoAP-related configurations:

  • COAP_SERVER_HOSTNAME – The CoAP server hostname, defaults to californium.eclipseprojects.io
  • COAP_SERVER_PORT – The CoAP server port, defaults to 5683
  • COAP_TX_RESOURCE – The CoAP resource name for the TX channel (of the board), no default value
  • COAP_RX_RESOURCE – The CoAP resource name for the RX channel (of the board), no default value

3.1 Configure the CoAP server hostname to point to the Eclipse Californium server.

CONFIG_COAP_SERVER_HOSTNAME="californium.eclipseprojects.io"
Kconfig

3.2 Set the resource names used for TX and RX communication.

CONFIG_COAP_TX_RESOURCE="large-update"
CONFIG_COAP_RX_RESOURCE="validate"
Kconfig

4. Define the macros for the message from the board, the CoAP version, and the CoAP message length.

4.1 Define the macro for the message from the board

#define MESSAGE_TO_SEND "Hi from nRF91 Series device"
C

4.2 Define the macros for the CoAP version and message length.

These will be used when initializing the CoAP packet, in coap_packet_init().

#define APP_COAP_VERSION 1
#define APP_COAP_MAX_MSG_LEN 1280
C

5. Declare the buffer coap_buf to receive the response.

static uint8_t coap_buf[APP_COAP_MAX_MSG_LEN];
C

6. Define and generate a random token to be used when creating CoAP messages

6.1 Declare the CoAP message token next_token.

static uint16_t next_token;
C

6.2 Generate a random token after the socket is connected.

In client_init(), after connect() has been called, use sys_rand32_get() to get a random 32-bit value assigned to next_token to be used in the CoAP messages.

next_token = sys_rand32_get();
C

7. Define the function client_get_send() to create, initialize and configure CoAP messages to be used in GET requests, and send them.

7.1 Create the CoAP message using the function coap_packet_init(), which has the following signature

  • type – In our case, we want a non-confirmable message, so we pass COAP_TYPE_NON_CON (see enum coap_msgtype).
  • code – In this case a GET request, so we pass COAP_METHOD_GET (see enum coap_method).
  • id – We use coap_next_id() to generate the message id.

Make sure to generating a new random next_token.

struct coap_packet request;

next_token = sys_rand32_get();

int err = coap_packet_init(&request, coap_buf, sizeof(coap_buf),
		       APP_COAP_VERSION, COAP_TYPE_NON_CON,
		       sizeof(next_token), (uint8_t *)&next_token,
		       COAP_METHOD_GET, coap_next_id());
if (err < 0) {
	LOG_ERR("Failed to create CoAP request, %d", err);
	return err;
}
C

7.2 We also want to add an option to the CoAP packet, specifying the resource we are requesting.

For this we use coap_packet_append_option() which has the following signature

  • code – In our case, we want to specify the URI to the resource we are requesting, so we pass COAP_OPTION_URI_PATH (see enum coap_option_num)
  • value – Recall that the resource we are requesting has been defined as CONFIG_COAP_RX_RESOURCE.
err = coap_packet_append_option(&request, COAP_OPTION_URI_PATH,
				(uint8_t *)CONFIG_COAP_RX_RESOURCE,
				strlen(CONFIG_COAP_RX_RESOURCE));
if (err < 0) {
	LOG_ERR("Failed to encode CoAP option, %d", err);
	return err;
}
C

7.3 Lastly, use send() to send the configured CoAP packet.

err = send(sock, request.data, request.offset, 0);
if (err < 0) {
	LOG_ERR("Failed to send CoAP request, %d", errno);
	return -errno;
}

LOG_INF("CoAP GET request sent: Token 0x%04x", next_token);
C

8. The function client_put_send() will create and initialize the CoAP messages to be used in the PUT requests.

8.1 The beginning is quite similar to client_get_send(). When creating the CoAP message, the header code is now COAP_METHOD_PUT. And when adding the resource path, make sure to use CONFIG_COAP_TX_RESOURCE.

err = coap_packet_init(&request, coap_buf, sizeof(coap_buf),
		       APP_COAP_VERSION, COAP_TYPE_NON_CON,
		       sizeof(next_token), (uint8_t *)&next_token,
		       COAP_METHOD_PUT, coap_next_id());
if (err < 0) {
	LOG_ERR("Failed to create CoAP request, %d", err);
	return err;
}

err = coap_packet_append_option(&request, COAP_OPTION_URI_PATH,
				(uint8_t *)CONFIG_COAP_TX_RESOURCE,
				strlen(CONFIG_COAP_TX_RESOURCE));
if (err < 0) {
	LOG_ERR("Failed to encode CoAP option, %d", err);
	return err;
}
C

8.2 In PUT messages, we also append the option COAP_OPTION_CONTENT_FORMAT to be of type COAP_CONTENT_FORMAT_TEXT_PLAIN.

const uint8_t text_plain = COAP_CONTENT_FORMAT_TEXT_PLAIN;
err = coap_packet_append_option(&request, COAP_OPTION_CONTENT_FORMAT,
				&text_plain,
				sizeof(text_plain));
C

8.3 Then we must add the payload to the message

First, we use coap_packet_append_payload_marker() to add a payload marker to the CoAP packet. Then coap_packet_append_payload() to add the payload (MESSAGE_TO_SEND that we defined earlier).

err = coap_packet_append_payload_marker(&request);
if (err < 0) {
	LOG_ERR("Failed to append payload marker, %d", err);
	return err;
}

err = coap_packet_append_payload(&request, (uint8_t *)MESSAGE_TO_SEND, sizeof(MESSAGE_TO_SEND));
if (err < 0) {
	LOG_ERR("Failed to append payload, %d", err);
	return err;
}
C

We will send the configured CoAP packet the same as we did in step 7.

9. Define the function client_handle_response(uint8_t *buf, int received) to handle the response from the CoAP server.

We want to parse the received packet to get a struct coap_packet, then use various helper functions available in the CoAP library to retrieve the token, payload and header code to log.

9.1 Parse the received CoAP packet buf using coap_packet_parse().

int err = coap_packet_parse(&reply, buf, received, NULL, 0);
if (err < 0) {
	LOG_ERR("Malformed response received: %d", err);
	return err;
}
C

9.2 Confirm that the token in the response matches the token sent in the request, next_token.

We use the function coap_header_get_token() to get the token of the CoAP packet. Then compare both the length and the contents of the retrieved token with next_token and return an error if they don’t match.

token_len = coap_header_get_token(&reply, token);
if ((token_len != sizeof(next_token)) ||
    (memcmp(&next_token, token, sizeof(next_token)) != 0)) {
	LOG_ERR("Invalid token received: 0x%02x%02x",
	       token[1], token[0]);
	return 0;
}
C

9.3 Retrieve the payload, confirm it’s nonzero, and copy the contents into a buffer temp_buf. The temp_buf is used to format the output string on the terminal

To get the payload from the CoAP packet, we use the function coap_packet_get_payload().

payload = coap_packet_get_payload(&reply, &payload_len);
if (payload_len > 0) {
	snprintf(temp_buf, MIN(payload_len+1, sizeof(temp_buf)), "%s", payload);
} else {
	strcpy(temp_buf, "EMPTY");
}
C

9.4 Print the header code, token, and payload of the response.

To print the header code we use the function coap_header_get_code().

LOG_INF("CoAP response: Code 0x%x, Token 0x%02x%02x, Payload: %s",
 coap_header_get_code(&reply), token[1], token[0], (char *)temp_buf);
C

10. The function button_handler(), which is triggered on button pushes, should call either client_get_send() or client_put_send() to send a GET request or a PUT request.

Since the nRF91 Series DK’s and the Thingy:91 have a different number of buttons, this code depends on which board you are using.

nRF91 Series DK

All the nRF91 Series DKs have at least two buttons, which we will use to indicate a GET request and a PUT request.

Add the following code in button_handler() so the application calls client_get_send() to send a GET request when button 1 is pressed, and calls client_put_send() to send a PUT request when button 2 is pressed.

if (has_changed & DK_BTN1_MSK && button_state & DK_BTN1_MSK) {
	client_get_send();
} else if (has_changed & DK_BTN2_MSK && button_state & DK_BTN2_MSK) {
	client_put_send();
}
C

THingy

Since the Thingy:91 and Thingy:91 X only has one button, the behavior will be a bit different.

The function of the button will change for each press, meaning the first press will send a GET request, then the next time you press the button it will send a PUT request, and so on.

static bool toogle = 1;
if (has_changed & DK_BTN1_MSK && button_state & DK_BTN1_MSK) {
	if (toogle == 1) {
		client_get_send();	
	} else {
		client_put_send();
	}
	toogle = !toogle;
} 
C

11. In the while-loop in main(), continuously call recv() to receive responses from the CoAP server.

Recall that recv() returns the number of bytes received, or -1 if an error has occurred. We break in the case of an error, and if the number of received bytes is zero we go to the next iteration. Note that recv() is a blocking function so if there is no data, the thread executing this function which is the main thread will go to sleep to let other threads run and then wake up if there is data to be read.

received = recv(sock, coap_buf, sizeof(coap_buf), 0);
if (received < 0) {
	LOG_ERR("Socket error: %d, exit", errno);
	break;
} if (received == 0) {
	LOG_INF("Empty datagram");
	continue;
}
C

12. Then call client_handle_response() to parse the received CoAP packet, found in coap_buf.

err = client_handle_response(coap_buf, received);
if (err < 0) {
	LOG_ERR("Invalid response, exit");
	break;
}
C

13. Build the exercise and flash it on your board.

Testing

14. Let’s first set up a CoAP Client to communicate with our board.

We will be testing on the PC using cf-browser. You will need Java Runtime Environment installed on your machine.

More on this

We have many options here. If you are using a PC, you could either download the desktop application cf-browser or you could use a chrome extension Copper for Chrome (Cu4Cr) CoAP. If you are using a tablet or smartphone, several Android and iOS apps are available that act as a CoAP client (for example CoAP Client).

14.1 Enter the CoAP server URL (set in CONFIG_COAP_SERVER_HOSTNAME step 3.1) and discover its resources as shown below.

14.2 Send a message from the CoAP client to the board.

Locate the CONFIG_COAP_RX_RESOURCE resource used by the board to receive data. In other words, this is the CoAP resource that you will use to send to the board. This was set in step 3.2 to validate . Type the message you want to send to the board and send it as a PUT request. You should see a response of ACK 2.04/CHANGED which means that the client has successfully modified the content of the resource.

On your board, press button 1, and the message should be displayed in the terminal.

*** Booting nRF Connect SDK 2.6.1-3758bcbfa5cd ***
[00:00:00.322,529] <inf> Lesson5_Exercise1: Initializing modem library
[00:00:00.622,528] <inf> Lesson5_Exercise1: Connecting to LTE network
[00:00:04.381,195] <inf> Lesson5_Exercise1: RRC mode: Connected
[00:00:05.521,118] <inf> Lesson5_Exercise1: Network registration status: Connected - roaming
[00:00:05.521,270] <inf> Lesson5_Exercise1: Connected to LTE network
[00:00:05.688,232] <inf> Lesson5_Exercise1: IPv4 Address found 20.47.97.44
[00:00:05.688,964] <inf> Lesson5_Exercise1: Successfully connected to server
[00:00:10.806,854] <inf> Lesson5_Exercise1: RRC mode: Idle
[00:00:19.563,446] <inf> Lesson5_Exercise1: CoAP GET request sent: Token 0x4a6c
[00:00:19.650,817] <inf> Lesson5_Exercise1: RRC mode: Connected
[00:00:19.802,947] <inf> Lesson5_Exercise1: CoAP response: Code 0x45, Token 0x4a6c, Payload: Hi from my PC!
[00:00:25.094,940] <inf> Lesson5_Exercise1: RRC mode: Idle
Terminal

The payload “Hi From my PC!” is the value stored in the CONFIG_COAP_RX_RESOURCE resource.

14.2 Send a message from your board to the CoAP client.

Press button 2 on your nRF91 Series DK, or button 1 twice on the Thingy:91. This will send a PUT request from your board to the CoAP server. The message sent is set in the macro MESSAGE_TO_SEND in STEP 4.1

[00:02:55.938,201] <inf> Lesson5_Exercise1: CoAP PUT request sent: Token 0x4a6d
[00:02:56.027,679] <inf> Lesson5_Exercise1: RRC mode: Connected
[00:02:56.207,336] <inf> Lesson5_Exercise1: CoAP response: Code 0x44, Token 0x4a6d, Payload: EMPTY
[00:03:01.572,784] <inf> Lesson5_Exercise1: RRC mode: Idle
Terminal

Notice that when sending a PUT request, the CoAP packet received back from the server has no payload.

On the CoAP client side, locate the CONFIG_COAP_TX_RESOURCE resource used by the board to send data. In other words, this is the CoAP resource that you will use to receive from the board. This was set in step 3.2 to large-update. Then issue a GET request. You should see the message in the response payload as shown below.

The payload “Hi from nRF91 Series device” is the value stored in the CONFIG_COAP_TX_RESOURCE resource.

The solution for this exercise can be found in the GitHub repository in l5/l5_e1_sol, of whichever version directory you are using.

Register an account
Already have an account? Log in
(All fields are required unless specified optional)

  • 8 or more characters
  • Upper and lower case letters
  • At least one number or special character

Forgot your password?
Enter the email associated with your account, and we will send you a link to reset your password.