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.
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.
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.
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.
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
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 attributemy_lbs_svc.arrts[0] , ....[1], etc..
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 .
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:
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().
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.
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.
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.
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.
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.
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.
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.
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).
Nordic Developer Academy Privacy Policy
1. Introduction
In this Privacy Policy you will find information on Nordic Semiconductor ASA (“Nordic Semiconductor”) processes your personal data when you use the Nordic Developer Academy.
References to “we” and “us” in this document refers to Nordic Semiconductor.
2. Our processing of personal data when you use the Nordic Developer Academy
2.1 Nordic Developer Academy
Nordic Semiconductor processes personal data in order to provide you with the features and functionality of the Nordic Developer Academy. Creating a user account is optional, but required if you want to track you progress and view your completed courses and obtained certificates. If you choose to create a user account, we will process the following categories of personal data:
Email
Name
Password (encrypted)
Course progression (e.g. which course you have completely or partly completed)
Certificate information, which consists of name of completed course and the validity of the certificate
Course results
During your use of the Nordic Developer Academy, you may also be asked if you want to provide feedback. If you choose to respond to any such surveys, we will also process the personal data in your responses in that survey.
The legal basis for this processing is GDPR article 6 (1) b. The processing is necessary for Nordic Semiconductor to provide the Nordic Developer Academy under the Terms of Service.
2.2 Analytics
If you consent to analytics, Nordic Semiconductor will use Google Analytics to obtain statistics about how the Nordic Developer Academy is used. This includes collecting information on for example what pages are viewed, the duration of the visit, the way in which the pages are maneuvered, what links are clicked, technical information about your equipment. The information is used to learn how Nordic Developer Academy is used and how the user experience can be further developed.
2.2 Newsletter
You can consent to receive newsletters from Nordic from within the Nordic Developer Academy. How your personal data is processed when you sign up for our newsletters is described in the Nordic Semiconductor Privacy Policy.
3. Retention period
We will store your personal data for as long you use the Nordic Developer Academy. If our systems register that you have not used your account for 36 months, your account will be deleted.
4. Additional information
Additional information on how we process personal data can be found in the Nordic Semiconductor Privacy Policy and Cookie Policy.
Nordic Developer Academy Terms of Service
1. Introduction
These terms and conditions (“Terms of Use”) apply to the use of the Nordic Developer Academy, provided by Nordic Semiconductor ASA, org. nr. 966 011 726, a public limited liability company registered in Norway (“Nordic Semiconductor”).
Nordic Developer Academy allows the user to take technical courses related to Nordic Semiconductor products, software and services, and obtain a certificate certifying completion of these courses. By completing the registration process for the Nordic Developer Academy, you are agreeing to be bound by these Terms of Use.
These Terms of Use are applicable as long as you have a user account giving you access to Nordic Developer Academy.
2. Access to and use of Nordic Developer Academy
Upon acceptance of these Terms of Use you are granted a non-exclusive right of access to, and use of Nordic Developer Academy, as it is provided to you at any time. Nordic Semiconductor provides Nordic Developer Academy to you free of charge, subject to the provisions of these Terms of Use and the Nordic Developer Academy Privacy Policy.
To access select features of Nordic Developer Academy, you need to create a user account. You are solely responsible for the security associated with your user account, including always keeping your login details safe.
You will able to receive an electronic certificate from Nordic Developer Academy upon completion of courses. By issuing you such a certificate, Nordic Semiconductor certifies that you have completed the applicable course, but does not provide any further warrants or endorsements for any particular skills or professional qualifications.
Nordic Semiconductor will continuously develop Nordic Developer Academy with new features and functionality, but reserves the right to remove or alter any existing functions without notice.
3. Acceptable use
You undertake that you will use Nordic Developer Academy in accordance with applicable law and regulations, and in accordance with these Terms of Use. You must not modify, adapt, or hack Nordic Developer Academy or modify another website so as to falsely imply that it is associated with Nordic Developer Academy, Nordic Semiconductor, or any other Nordic Semiconductor product, software or service.
You agree not to reproduce, duplicate, copy, sell, resell or in any other way exploit any portion of Nordic Developer Academy, use of Nordic Developer Academy, or access to Nordic Developer Academy without the express written permission by Nordic Semiconductor. You must not upload, post, host, or transmit unsolicited email, SMS, or \”spam\” messages.
You are responsible for ensuring that the information you post and the content you share does not;
contain false, misleading or otherwise erroneous information
infringe someone else’s copyrights or other intellectual property rights
contain sensitive personal data or
contain information that might be received as offensive or insulting.
Such information may be removed without prior notice.
Nordic Semiconductor reserves the right to at any time determine whether a use of Nordic Developer Academy is in violation of its requirements for acceptable use.
Violation of the at any time applicable requirements for acceptable use may result in termination of your account. We will take reasonable steps to notify you and state the reason for termination in such cases.
4. Routines for planned maintenance
Certain types of maintenance may imply a stop or reduction in availability of Nordic Developer Academy. Nordic Semiconductor does not warrant any level of service availability but will provide its best effort to limit the impact of any planned maintenance on the availability of Nordic Developer Academy.
5. Intellectual property rights
Nordic Semiconductor retains all rights to all elements of Nordic Developer Academy. This includes, but is not limited to, the concept, design, trademarks, know-how, trade secrets, copyrights and all other intellectual property rights.
Nordic Semiconductor receives all rights to all content uploaded or created in Nordic Developer Academy. You do not receive any license or usage rights to Nordic Developer Academy beyond what is explicitly stated in this Agreement.
6. Liability and damages
Nothing within these Terms of Use is intended to limit your statutory data privacy rights as a data subject, as described in the Nordic Developer Academy Privacy Policy. You acknowledge that errors might occur from time to time and waive any right to claim for compensation as a result of errors in Nordic Developer Academy. When an error occurs, you shall notify Nordic Semiconductor of the error and provide a description of the error situation.
You agree to indemnify Nordic Semiconductor for any loss, including indirect loss, arising out of or in connection with your use of Nordic Developer Academy or violations of these Terms of Use. Nordic Semiconductor shall not be held liable for, and does not warrant that (i) Nordic Developer Academy will meet your specific requirements, (ii) Nordic Developer Academy will be uninterrupted, timely, secure, or error-free, (iii) the results that may be obtained from the use of Nordic Developer Academy will be accurate or reliable, (iv) the quality of any products, services, information, or other material purchased or obtained by you through Nordic Developer Academy will meet your expectations, or that (v) any errors in Nordic Developer Academy will be corrected.
You accept that this is a service provided to you without any payment and hence you accept that Nordic Semiconductor will not be held responsible, or liable, for any breaches of these Terms of Use or any loss connected to your use of Nordic Developer Academy. Unless otherwise follows from mandatory law, Nordic Semiconductor will not accept any such responsibility or liability.
7. Change of terms
Nordic Semiconductor may update and change the Terms of Use from time to time. Nordic Semiconductor will seek to notify you about significant changes before such changes come into force and give you a possibility to evaluate the effects of proposed changes. Continued use of Nordic Developer Academy after any such changes shall constitute your acceptance of such changes. You can review the current version of the Terms of Use at any time at https://academy.nordicsemi.com/terms-of-service/
8. Transfer of rights
Nordic Semiconductor is entitled to transfer its rights and obligation pursuant to these Terms of Use to a third party as part of a merger or acquisition process, or as a result of other organizational changes.
9. Third Party Services
To the extent Nordic Developer Academy facilitates access to services provided by a third party, you agree to comply with the terms governing such third party services. Nordic Semiconductor shall not be held liable for any errors, omissions, inaccuracies, etc. related to such third party services.
10. Dispute resolution
The Terms of Use and any other legally binding agreement between yourself and Nordic Semiconductor shall be subject to Norwegian law and Norwegian courts’ exclusive jurisdiction.