Exercise 2

Adding notification and indication support

In this exercise, we will add support for the GATT operations Notify and Indicate. Recall that these operations are server-initiated, by the GATT client must subscribe to the desired data to receive the messages.

The exercise is divided into two parts.

First, we will add support for the Indicate operation to the Button characteristic and then subscribe to the Button characteristic from nRF Connect for Mobile to be notified whenever the button is pushed.

In the second part, we will add another custom characteristic to our service that will only support notifications. We will call this characteristic MYSENSOR, and use it to periodically send simulated sensor data to your phone. This is a very relevant use-case, for example, if your board has a sensor that collects some data that you want to periodically transmit to a central device.

Exercise steps

In the GitHub repository for this course, go to the base code for this exercise, found in lesson4/blefund_less4_exer2.

1. Modify the Button characteristic declaration to support indication.

Modify the declaration of the Button characteristic to pass the BT_GATT_CHRC_INDICATE attribute property, as well as the read property. Notice how we use the bitwise or operator | to support both read and indication.

Change the following code in my_lbs.c

	BT_GATT_CHARACTERISTIC(BT_UUID_LBS_BUTTON,
			       BT_GATT_CHRC_READ | BT_GATT_CHRC_INDICATE,
			       BT_GATT_PERM_READ, read_button, NULL,
			       &button_state),

2. Create and add the Client Characteristic Configuration Descriptor.

Since we are now using indication, we need to have a Client Characteristic Configuration Descriptor to enable devices acting as GATT clients (for example, nRF Connect for Mobile) to subscribe to this characteristic.

We will use the macro BT_GATT_CCC() to create and add the Client Characteristic Configuration Descriptor, which has the following signature

The first parameter is the configuration change callback function that we will call mylbsbc_ccc_cfg_changed and implement in the next step, and the second parameter is the access permission for the descriptor which we will grant both read and write permissions.

Add the following code:

	BT_GATT_CCC(mylbsbc_ccc_cfg_changed,
		    BT_GATT_PERM_READ | BT_GATT_PERM_WRITE),

This code is added right below the Buttons Characteristic definition. The location of where to place this definition is important, as discussed in the Attribute table topic.

3. Implement the configuration change callback function.

This function is called when a GATT client enables or disables indication. The callback function must have the signature as shown in the code below.

We want this callback function to update the boolean indicate_enabled to true if the client (your phone) enables indications or false if the client disables indications.

Add the following code in my_lbs.c .

static void mylbsbc_ccc_cfg_changed(const struct bt_gatt_attr *attr,
				  uint16_t value)
{
	indicate_enabled = (value == BT_GATT_CCC_INDICATE);
}

4. Define an indication parameter

In order to use the Indicate operation, we need to define a variable of type bt_gatt_indicate_params to hold the variable that you want to send out and the characteristic that you want to associate the indication with.

Add the following line in my_lbs.c .

static struct bt_gatt_indicate_params ind_params;

We will populate the fields of this struct variable in the next step.

5. Define the function to send indications.

This is the function that your application code can call to send data to subscribed clients whenever it needs to.

In this function, we will use the GATT API function bt_gatt_indicate() to do the work of sending indications.

Before calling bt_gatt_indicate(), we need to check if indication is enabled (indicate_enabled is true or false). If indicate_enabled is false, we will simply return and not send indications.

5.1 Add the following function definition in my_lbs.c

int my_lbs_send_button_state_indicate(bool button_state)
{
	if (!indicate_enabled) {
		return -EACCES;
	}

	/* STEP 5.2 - Populate the indication */

}

5.2 If indications are enabled, populate ind_params.

The structure ind_params is of type bt_gatt_indicate_params which has several members, some of which are mandatory to fill and some that are optional.

We will take a closer look at the first two members (uuid and attr) first, see below

First two members of bt_gatt_indicate_params

We need to provide either the UUID or a pointer to the attribute of the characteristic that we want to have Indicate support. In this case, we will be using the latter.

Remember as we discussed before, that a characteristic will have at least two attributes, the characteristic declaration attribute and the characteristic value attribute. So we need to provide a pointer to either the Button characteristic declaration or the Button characteristic value.

Here is a screenshot of the attributes table of our “My LBS” service with indication (captured in a debugging session). Also notice the index for each attribute my_lbs_svc.arrts[0] , ....[1], etc..

The attribute table for custom service

Note

To see your own attributes table, you need to watch the variables my_lbs_svc.attrs[i] for every attribute in the table while debugging the application.
In the Watch window in the Debug panel, select the plus icon to Add Expression and type in the fields you want to watch, my_lbs_svc, my_lbs_svc[0], my_lbs_svc[1], etc…

