Exercise 1

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 lesson5/cellfund_less5_exer1.

2. Enable the CoAP library.

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

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

#include <zephyr/net/coap.h>

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.

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

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 "Hello from nRF9160 SiP"

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

5. Declare the buffer coap_buf to receive the response.

static uint8_t coap_buf[APP_COAP_MAX_MSG_LEN];

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;

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();

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 increment the random token next_token to make sure it’s different for every message.

struct coap_packet request;

next_token++;

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;
}

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;
}

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);

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;
}

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));

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;
}

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;
}

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;
}

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, sizeof(temp_buf)), "%s", payload);
} else {
	strcpy(temp_buf, "EMPTY");
}

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);

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 nRF9160 DK and the Thingy:91 have a different number of buttons, this code depends on which board you are using.

nRF9160 DK

The nRF9160 DK has two buttons so we will use them 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();
}
Thingy:91

Since the Thingy:91 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;
} 

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;
}

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;
}

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.

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 nRF9160 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 macron MESSAGE_TO_SEND in STEP 4.1

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 “Hello from nRF9160 SiP” is the value stored in the CONFIG_COAP_TX_RESOURCE resource.

The solution for this exercise can be found in the GitHub repository in lesson5/cellfund_less5_exer1_solution.

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

Forgot your password?
Enter your email address, and we will send a link to reset your password.