So we can pass either the Button characteristic declaration in index 1 (&my_lbs_svc.attrs[1]) or the Button characteristic value in index 2 (&my_lbs_svc.attrs[2]).

Let’s take a look at the rest of the members of bt_gatt_indicate_params .

bt_gatt_indicate_params struct type

The optional member func allows you to register a function when the remote device acknowledges an indication. We will set it to indicate_cb which prints it to the debug log.

The optional member destroy allows you to register a function when indication ends, which we will set to NULL.

For the last two parameters, the Indicate Value data and its length, we need to specify the data we want to send out and its size. Here, we will simply pass the button_state and its size.

Add the following lines to the function definition:

	ind_params.attr = &my_lbs_svc.attrs[2];
	ind_params.func = indicate_cb;
	ind_params.destroy = NULL;
	ind_params.data = &button_state;
	ind_params.len = sizeof(button_state);
	return bt_gatt_indicate(NULL, &ind_params);

6. Send indication on a button press.

Now we want the GATT server to send the indication upon a button press. We will trigger indication in the button_changed() function so that every time button 1 is pressed, we will send its status as indication.

Add the following line in main.c inside button_changed().

my_lbs_send_button_state_indicate(user_button_state);

Note that we are still supporting the Read operation that we did in the previous exercise, so the Button characteristic now supports both read and indication.

7. Build and flash the application on your board.

LED1 on your board should be blinking, indicating that your board is advertising.

8. Connect to your board using your smartphone.

Android

Open nRF Connect for Mobile on your smartphone, and connect to your device, now named “MY_LBS2“, in the Scanner tab.

Notice how the Button characteristic now includes support for the GATT indicate operation. Also, notice the symbol consisting of two arrows. This allows your smartphone, acting as a GATT client, to subscribe to Button characteristic indication.

nRF Connect for Android
iOS

Open nRF Connect for Mobile on your smartphone, and connect to your device, now named “MY_LBS2“, in the Scanner tab.

Notice how the Button characteristic now includes support for the GATT indicate operation. Also, notice the symbol consisting of two arrows. This allows your smartphone, acting as a GATT client, to subscribe to Button characteristic indication.

nRF Connect for iOS

9. Subscribe to the Button characteristic indication.

Press on the two arrows symbol to subscribe to the Button characteristic indication.

10. Press Button 1 on your board, and notice how indication is sent by the board as soon as the button is pressed or released.

With this, we have covered how to create a custom Bluetooth LE service from scratch. It’s worth noting that the nRF Connect SDK comes with the LBS service, among many others (from nRF Connect SDK and Zephyr RTOS ) that you can use out-of-the-box, and you don’t have to implement it from scratch as we did in this exercise and the past exercise. We only did this for learning purposes.

You can easily use the built-in LBS service in nRF Connect SDK by enabling the Kconfig symbol CONFIG_BT_LBS in prj.conf and registering your application callback functions to read the button status and update the LEDs.

In this part of the exercise, we will add another custom characteristic that supports only notifications. We will call this characteristic MYSENSOR, and use it to periodically stream data over Bluetooth LE.

11. Add the UUID for the MYSENSOR characteristic

11.1 Assign a UUID to the new characteristic. We will use the base UUID for the LBS service 0x00001526, 0x1212, 0xefde, 0x1523, 0x785feabcd123 where the first portion is simply incremented from the last characteristic.

Note

You can also generate your own UUID using this website or by using Python or similar scripting languages.

Add the following code in my_lbs.h

/** @brief LED Characteristic UUID. */
#define BT_UUID_LBS_MYSENSOR_VAL 
	BT_UUID_128_ENCODE(0x00001526, 0x1212, 0xefde, 0x1523, 0x785feabcd123)

11.2 Convert the array to a generic UUID by using the macro BT_UUID_DECLARE_128().

Add the following line in my_lbs.h

#define BT_UUID_LBS_MYSENSOR       BT_UUID_DECLARE_128(BT_UUID_LBS_MYSENSOR_VAL)

12. Create and add the MYSENSOR characteristic and its Client Characteristic Configuration Descriptor.

We are only supporting the GATT Notify operation.

Add the following code in my_lbs.c in the service declaration.

	BT_GATT_CHARACTERISTIC(BT_UUID_LBS_MYSENSOR,
			       BT_GATT_CHRC_NOTIFY,
			       BT_GATT_PERM_NONE, NULL, NULL,
			       NULL),

	BT_GATT_CCC(mylbsbc_ccc_mysensor_cfg_changed,
		    BT_GATT_PERM_READ | BT_GATT_PERM_WRITE),

13. Define the configuration change callback function to detect enabling/disabling notifications for the MYSENSOR characteristic.

In this function, we will update the boolean notify_mysensor_enabled to true if the client (the remote device) enables notification or false if the client disables notification on the MYSENSOR characteristic.

Add the following code in my_lbs.c

static void mylbsbc_ccc_mysensor_cfg_changed(const struct bt_gatt_attr *attr,
				  uint16_t value)
{
	notify_mysensor_enabled = (value == BT_GATT_CCC_NOTIFY);
}

14. Define the function my_lbs_send_sensor_notify() to send notifications for the MYSENSOR characteristic.

This is the function that your application code can call to send data to subscribed clients whenever it needs to.

In this function, we will use the GATT API function bt_gatt_notify() to do the work of sending notifications.

bt_gatt_notify() is easier to use than bt_gatt_indicate(), which we used in part 1 of this exercise. We just need to specify the pointer to the attribute of the characteristic that we want to support notification in.

As we discussed earlier, we need to provide a pointer to either the MYSENSOR characteristic declaration (index 6), or the MYSENSOR characteristic value (index 7).

And we need to specify the data we want to send out and its size. This time we are sending 4 bytes (or 32 bits, the size of the uint32_t type) to represent the sensor reading. You can send any data type of your preference over Bluetooth LE.

Before calling bt_gatt_notify(), we need to check if notification is enabled on the MYSENSOR characteristics, meaning a client has subscribed to it. This is done by simply checking the value of the boolean variable notify_mysensor_enabled. If it is not enabled, we will return and do nothing.

Add the following code in my_lbs.c

int my_lbs_send_sensor_notify(uint32_t sensor_value)
{
	if (!notify_mysensor_enabled) {
		return -EACCES;
	}

	return bt_gatt_notify(NULL, &my_lbs_svc.attrs[7], 
			      &sensor_value,
			      sizeof(sensor_value));
}

15. Define the data you want to stream over Bluetooth LE

We will declare a uint32_t (4 bytes) to hold the simulated sensor readings and assign it an initial value of 100.

Add the following line in main.c

static uint32_t app_sensor_value = 100;

16. Define a function simulate_data() to simulate the data.

Just for the sake of demonstration and to visually see the change of data on the remote device, we will include a function that increments the app_sensor_value sent over Bluetooth LE by 1 each time. app_sensor_value will start from 100 and get incremented by one on every notification push; it will roll back to 100 once the value reaches 200.

In a real application, we would normally call a sensor API to get actual data.

Add the following code to main.c

static void simulate_data(void)
{
	app_sensor_value++;
	if (app_sensor_value == 200) {
		app_sensor_value = 100;
	}
}

17. Define the interval at which you want to send data at (streaming interval).

We will set this to 500 ms. Typically, you must set this value to meet your application’s needs.

Add the following code in main.c

#define NOTIFY_INTERVAL         500

18. Create a thread to periodically send data

The nRF Connect SDK, which is based on Zephyr RTOS, has many options to schedule tasks periodically. One option is to create a separate thread, as covered in the nRF Connect SDK Fundamentals course – Lesson 7.

We will create a thread dedicated to sending notifications periodically.

18.1 Define the thread function

In this function, we will call simulate_data() to increment the simulated data sensor by one, send it to the remote device as Bluetooth LE notification, and sleep for NOTIFY_INTERVAL .

Add the following code in main.c

void send_data_thread(void)
{
	while(1){
		/* Simulate data */
		simulate_data();
		/* Send notification, the function sends notifications only if a client is subscribed */
		my_lbs_send_sensor_notify(app_sensor_value);

		k_sleep(K_MSEC(NOTIFY_INTERVAL));
	}
		
}

18.2. Define and initialize the thread to periodically send the data.

Add the following line in main.c

K_THREAD_DEFINE(send_data_thread_id, STACKSIZE, send_data_thread, NULL, NULL,
		NULL, PRIORITY, 0, 0);

19. Build and flash the application on your board, and connect to it using your smartphone.

20. Subscribe to the MYSENSOR characteristic

The MYSENSOR characteristic is shown as Unknown Characteristic as the nRF Connect for Mobile has no registered name for the new UUID chosen for the MYSENSOR characteristic.

Note

(In Android) You can add a name to it in nRF Connect for Mobile by pressing the MYSENSOR characteristic and clicking on the pen symbol at the top to assign it a name.

Subscribe to the characteristic and notice how data is received periodically from your board approximately twice a second (NOTIFY_INTERVAL was set to 500ms).

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.