Issue with Central application not detecting the Blood Pressure Service characteristics correctly.

Hello,

Unfortunately I was given the task to implement support for BPS service at the Central side of things. As you probably know, there is no example on BPS for Central application. Therefore (correctly or nor) I started using the multilink_central_pca10056_s140 example and modified it while building up the BPS support.

I am currently at the state where scanning, connection and bonding is working. But, there is something strange with the discovery of the characteristics which seem to varying from 0 to 3 during the time of the "discovery" process. And when it matters the most (at the call to ble_bps_on_db_disc_evt()) the variable p_evt->params.discovered_db.char_count is set to 0.

It is worth mentioning that currently I also experience a Reason 0x13 Disconnection from Peer (which I need to investigate further). But nevertheless, I would appreciated if you could check my implementation around the setting up of the characteristics I need (not more that the standard ones).

I am attaching main.c and the heavily modified ble_bps.c and ble_bps.h files which needed further work (since no other example has explored this service before).

/**
 * Copyright (c) 2014 - 2019, Nordic Semiconductor ASA
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form, except as embedded into a Nordic
 *    Semiconductor ASA integrated circuit in a product or a software update for
 *    such product, must reproduce the above copyright notice, this list of
 *    conditions and the following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 *
 * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 *
 * 4. This software, with or without modification, must only be used with a
 *    Nordic Semiconductor ASA integrated circuit.
 *
 * 5. Any software provided in binary form under this license must not be reverse
 *    engineered, decompiled, modified and/or disassembled.
 *
 * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
/**
 * @brief BLE LED Button Service central and client application main file.
 *
 * This example can be a central for up to 8 peripherals.
 * The peripheral is called ble_app_blinky and can be found in the ble_peripheral
 * folder.
 */

#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "nordic_common.h"
#include "nrf_sdh.h"
#include "nrf_sdh_ble.h"
#include "app_timer.h"
#include "bsp_btn_ble.h"
#include "ble.h"
#include "ble_hci.h"
#include "ble_advertising.h"
#include "ble_conn_params.h"
#include "ble_db_discovery.h"
#include "ble_conn_state.h"
#include "nrf_ble_gatt.h"
#include "nrf_pwr_mgmt.h"
#include "nrf_ble_scan.h"

#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"

#include "peer_manager.h"
#include "peer_manager_handler.h"
#include "fds.h"
#include "nrf_fstorage.h"
#include "ble_bps.h"




#define APP_BLE_CONN_CFG_TAG      1                                     /**< Tag that refers to the BLE stack configuration that is set with @ref sd_ble_cfg_set. The default tag is @ref APP_BLE_CONN_CFG_TAG. */
#define APP_BLE_OBSERVER_PRIO     3                                     /**< BLE observer priority of the application. There is no need to modify this value. */

#define CENTRAL_SCANNING_LED      BSP_BOARD_LED_0
#define CENTRAL_CONNECTED_LED     BSP_BOARD_LED_1
#define LEDBUTTON_LED             BSP_BOARD_LED_2                       /**< LED to indicate a change of state of the Button characteristic on the peer. */

#define LEDBUTTON_BUTTON          BSP_BUTTON_0                          /**< Button that writes to the LED characteristic of the peer. */
#define BUTTON_DETECTION_DELAY    APP_TIMER_TICKS(50)                   /**< Delay from a GPIOTE event until a button is reported as pushed (in number of timer ticks). */

#define SEC_PARAM_BOND              1                                   /**< Perform bonding. */
#define SEC_PARAM_MITM              0                                   /**< Man In The Middle protection not required. */
#define SEC_PARAM_LESC              1                                   /**< LE Secure Connections enabled. */
#define SEC_PARAM_KEYPRESS          0                                   /**< Keypress notifications not enabled. */
#define SEC_PARAM_IO_CAPABILITIES   BLE_GAP_IO_CAPS_NONE                /**< No I/O capabilities. */
#define SEC_PARAM_OOB               0                                   /**< Out Of Band data not available. */
#define SEC_PARAM_MIN_KEY_SIZE      7                                   /**< Minimum encryption key size in octets. */
#define SEC_PARAM_MAX_KEY_SIZE      16                                  /**< Maximum encryption key size in octets. */

BLE_BPS_DEF(m_bps_c);
NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
               NRF_SDH_BLE_CENTRAL_LINK_COUNT,
               NRF_BLE_GQ_QUEUE_SIZE);

static char const m_target_periph_name[] = "A&D_";             /**< Name of the device to try to connect to. This name is searched for in the scanning report data. */

/**@brief BPS UUID. */
static ble_uuid_t const m_bps_uuid =
{
    .uuid = BLE_UUID_BLOOD_PRESSURE_SERVICE,
    .type = BLE_UUID_TYPE_BLE
};


/**@brief Function for handling asserts in the SoftDevice.
 *
 * @details This function is called in case of an assert in the SoftDevice.
 *
 * @warning This handler is only an example and is not meant for the final product. You need to analyze
 *          how your product is supposed to react in case of an assert.
 * @warning On assert from the SoftDevice, the system can only recover on reset.
 *
 * @param[in] line_num     Line number of the failing assert call.
 * @param[in] p_file_name  File name of the failing assert call.
 */
void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name)
{
    app_error_handler(0xDEADBEEF, line_num, p_file_name);
}


/**@brief Function for handling the LED Button Service Client errors.
 *
 * @param[in]   nrf_error   Error code containing information about what went wrong.
 */
static void lbs_error_handler(uint32_t nrf_error)
{
    APP_ERROR_HANDLER(nrf_error);
}



/**@brief Function for the LEDs initialization.
 *
 * @details Initializes all LEDs used by the application.
 */
static void leds_init(void)
{
    bsp_board_init(BSP_INIT_LEDS);
}


static void scan_evt_handler(scan_evt_t const * p_scan_evt)
{
    ret_code_t err_code;

    switch(p_scan_evt->scan_evt_id)
    {
        case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
        {
            err_code = p_scan_evt->params.connecting_err.err_code;
            APP_ERROR_CHECK(err_code);
        } break;

        case NRF_BLE_SCAN_EVT_CONNECTED:
         {
            ble_gap_evt_connected_t const * p_connected =
                             p_scan_evt->params.connected.p_connected;
             // Scan is automatically stopped by the connection.
             NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
                      p_connected->peer_addr.addr[0],
                      p_connected->peer_addr.addr[1],
                      p_connected->peer_addr.addr[2],
                      p_connected->peer_addr.addr[3],
                      p_connected->peer_addr.addr[4],
                      p_connected->peer_addr.addr[5]
                        );
         } break;

        default:
            break;
    }
}


/**@brief Function for initializing the scanning and setting the filters.
 */
static void scan_init(void)
{
    ret_code_t          err_code;
    nrf_ble_scan_init_t init_scan;

    memset(&init_scan, 0, sizeof(init_scan));

    init_scan.connect_if_match = true;
    init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;

    err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
    APP_ERROR_CHECK(err_code);

    err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_NAME_FILTER, m_target_periph_name);
    APP_ERROR_CHECK(err_code);

    err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_NAME_FILTER, false);
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for starting scanning. */
static void scan_start(void)
{
    ret_code_t ret;

    NRF_LOG_INFO("Start scanning for device name %s.", (uint32_t)m_target_periph_name);
    ret = nrf_ble_scan_start(&m_scan);
    APP_ERROR_CHECK(ret);
    // Turn on the LED to signal scanning.
    bsp_board_led_on(CENTRAL_SCANNING_LED);
}



/**@brief Function for handling BLE events.
 *
 * @param[in]   p_ble_evt   Bluetooth stack event.
 * @param[in]   p_context   Unused.
 */
static void ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context)
{
    ret_code_t err_code;
    static uint16_t start_handle = 1;
    static uint16_t last = 0;

    // For readability.
    ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;

    //NRF_LOG_INFO("EVT ID: 0x%x ", p_ble_evt->header.evt_id);

    switch (p_ble_evt->header.evt_id)
    {
        // Upon connection, check which peripheral is connected, initiate DB
        // discovery, update LEDs status, and resume scanning, if necessary.
        case BLE_GAP_EVT_CONNECTED:
        {
            NRF_LOG_INFO("Connection 0x%x established, starting DB discovery.",
                         p_gap_evt->conn_handle);

            APP_ERROR_CHECK_BOOL(p_gap_evt->conn_handle < NRF_SDH_BLE_CENTRAL_LINK_COUNT);

            ble_bps_on_ble_evt(p_ble_evt, &m_bps_c);

            memset(&m_db_disc, 0, sizeof(m_db_disc));
            err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);

            // Update LEDs status and check whether it is needed to look for more
            // peripherals to connect to.
            bsp_board_led_on(CENTRAL_CONNECTED_LED);
            if (ble_conn_state_central_conn_count() == NRF_SDH_BLE_CENTRAL_LINK_COUNT)
            {
                bsp_board_led_off(CENTRAL_SCANNING_LED);
            }
            else
            {
                // Resume scanning.
                bsp_board_led_on(CENTRAL_SCANNING_LED);
                scan_start();
            }
        } break; // BLE_GAP_EVT_CONNECTED

        // Upon disconnection, reset the connection handle of the peer that disconnected, update
        // the LEDs status and start scanning again.
        case BLE_GAP_EVT_DISCONNECTED:
        {
            NRF_LOG_INFO("Central link 0x%x disconnected (reason: 0x%x)",
                         p_gap_evt->conn_handle,
                         p_gap_evt->params.disconnected.reason);

            if (ble_conn_state_central_conn_count() == 0)
            {
                err_code = app_button_disable();
                APP_ERROR_CHECK(err_code);

                // Turn off the LED that indicates the connection.
                bsp_board_led_off(CENTRAL_CONNECTED_LED);
            }

            // Start scanning.
            scan_start();

            // Turn on the LED for indicating scanning.
            bsp_board_led_on(CENTRAL_SCANNING_LED);

            start_handle = 1;
            last = 0;

        } break;

        case BLE_GAP_EVT_TIMEOUT:
        {
            // Timeout for scanning is not specified, so only the connection requests can time out.
            if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
            {
                NRF_LOG_DEBUG("Connection request timed out.");
            }
        } break;

        case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
        {
            NRF_LOG_DEBUG("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST.");
            // Accept parameters requested by peer.
            err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
                                        &p_gap_evt->params.conn_param_update_request.conn_params);
            APP_ERROR_CHECK(err_code);
        } break;

        case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
        {
            NRF_LOG_DEBUG("PHY update request.");
            ble_gap_phys_t const phys =
            {
                .rx_phys = BLE_GAP_PHY_AUTO,
                .tx_phys = BLE_GAP_PHY_AUTO,
            };
            err_code = sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
            APP_ERROR_CHECK(err_code);
        } break;

        case BLE_GATTC_EVT_TIMEOUT:
        {
            // Disconnect on GATT client timeout event.
            NRF_LOG_DEBUG("GATT client timeout.");
            err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
            APP_ERROR_CHECK(err_code);
        } break;

        case BLE_GATTS_EVT_TIMEOUT:
        {
            // Disconnect on GATT server timeout event.
            NRF_LOG_DEBUG("GATT server timeout.");
            err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
                                             BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
            APP_ERROR_CHECK(err_code);
        } break;

         /*case BLE_GAP_EVT_AUTH_STATUS:
             NRF_LOG_INFO("BLE_GAP_EVT_AUTH_STATUS: status=0x%x bond=0x%x lv4: %d kdist_own:0x%x kdist_peer:0x%x",
                          p_ble_evt->evt.gap_evt.params.auth_status.auth_status,
                          p_ble_evt->evt.gap_evt.params.auth_status.bonded,
                          p_ble_evt->evt.gap_evt.params.auth_status.sm1_levels.lv4,
                          *((uint8_t *)&p_ble_evt->evt.gap_evt.params.auth_status.kdist_own),
                          *((uint8_t *)&p_ble_evt->evt.gap_evt.params.auth_status.kdist_peer));
            break;

          /*case BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP:
                	NRF_LOG_INFO("Found service");
                        NRF_LOG_INFO("Last handle %x , start handle %x ", last, start_handle);

            if (p_ble_evt->evt.gattc_evt.gatt_status != BLE_GATT_STATUS_ATTERR_ATTRIBUTE_NOT_FOUND)
            {
              last = p_ble_evt->evt.gattc_evt.params.prim_srvc_disc_rsp.count - 1;
              start_handle = p_ble_evt->evt.gattc_evt.params.prim_srvc_disc_rsp.services[last].handle_range.end_handle + 1;
              err_code = sd_ble_gattc_primary_services_discover(p_gap_evt->conn_handle, start_handle, NULL);
              APP_ERROR_CHECK(err_code);
            }
            else
            {
              NRF_LOG_INFO("Got BLE_GATT_STATUS_ATTERR_ATTRIBUTE_NOT_FOUND");  
            }*/

                            
            break;

        default:
            // No implementation needed.
            break;
    }
}

/**@brief Function for handling the Nordic UART Service Client errors.
 *
 * @param[in]   nrf_error   Error code containing information about what went wrong.
 */
static void bps_error_handler(uint32_t nrf_error)
{
    APP_ERROR_HANDLER(nrf_error);
}

static void ble_bps_evt_handler(ble_bps_t * p_bps, ble_bps_evt_t const * ble_bps_evt)
{
    ret_code_t err_code;

    NRF_LOG_INFO("BPS EVT ID:%d ", ble_bps_evt->evt_type);
    switch (ble_bps_evt->evt_type)
    {
        case BLE_BPS_EVT_DISCOVERY_COMPLETE:
            NRF_LOG_INFO("Discovery complete.");
            err_code = ble_bps_handles_assign(p_bps, ble_bps_evt->conn_handle);
            APP_ERROR_CHECK(err_code);

            // Initiate bonding.
            err_code = pm_conn_secure(ble_bps_evt->conn_handle, false);
            if (err_code != NRF_ERROR_BUSY)
            {
                APP_ERROR_CHECK(err_code);
            }

            bps_enable_indication(p_bps);
            APP_ERROR_CHECK(err_code);

            NRF_LOG_INFO("Connected to device with BPS.");
            break;
    }
}


static void bps_init(void)
{
    ret_code_t       err_code;
    ble_bps_init_t   init;

    init.evt_handler   = ble_bps_evt_handler;
    init.error_handler = bps_error_handler;
    init.p_gatt_queue  = &m_ble_gatt_queue;

    err_code = ble_bps_init(&m_bps_c, &init);
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for initializing the BLE stack.
 *
 * @details Initializes the SoftDevice and the BLE event interrupts.
 */
static void ble_stack_init(void)
{
    ret_code_t err_code;

    err_code = nrf_sdh_enable_request();
    APP_ERROR_CHECK(err_code);

    // Configure the BLE stack using the default settings.
    // Fetch the start address of the application RAM.
    uint32_t ram_start = 0;
    err_code = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &ram_start);
    APP_ERROR_CHECK(err_code);

    // Enable BLE stack.
    err_code = nrf_sdh_ble_enable(&ram_start);
    APP_ERROR_CHECK(err_code);

    // Register a handler for BLE events.
    NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, ble_evt_handler, NULL);
}

/**@brief Function for handling Peer Manager events.
 *
 * @param[in] p_evt  Peer Manager event.
 */
static void pm_evt_handler(pm_evt_t const * p_evt)
{
    pm_handler_on_pm_evt(p_evt);
    pm_handler_flash_clean(p_evt);

    switch (p_evt->evt_id)
    {
        case PM_EVT_PEERS_DELETE_SUCCEEDED:
            // Bonds are deleted. Start scanning.
            scan_start();
            break;

        default:
            break;
    }
}

/**@brief Function for the Peer Manager initialization.
 */
static void peer_manager_init(void)
{
    ble_gap_sec_params_t sec_param;
    ret_code_t err_code;

    err_code = pm_init();
    APP_ERROR_CHECK(err_code);

    memset(&sec_param, 0, sizeof(ble_gap_sec_params_t));

    // Security parameters to be used for all security procedures.
    sec_param.bond           = SEC_PARAM_BOND;
    sec_param.mitm           = SEC_PARAM_MITM;
    sec_param.lesc           = SEC_PARAM_LESC;
    sec_param.keypress       = SEC_PARAM_KEYPRESS;
    sec_param.io_caps        = SEC_PARAM_IO_CAPABILITIES;
    sec_param.oob            = SEC_PARAM_OOB;
    sec_param.min_key_size   = SEC_PARAM_MIN_KEY_SIZE;
    sec_param.max_key_size   = SEC_PARAM_MAX_KEY_SIZE;
    sec_param.kdist_own.enc  = 1;
    sec_param.kdist_own.id   = 1;
    sec_param.kdist_peer.enc = 1;
    sec_param.kdist_peer.id  = 1;

    err_code = pm_sec_params_set(&sec_param);
    APP_ERROR_CHECK(err_code);

    err_code = pm_register(pm_evt_handler);
    APP_ERROR_CHECK(err_code);
}

/**@brief Function for writing to the LED characteristic of all connected clients.
 *
 * @details Based on whether the button is pressed or released, this function writes a high or low
 *          LED status to the server.
 *
 * @param[in] button_action The button action (press or release).
 *            Determines whether the LEDs of the servers are ON or OFF.
 *
 * @return If successful, NRF_SUCCESS is returned. Otherwise, returns the error code from @ref ble_lbs_led_status_send.
 */
/*static ret_code_t led_status_send_to_all(uint8_t button_action)
{
    ret_code_t err_code;

    for (uint32_t i = 0; i< NRF_SDH_BLE_CENTRAL_LINK_COUNT; i++)
    {
        err_code = ble_lbs_led_status_send(&m_lbs_c[i], button_action);
        if (err_code != NRF_SUCCESS &&
            err_code != BLE_ERROR_INVALID_CONN_HANDLE &&
            err_code != NRF_ERROR_INVALID_STATE)
        {
            return err_code;
        }
    }
        return NRF_SUCCESS;
}*/


/**@brief Function for handling events from the button handler module.
 *
 * @param[in] pin_no        The pin that the event applies to.
 * @param[in] button_action The button action (press or release).
 */
static void button_event_handler(uint8_t pin_no, uint8_t button_action)
{
    ret_code_t err_code;

    switch (pin_no)
    {
        case LEDBUTTON_BUTTON:
            //err_code = led_status_send_to_all(button_action);
            if (err_code == NRF_SUCCESS)
            {
                NRF_LOG_INFO("LBS write LED state %d", button_action);
            }
            break;

        default:
            APP_ERROR_HANDLER(pin_no);
            break;
    }
}


/**@brief Function for initializing the button handler module.
 */
static void buttons_init(void)
{
    ret_code_t err_code;

   // The array must be static because a pointer to it is saved in the button handler module.
    static app_button_cfg_t buttons[] =
    {
        {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
    };

    err_code = app_button_init(buttons, ARRAY_SIZE(buttons), BUTTON_DETECTION_DELAY);
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for handling database discovery events.
 *
 * @details This function is a callback function to handle events from the database discovery module.
 *          Depending on the UUIDs that are discovered, this function forwards the events
 *          to their respective services.
 *
 * @param[in] p_event  Pointer to the database discovery event.
 */
static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
{
    NRF_LOG_INFO("call to ble_bps_on_db_disc_evt for instance 0x%x and handle 0x%x!",
                  p_evt->params.p_db_instance,
                  p_evt->conn_handle);

    NRF_LOG_INFO("APP FOUND %d CHARACTERISTICS.", p_evt->params.discovered_db.char_count);

    ble_bps_on_db_disc_evt(&m_bps_c, p_evt);
}



/** @brief Database discovery initialization.
 */
static void db_discovery_init(void)
{
    ble_db_discovery_init_t db_init;

    memset(&db_init, 0, sizeof(ble_db_discovery_init_t));

    db_init.evt_handler  = db_disc_handler;
    db_init.p_gatt_queue = &m_ble_gatt_queue;

    ret_code_t err_code = ble_db_discovery_init(&db_init);
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for initializing power management.
 */
static void power_management_init(void)
{
    ret_code_t err_code;
    err_code = nrf_pwr_mgmt_init();
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for handling the idle state (main loop).
 *
 * @details This function handles any pending log operations, then sleeps until the next event occurs.
 */
static void idle_state_handle(void)
{
    if (NRF_LOG_PROCESS() == false)
    {
        nrf_pwr_mgmt_run();
    }
}


/** @brief Function for initializing the log module.
 */
static void log_init(void)
{
    ret_code_t err_code = NRF_LOG_INIT(NULL);
    APP_ERROR_CHECK(err_code);

    NRF_LOG_DEFAULT_BACKENDS_INIT();
}


/** @brief Function for initializing the timer.
 */
static void timer_init(void)
{
    ret_code_t err_code = app_timer_init();
    APP_ERROR_CHECK(err_code);
}


/**@brief Function for initializing the GATT module.
 */
static void gatt_init(void)
{
    ret_code_t err_code = nrf_ble_gatt_init(&m_gatt, NULL);
    APP_ERROR_CHECK(err_code);
}


int main(void)
{
    // Initialize.
    log_init();
    timer_init();
    leds_init();
    buttons_init();
    db_discovery_init();
    power_management_init();
    ble_stack_init();
    gatt_init();
    bps_init();
    ble_conn_state_init();
    scan_init();
    peer_manager_init();


    // Start execution.
    NRF_LOG_INFO("C-Detect-LIKE example started.");
    scan_start();

    for (;;)
    {
        idle_state_handle();
    }
}
ble_bps.h
/**
 * Copyright (c) 2012 - 2019, Nordic Semiconductor ASA
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form, except as embedded into a Nordic
 *    Semiconductor ASA integrated circuit in a product or a software update for
 *    such product, must reproduce the above copyright notice, this list of
 *    conditions and the following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 *
 * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 *
 * 4. This software, with or without modification, must only be used with a
 *    Nordic Semiconductor ASA integrated circuit.
 *
 * 5. Any software provided in binary form under this license must not be reverse
 *    engineered, decompiled, modified and/or disassembled.
 *
 * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
/* Attention!
 * To maintain compliance with Nordic Semiconductor ASA's Bluetooth profile
 * qualification listings, this section of source code must not be modified.
 */
#include "sdk_common.h"
//#if NRF_MODULE_ENABLED(BLE_BPS)
#include "ble_bps.h"
#include "ble_err.h"
#include <string.h>
#include "nordic_common.h"
#include "ble_srv_common.h"


#define OPCODE_LENGTH   1     /**< Length of opcode inside Blood Pressure Measurement packet. */
#define HANDLE_LENGTH   2     /**< Length of handle inside Blood Pressure Measurement packet. */
#define MAX_BPM_LEN     (BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH)    /**< Maximum size of a transmitted Blood Pressure Measurement. */

// Blood Pressure Measurement Flags bits
#define BPS_MEAS_BLOOD_PRESSURE_UNITS_FLAG_BIT (0x01 << 0)  /**< Blood Pressure Units Flag bit. */
#define BPS_MEAS_TIME_STAMP_FLAG_BIT           (0x01 << 1)  /**< Time Stamp Flag bit. */
#define BPS_MEAS_PULSE_RATE_FLAG_BIT           (0x01 << 2)  /**< Pulse Rate Flag bit. */
#define BPS_MEAS_USER_ID_FLAG_BIT              (0x01 << 3)  /**< User ID Flag bit. */
#define BPS_MEAS_MEASUREMENT_STATUS_FLAG_BIT   (0x01 << 4)  /**< Measurement Status Flag bit. */


/**@brief Function for interception of GATT errors and @ref nrf_ble_gq errors.
 *
 * @param[in] nrf_error   Error code.
 * @param[in] p_ctx       Parameter from the event handler.
 * @param[in] conn_handle Connection handle.
 */
static void gatt_error_handler(uint32_t   nrf_error,
                               void     * p_ctx,
                               uint16_t   conn_handle)
{
    ble_bps_t * p_bps = (ble_bps_t *)p_ctx;

    if (p_bps->error_handler != NULL)
    {
        p_bps->error_handler(nrf_error);
    }
}


/**@brief Function for handling the Connect event.
 *
 * @param[in]   p_bps       Blood Pressure Service structure.
 * @param[in]   p_ble_evt   Event received from the BLE stack.
 */
static void on_connect(ble_bps_t * p_bps, ble_evt_t const * p_ble_evt)
{
    ret_code_t err_code;

    p_bps->conn_handle = p_ble_evt->evt.gap_evt.conn_handle;

    err_code = nrf_ble_gq_conn_handle_register(p_bps->p_gatt_queue, 
                                               p_ble_evt->evt.gap_evt.conn_handle);

    if ((p_bps->error_handler != NULL) &&
        (err_code != NRF_SUCCESS))
    {
        p_bps->error_handler(err_code);
    }
}


/**@brief Function for handling the Disconnect event.
 *
 * @param[in]   p_bps       Blood Pressure Service structure.
 * @param[in]   p_ble_evt   Event received from the BLE stack.
 */
static void on_disconnect(ble_bps_t * p_bps, ble_evt_t const * p_ble_evt)
{
    UNUSED_PARAMETER(p_ble_evt);
    p_bps->conn_handle = BLE_CONN_HANDLE_INVALID;
}


/**@brief Function for handling the write events to the Blood Pressure Measurement characteristic.
 *
 * @param[in]   p_bps         Blood Pressure Service structure.
 * @param[in]   p_evt_write   Write event received from the BLE stack.
 */
static void on_cccd_write(ble_bps_t * p_bps, ble_gatts_evt_write_t const * p_evt_write)
{
    if (p_evt_write->len == 2)
    {
        // CCCD written, update indication state
        if (p_bps->evt_handler != NULL)
        {
            ble_bps_evt_t evt;

            if (ble_srv_is_indication_enabled(p_evt_write->data))
            {
                evt.evt_type = BLE_BPS_EVT_INDICATION_ENABLED;
            }
            else
            {
                evt.evt_type = BLE_BPS_EVT_INDICATION_DISABLED;
            }

            p_bps->evt_handler(p_bps, &evt);
        }
    }
}


/**@brief Function for handling the Write event.
 *
 * @param[in]   p_bps       Blood Pressure Service structure.
 * @param[in]   p_ble_evt   Event received from the BLE stack.
 */
static void on_write(ble_bps_t * p_bps, ble_evt_t const * p_ble_evt)
{
    ble_gatts_evt_write_t const * p_evt_write = &p_ble_evt->evt.gatts_evt.params.write;

    if (p_evt_write->handle == p_bps->meas_handles.cccd_handle)
    {
        on_cccd_write(p_bps, p_evt_write);
    }
}


/**@brief Function for handling the HVC event.
 *
 * @details Handles HVC events from the BLE stack.
 *
 * @param[in]   p_bps       Blood Pressure Service structure.
 * @param[in]   p_ble_evt   Event received from the BLE stack.
 */
static void on_hvc(ble_bps_t * p_bps, ble_evt_t const * p_ble_evt)
{
    ble_gatts_evt_hvc_t const * p_hvc = &p_ble_evt->evt.gatts_evt.params.hvc;

    if (p_hvc->handle == p_bps->meas_handles.value_handle)
    {
        ble_bps_evt_t evt;

        evt.evt_type = BLE_BPS_EVT_INDICATION_CONFIRMED;
        p_bps->evt_handler(p_bps, &evt);
    }
}


void ble_bps_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_context)
{
    ble_bps_t * p_bps = (ble_bps_t *)p_context;

    switch (p_ble_evt->header.evt_id)
    {
        case BLE_GAP_EVT_CONNECTED:
            on_connect(p_bps, p_ble_evt);
            break;

        case BLE_GAP_EVT_DISCONNECTED:
            on_disconnect(p_bps, p_ble_evt);
            break;

        case BLE_GATTS_EVT_WRITE:
            on_write(p_bps, p_ble_evt);
            break;

        case BLE_GATTS_EVT_HVC:
            on_hvc(p_bps, p_ble_evt);
            break;

        default:
            // No implementation needed.
            break;
    }
}


/**@brief Function for encoding a Blood Pressure Measurement.
 *
 * @param[in]   p_bps              Blood Pressure Service structure.
 * @param[in]   p_bps_meas         Measurement to be encoded.
 * @param[out]  p_encoded_buffer   Buffer where the encoded data will be written.
 *
 * @return      Size of encoded data.
 */
static uint8_t bps_measurement_encode(ble_bps_t      * p_bps,
                                      ble_bps_meas_t * p_bps_meas,
                                      uint8_t        * p_encoded_buffer)
{
    uint8_t  flags = 0;
    uint8_t  len   = 1;
    uint16_t encoded_sfloat;

    // Set measurement units flag
    if (p_bps_meas->blood_pressure_units_in_kpa)
    {
        flags |= BPS_MEAS_BLOOD_PRESSURE_UNITS_FLAG_BIT;
    }

    // Blood Pressure Measurement - Systolic
    encoded_sfloat = ((p_bps_meas->blood_pressure_systolic.exponent << 12) & 0xF000) |
                     ((p_bps_meas->blood_pressure_systolic.mantissa <<  0) & 0x0FFF);
    len += uint16_encode(encoded_sfloat, &p_encoded_buffer[len]);

    // Blood Pressure Measurement - Diastolic
    encoded_sfloat = ((p_bps_meas->blood_pressure_diastolic.exponent << 12) & 0xF000) |
                     ((p_bps_meas->blood_pressure_diastolic.mantissa <<  0) & 0x0FFF);
    len += uint16_encode(encoded_sfloat, &p_encoded_buffer[len]);

    // Blood Pressure Measurement - Mean Arterial Pressure
    encoded_sfloat = ((p_bps_meas->mean_arterial_pressure.exponent << 12) & 0xF000) |
                     ((p_bps_meas->mean_arterial_pressure.mantissa <<  0) & 0x0FFF);
    len += uint16_encode(encoded_sfloat, &p_encoded_buffer[len]);

    // Time Stamp field
    if (p_bps_meas->time_stamp_present)
    {
        flags |= BPS_MEAS_TIME_STAMP_FLAG_BIT;
        len   += ble_date_time_encode(&p_bps_meas->time_stamp, &p_encoded_buffer[len]);
    }

    // Pulse Rate
    if (p_bps_meas->pulse_rate_present)
    {
        flags |= BPS_MEAS_PULSE_RATE_FLAG_BIT;

        encoded_sfloat = ((p_bps_meas->pulse_rate.exponent << 12) & 0xF000) |
                         ((p_bps_meas->pulse_rate.mantissa <<  0) & 0x0FFF);
        len += uint16_encode(encoded_sfloat, &p_encoded_buffer[len]);
    }

    // User ID
    if (p_bps_meas->user_id_present)
    {
        flags                  |= BPS_MEAS_USER_ID_FLAG_BIT;
        p_encoded_buffer[len++] = p_bps_meas->user_id;
    }

    // Measurement Status
    if (p_bps_meas->measurement_status_present)
    {
        flags |= BPS_MEAS_MEASUREMENT_STATUS_FLAG_BIT;
        len   += uint16_encode(p_bps_meas->measurement_status, &p_encoded_buffer[len]);
    }

    // Flags field
    p_encoded_buffer[0] = flags;

    return len;
}


uint32_t ble_bps_init(ble_bps_t * p_bps, ble_bps_init_t const * p_bps_init)
{
    VERIFY_PARAM_NOT_NULL(p_bps);
    VERIFY_PARAM_NOT_NULL(p_bps_init);
    VERIFY_PARAM_NOT_NULL(p_bps_init->p_gatt_queue);

    uint32_t              err_code;
    uint16_t              service_handle;
    uint8_t               init_value_encoded[MAX_BPM_LEN];
    uint8_t               initial_feature_len;
    ble_bps_meas_t        initial_bpm;
    ble_uuid_t            ble_uuid;
    ble_add_char_params_t add_meas_char_params;
    ble_add_char_params_t add_feat_char_params;

    // Initialize service structure
    p_bps->evt_handler   = p_bps_init->evt_handler;
    p_bps->error_handler = p_bps_init->error_handler;
    p_bps->p_gatt_queue  = p_bps_init->p_gatt_queue;
    p_bps->conn_handle   = BLE_CONN_HANDLE_INVALID;
    p_bps->feature       = p_bps_init->feature;
    p_bps->meas_handles.value_handle = BLE_GATT_HANDLE_INVALID;
    p_bps->feature_handles.value_handle = BLE_GATT_HANDLE_INVALID;

    // Add service
    BLE_UUID_BLE_ASSIGN(ble_uuid, BLE_UUID_BLOOD_PRESSURE_SERVICE);

    err_code = sd_ble_gatts_service_add(BLE_GATTS_SRVC_TYPE_PRIMARY, &ble_uuid, &service_handle);
    if (err_code != NRF_SUCCESS)
    {
        return err_code;
    }

    // Add measurement characteristic
    memset(&initial_bpm, 0, sizeof(initial_bpm));
    memset(&add_meas_char_params, 0, sizeof(add_meas_char_params));

    add_meas_char_params.uuid                = BLE_UUID_BLOOD_PRESSURE_MEASUREMENT_CHAR;
    add_meas_char_params.uuid_type           = 0;
    add_meas_char_params.max_len             = MAX_BPM_LEN;
    add_meas_char_params.is_var_len          = true;
    add_meas_char_params.init_len            = bps_measurement_encode(p_bps, &initial_bpm, init_value_encoded);
    add_meas_char_params.p_init_value        = init_value_encoded;
    add_meas_char_params.char_props.indicate = 1;
    add_meas_char_params.cccd_write_access   = p_bps_init->bp_cccd_wr_sec;

    err_code = characteristic_add(service_handle, &add_meas_char_params, &(p_bps->meas_handles));
    if (err_code != NRF_SUCCESS)
    {
        return err_code;
    }

    // Add feature characteristic
    memset(&add_feat_char_params, 0, sizeof(add_feat_char_params));
    initial_feature_len = uint16_encode(p_bps_init->feature, init_value_encoded);

    add_feat_char_params.uuid            = BLE_UUID_BLOOD_PRESSURE_FEATURE_CHAR;
    add_meas_char_params.uuid_type       = 0;
    add_feat_char_params.max_len         = initial_feature_len;
    add_feat_char_params.init_len        = initial_feature_len;
    add_feat_char_params.p_init_value    = init_value_encoded;
    add_feat_char_params.char_props.read = 1;
    add_feat_char_params.read_access     = p_bps_init->bp_feature_rd_sec;

    err_code = characteristic_add(service_handle, &add_feat_char_params, &p_bps->feature_handles);
    if (err_code != NRF_SUCCESS)
    {
        return err_code;
    }

    ble_uuid.uuid = BLE_UUID_BLOOD_PRESSURE_SERVICE;
    ble_uuid.type = BLE_UUID_TYPE_BLE;

    return ble_db_discovery_evt_register(&ble_uuid);//NRF_SUCCESS;
}


uint32_t ble_bps_measurement_send(ble_bps_t * p_bps, ble_bps_meas_t * p_bps_meas)
{
    uint32_t err_code;

    // Send value if connected
    if (p_bps->conn_handle != BLE_CONN_HANDLE_INVALID)
    {
        uint8_t                encoded_bps_meas[MAX_BPM_LEN];
        uint16_t               len;
        nrf_ble_gq_req_t       bps_req;

        len     = bps_measurement_encode(p_bps, p_bps_meas, encoded_bps_meas);

        memset(&bps_req, 0, sizeof(nrf_ble_gq_req_t));

        bps_req.type                               = NRF_BLE_GQ_REQ_GATTS_HVX;
        bps_req.error_handler.cb                   = gatt_error_handler;
        bps_req.error_handler.p_ctx                = p_bps;
        bps_req.params.gatts_hvx.handle  = p_bps->meas_handles.value_handle;
        bps_req.params.gatts_hvx.offset  = 0;
        bps_req.params.gatts_hvx.p_data  = encoded_bps_meas;
        bps_req.params.gatts_hvx.p_len   = &len;
        bps_req.params.gatts_hvx.type    = BLE_GATT_HVX_INDICATION;

        err_code = nrf_ble_gq_item_add(p_bps->p_gatt_queue, &bps_req, p_bps->conn_handle);
    }
    else
    {
        err_code = NRF_ERROR_INVALID_STATE;
    }

    return err_code;
}


uint32_t ble_bps_is_indication_enabled(ble_bps_t * p_bps, bool * p_indication_enabled)
{
    uint32_t err_code;
    uint8_t  cccd_value_buf[BLE_CCCD_VALUE_LEN];
    ble_gatts_value_t gatts_value;

    // Initialize value struct.
    memset(&gatts_value, 0, sizeof(gatts_value));

    gatts_value.len     = BLE_CCCD_VALUE_LEN;
    gatts_value.offset  = 0;
    gatts_value.p_value = cccd_value_buf;

    err_code = sd_ble_gatts_value_get(p_bps->conn_handle,
                                      p_bps->meas_handles.cccd_handle,
                                      &gatts_value);

    if (err_code == NRF_SUCCESS)
    {
        *p_indication_enabled = ble_srv_is_indication_enabled(cccd_value_buf);
    }
    if (err_code == BLE_ERROR_GATTS_SYS_ATTR_MISSING)
    {
        *p_indication_enabled = false;
        return NRF_SUCCESS;
    }
    return err_code;
}

void ble_bps_on_db_disc_evt(ble_bps_t * p_bps, const ble_db_discovery_evt_t * p_evt)
{
    // Check if the Heart Rate Service was discovered.
    if (p_evt->evt_type == BLE_DB_DISCOVERY_COMPLETE &&
        p_evt->params.discovered_db.srv_uuid.uuid == BLE_UUID_BLOOD_PRESSURE_SERVICE &&
        p_evt->params.discovered_db.srv_uuid.type == BLE_UUID_TYPE_BLE)
    {
        // Find the CCCD Handle of the Heart Rate Measurement characteristic.
        uint32_t i;

        ble_bps_evt_t evt; 

        evt.evt_type    = BLE_BPS_EVT_DISCOVERY_COMPLETE;
        evt.conn_handle = p_evt->conn_handle;



        for (i = 0; i < p_evt->params.discovered_db.char_count; i++)
        {
            /* TODO SOMETHING SIMILAR AS BELOW...
            
            
            if (p_evt->params.discovered_db.charateristics[i].characteristic.uuid.uuid ==
                BLE_UUID_HEART_RATE_MEASUREMENT_CHAR)
            {
                // Found Heart Rate characteristic. Store CCCD handle and break.
                evt.params.peer_db.hrm_cccd_handle =
                    p_evt->params.discovered_db.charateristics[i].cccd_handle;
                evt.params.peer_db.hrm_handle =
                    p_evt->params.discovered_db.charateristics[i].characteristic.handle_value;
                break;
            }*/
        }

        if (p_bps->evt_handler != NULL)
        {
            evt.conn_handle = p_evt->conn_handle;
            evt.evt_type    = BLE_BPS_EVT_DISCOVERY_COMPLETE;
            p_bps->evt_handler(p_bps, &evt);
        }
    }
}

uint32_t ble_bps_handles_assign(ble_bps_t * p_bps, uint16_t conn_handle)
{
    VERIFY_PARAM_NOT_NULL(p_bps);

    p_bps->conn_handle = conn_handle; 

    return nrf_ble_gq_conn_handle_register(p_bps->p_gatt_queue, conn_handle);
}

/**@brief Function for creating a message for writing to the CCCD.
 */
static uint32_t bps_cccd_configure_indication(ble_bps_t * p_bps, bool enable)
{
    nrf_ble_gq_req_t bps_c_req;
    uint8_t          cccd[BLE_CCCD_VALUE_LEN];
    uint16_t         cccd_val = enable ? BLE_GATT_HVX_INDICATION : 0;

    cccd[0] = LSB_16(cccd_val);
    cccd[1] = MSB_16(cccd_val);

    memset(&bps_c_req, 0, sizeof(bps_c_req));
 
    bps_c_req.type                        = NRF_BLE_GQ_REQ_GATTC_WRITE;
    bps_c_req.error_handler.cb            = gatt_error_handler;
    bps_c_req.error_handler.p_ctx         = p_bps;
    bps_c_req.params.gattc_write.handle   = p_bps->meas_handles.cccd_handle;
    bps_c_req.params.gattc_write.len      = BLE_CCCD_VALUE_LEN;
    bps_c_req.params.gattc_write.p_value  = cccd;
    bps_c_req.params.gattc_write.offset   = 0;
    bps_c_req.params.gattc_write.write_op = BLE_GATT_OP_WRITE_REQ;

    return nrf_ble_gq_item_add(p_bps->p_gatt_queue, &bps_c_req, p_bps->conn_handle);
}

uint32_t bps_enable_indication(ble_bps_t * p_bps)
{
    VERIFY_PARAM_NOT_NULL(p_bps);

    if (p_bps->conn_handle == BLE_CONN_HANDLE_INVALID)
    {
        return NRF_ERROR_INVALID_STATE;
    }

    return bps_cccd_configure_indication(p_bps, true);
}

//#endif // NRF_MODULE_ENABLED(BLE_BPS)

Regards

George

  • Hi George

    To confirm, the attached files will be the client implementation, despite still having the ble_bps name usually used on the server side? 

    I think a safer way to go about it is to start out with an existing client implementation, such as the ble_hrs_c module, and modify this to target the blood pressure service and characteristics rather than the heart rate related ones.

    Then you will see exactly which steps are required for a service client module. 

    Looking at your code I already notice some references to the heart rate service, but also see a lot of code which I must assume is left over from the ble_pbs module. For instance you are still adding services and characteristics in the init function, which is not something you should do on the client side. 

    The difference between the two services are not that large. The Blood Pressure Measurement characteristic is similar to the Heart Rate Measurement characteristic, only it uses indications rather than notifications (indications need to be configured in a very similar way, having the client write to the CCCD in order to enable them on the server side). 

    Then you have a second Blood Pressure Feature characteristic which only supports read, which means you don't need to worry about writing to the CCCD etc, but need to implement a function to read it out instead. 

    The first step of such a conversion should be to rename all the functions, variables etc, replacing "hrs" with "bps" and "HRS" with "BPS" (case sensitivity is important). 

    Then you can go on to the more service related changes, updating the UUID's, using indications instead of notifications for the main characteristic, and adding the second characteristic required by BPS. 

    Best regards
    Torbjørn

  • Hi Torbjørn,

    Many thanks for your response. Can you please clarify the following for me:

    1) Are you asking me to adopt the content of ble_hrs_c.c/.h and create similar functions for BPS Client module (i.e. ending up with two new files ble_bps_c.c/.h?

    2) If the answer to the above is "yes" then how should I treat the function static void on_hvx(ble_hrs_c_t * p_ble_hrs_c, const ble_evt_t * p_ble_evt) ? Do I need an equivalent for BPS Client module? Let me know how the new files I have created ble_bps_c.c/.h, main.c and sdk_config.h attached below...

    1581.sdk_config.h

    ble_bps_c.h

    /**
     * Copyright (c) 2014 - 2019, Nordic Semiconductor ASA
     *
     * All rights reserved.
     *
     * Redistribution and use in source and binary forms, with or without modification,
     * are permitted provided that the following conditions are met:
     *
     * 1. Redistributions of source code must retain the above copyright notice, this
     *    list of conditions and the following disclaimer.
     *
     * 2. Redistributions in binary form, except as embedded into a Nordic
     *    Semiconductor ASA integrated circuit in a product or a software update for
     *    such product, must reproduce the above copyright notice, this list of
     *    conditions and the following disclaimer in the documentation and/or other
     *    materials provided with the distribution.
     *
     * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
     *    contributors may be used to endorse or promote products derived from this
     *    software without specific prior written permission.
     *
     * 4. This software, with or without modification, must only be used with a
     *    Nordic Semiconductor ASA integrated circuit.
     *
     * 5. Any software provided in binary form under this license must not be reverse
     *    engineered, decompiled, modified and/or disassembled.
     *
     * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
     * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
     * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
     * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
     * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
     * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     *
     */
    /**
     * @brief BLE LED Button Service central and client application main file.
     *
     * This example can be a central for up to 8 peripherals.
     * The peripheral is called ble_app_blinky and can be found in the ble_peripheral
     * folder.
     */
    
    #include <stdint.h>
    #include <stdio.h>
    #include <string.h>
    #include "nordic_common.h"
    #include "nrf_sdh.h"
    #include "nrf_sdh_ble.h"
    #include "app_timer.h"
    #include "bsp_btn_ble.h"
    #include "ble.h"
    #include "ble_hci.h"
    #include "ble_advertising.h"
    #include "ble_conn_params.h"
    #include "ble_db_discovery.h"
    #include "ble_conn_state.h"
    #include "nrf_ble_gatt.h"
    #include "nrf_pwr_mgmt.h"
    #include "nrf_ble_scan.h"
    
    #include "nrf_log.h"
    #include "nrf_log_ctrl.h"
    #include "nrf_log_default_backends.h"
    
    #include "peer_manager.h"
    #include "peer_manager_handler.h"
    #include "fds.h"
    #include "nrf_fstorage.h"
    #include "ble_bps_c.h"
    //#include "ble_bas_c.h"
    
    
    
    
    #define APP_BLE_CONN_CFG_TAG      1                                     /**< Tag that refers to the BLE stack configuration that is set with @ref sd_ble_cfg_set. The default tag is @ref APP_BLE_CONN_CFG_TAG. */
    #define APP_BLE_OBSERVER_PRIO     3                                     /**< BLE observer priority of the application. There is no need to modify this value. */
    
    #define CENTRAL_SCANNING_LED      BSP_BOARD_LED_0
    #define CENTRAL_CONNECTED_LED     BSP_BOARD_LED_1
    #define LEDBUTTON_LED             BSP_BOARD_LED_2                       /**< LED to indicate a change of state of the Button characteristic on the peer. */
    
    #define LEDBUTTON_BUTTON          BSP_BUTTON_0                          /**< Button that writes to the LED characteristic of the peer. */
    #define BUTTON_DETECTION_DELAY    APP_TIMER_TICKS(50)                   /**< Delay from a GPIOTE event until a button is reported as pushed (in number of timer ticks). */
    
    #define SEC_PARAM_BOND              1                                   /**< Perform bonding. */
    #define SEC_PARAM_MITM              0                                   /**< Man In The Middle protection not required. */
    #define SEC_PARAM_LESC              1                                   /**< LE Secure Connections enabled. */
    #define SEC_PARAM_KEYPRESS          0                                   /**< Keypress notifications not enabled. */
    #define SEC_PARAM_IO_CAPABILITIES   BLE_GAP_IO_CAPS_NONE                /**< No I/O capabilities. */
    #define SEC_PARAM_OOB               0                                   /**< Out Of Band data not available. */
    #define SEC_PARAM_MIN_KEY_SIZE      7                                   /**< Minimum encryption key size in octets. */
    #define SEC_PARAM_MAX_KEY_SIZE      16                                  /**< Maximum encryption key size in octets. */
    
    BLE_BPS_C_DEF(m_bps_c);
    //BLE_BAS_C_DEF(m_bas_c);  
    NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
    BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
    NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
    NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
                   NRF_SDH_BLE_CENTRAL_LINK_COUNT,
                   NRF_BLE_GQ_QUEUE_SIZE);
    
    static char const m_target_periph_name[] = "A&D_";             /**< Name of the device to try to connect to. This name is searched for in the scanning report data. */
    
    /**@brief BPS UUID. */
    static ble_uuid_t const m_bps_uuid =
    {
        .uuid = BLE_UUID_BLOOD_PRESSURE_SERVICE,
        .type = BLE_UUID_TYPE_BLE
    };
    
    
    /**@brief Function for handling asserts in the SoftDevice.
     *
     * @details This function is called in case of an assert in the SoftDevice.
     *
     * @warning This handler is only an example and is not meant for the final product. You need to analyze
     *          how your product is supposed to react in case of an assert.
     * @warning On assert from the SoftDevice, the system can only recover on reset.
     *
     * @param[in] line_num     Line number of the failing assert call.
     * @param[in] p_file_name  File name of the failing assert call.
     */
    void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name)
    {
        app_error_handler(0xDEADBEEF, line_num, p_file_name);
    }
    
    
    /**@brief Function for handling the LED Button Service Client errors.
     *
     * @param[in]   nrf_error   Error code containing information about what went wrong.
     */
    static void lbs_error_handler(uint32_t nrf_error)
    {
        APP_ERROR_HANDLER(nrf_error);
    }
    
    
    
    /**@brief Function for the LEDs initialization.
     *
     * @details Initializes all LEDs used by the application.
     */
    static void leds_init(void)
    {
        bsp_board_init(BSP_INIT_LEDS);
    }
    
    
    static void scan_evt_handler(scan_evt_t const * p_scan_evt)
    {
        ret_code_t err_code;
    
        switch(p_scan_evt->scan_evt_id)
        {
            case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
            {
                err_code = p_scan_evt->params.connecting_err.err_code;
                APP_ERROR_CHECK(err_code);
            } break;
    
            case NRF_BLE_SCAN_EVT_CONNECTED:
             {
                ble_gap_evt_connected_t const * p_connected =
                                 p_scan_evt->params.connected.p_connected;
                 // Scan is automatically stopped by the connection.
                 NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
                          p_connected->peer_addr.addr[0],
                          p_connected->peer_addr.addr[1],
                          p_connected->peer_addr.addr[2],
                          p_connected->peer_addr.addr[3],
                          p_connected->peer_addr.addr[4],
                          p_connected->peer_addr.addr[5]
                            );
             } break;
    
            default:
                break;
        }
    }
    
    
    /**@brief Function for initializing the scanning and setting the filters.
     */
    static void scan_init(void)
    {
        ret_code_t          err_code;
        nrf_ble_scan_init_t init_scan;
    
        memset(&init_scan, 0, sizeof(init_scan));
    
        init_scan.connect_if_match = true;
        init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
    
        err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
        APP_ERROR_CHECK(err_code);
    
        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_NAME_FILTER, m_target_periph_name);
        APP_ERROR_CHECK(err_code);
    
        err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_NAME_FILTER, false);
        APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function for starting scanning. */
    static void scan_start(void)
    {
        ret_code_t ret;
    
        NRF_LOG_INFO("Start scanning for device name %s.", (uint32_t)m_target_periph_name);
        ret = nrf_ble_scan_start(&m_scan);
        APP_ERROR_CHECK(ret);
        // Turn on the LED to signal scanning.
        bsp_board_led_on(CENTRAL_SCANNING_LED);
    }
    
    
    
    /**@brief Function for handling BLE events.
     *
     * @param[in]   p_ble_evt   Bluetooth stack event.
     * @param[in]   p_context   Unused.
     */
    static void ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context)
    {
        ret_code_t err_code;
        static uint16_t start_handle = 1;
        static uint16_t last = 0;
    
        // For readability.
        ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
    
        //NRF_LOG_INFO("EVT ID: 0x%x ", p_ble_evt->header.evt_id);
    
        switch (p_ble_evt->header.evt_id)
        {
            // Upon connection, check which peripheral is connected, initiate DB
            // discovery, update LEDs status, and resume scanning, if necessary.
            case BLE_GAP_EVT_CONNECTED:
            {
                NRF_LOG_INFO("Connection 0x%x established, starting DB discovery.",
                             p_gap_evt->conn_handle);
    
                APP_ERROR_CHECK_BOOL(p_gap_evt->conn_handle < NRF_SDH_BLE_CENTRAL_LINK_COUNT);
    
                memset(&m_db_disc, 0, sizeof(m_db_disc));
                err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
    
                // Update LEDs status and check whether it is needed to look for more
                // peripherals to connect to.
                bsp_board_led_on(CENTRAL_CONNECTED_LED);
                if (ble_conn_state_central_conn_count() == NRF_SDH_BLE_CENTRAL_LINK_COUNT)
                {
                    bsp_board_led_off(CENTRAL_SCANNING_LED);
                }
                else
                {
                    // Resume scanning.
                    bsp_board_led_on(CENTRAL_SCANNING_LED);
                    scan_start();
                }
            } break; // BLE_GAP_EVT_CONNECTED
    
            // Upon disconnection, reset the connection handle of the peer that disconnected, update
            // the LEDs status and start scanning again.
            case BLE_GAP_EVT_DISCONNECTED:
            {
                NRF_LOG_INFO("Central link 0x%x disconnected (reason: 0x%x)",
                             p_gap_evt->conn_handle,
                             p_gap_evt->params.disconnected.reason);
    
                if (ble_conn_state_central_conn_count() == 0)
                {
                    err_code = app_button_disable();
                    APP_ERROR_CHECK(err_code);
    
                    // Turn off the LED that indicates the connection.
                    bsp_board_led_off(CENTRAL_CONNECTED_LED);
                }
    
                // Start scanning.
                scan_start();
    
                // Turn on the LED for indicating scanning.
                bsp_board_led_on(CENTRAL_SCANNING_LED);
    
                start_handle = 1;
                last = 0;
    
            } break;
    
            case BLE_GAP_EVT_TIMEOUT:
            {
                // Timeout for scanning is not specified, so only the connection requests can time out.
                if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
                {
                    NRF_LOG_DEBUG("Connection request timed out.");
                }
            } break;
    
            case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
            {
                NRF_LOG_DEBUG("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST.");
                // Accept parameters requested by peer.
                err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
                                            &p_gap_evt->params.conn_param_update_request.conn_params);
                APP_ERROR_CHECK(err_code);
            } break;
    
            case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
            {
                NRF_LOG_DEBUG("PHY update request.");
                ble_gap_phys_t const phys =
                {
                    .rx_phys = BLE_GAP_PHY_AUTO,
                    .tx_phys = BLE_GAP_PHY_AUTO,
                };
                err_code = sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
                APP_ERROR_CHECK(err_code);
            } break;
    
            case BLE_GATTC_EVT_TIMEOUT:
            {
                // Disconnect on GATT client timeout event.
                NRF_LOG_DEBUG("GATT client timeout.");
                err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
                                                 BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
                APP_ERROR_CHECK(err_code);
            } break;
    
            case BLE_GATTS_EVT_TIMEOUT:
            {
                // Disconnect on GATT server timeout event.
                NRF_LOG_DEBUG("GATT server timeout.");
                err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
                                                 BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
                APP_ERROR_CHECK(err_code);
            } break;
    
             /*case BLE_GAP_EVT_AUTH_STATUS:
                 NRF_LOG_INFO("BLE_GAP_EVT_AUTH_STATUS: status=0x%x bond=0x%x lv4: %d kdist_own:0x%x kdist_peer:0x%x",
                              p_ble_evt->evt.gap_evt.params.auth_status.auth_status,
                              p_ble_evt->evt.gap_evt.params.auth_status.bonded,
                              p_ble_evt->evt.gap_evt.params.auth_status.sm1_levels.lv4,
                              *((uint8_t *)&p_ble_evt->evt.gap_evt.params.auth_status.kdist_own),
                              *((uint8_t *)&p_ble_evt->evt.gap_evt.params.auth_status.kdist_peer));
                break;
    
              /*case BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP:
                    	NRF_LOG_INFO("Found service");
                            NRF_LOG_INFO("Last handle %x , start handle %x ", last, start_handle);
    
                if (p_ble_evt->evt.gattc_evt.gatt_status != BLE_GATT_STATUS_ATTERR_ATTRIBUTE_NOT_FOUND)
                {
                  last = p_ble_evt->evt.gattc_evt.params.prim_srvc_disc_rsp.count - 1;
                  start_handle = p_ble_evt->evt.gattc_evt.params.prim_srvc_disc_rsp.services[last].handle_range.end_handle + 1;
                  err_code = sd_ble_gattc_primary_services_discover(p_gap_evt->conn_handle, start_handle, NULL);
                  APP_ERROR_CHECK(err_code);
                }
                else
                {
                  NRF_LOG_INFO("Got BLE_GATT_STATUS_ATTERR_ATTRIBUTE_NOT_FOUND");  
                }*/
    
                                
                break;
    
            default:
                // No implementation needed.
                break;
        }
    }
    
    /**@brief Function for handling the Nordic UART Service Client errors.
     *
     * @param[in]   nrf_error   Error code containing information about what went wrong.
     */
    static void bps_error_handler(uint32_t nrf_error)
    {
        APP_ERROR_HANDLER(nrf_error);
    }
    
    #if ATTEMPT_1
    static void ble_bps_evt_handler(ble_bps_t * p_bps, ble_bps_evt_t const * ble_bps_evt)
    {
        ret_code_t err_code;
    
        NRF_LOG_INFO("BPS EVT ID:%d ", ble_bps_evt->evt_type);
        switch (ble_bps_evt->evt_type)
        {
            case BLE_BPS_EVT_DISCOVERY_COMPLETE:
                NRF_LOG_INFO("Discovery complete.");
                err_code = ble_bps_handles_assign(p_bps, ble_bps_evt->conn_handle);
                APP_ERROR_CHECK(err_code);
    
                // Initiate bonding.
                err_code = pm_conn_secure(ble_bps_evt->conn_handle, false);
                if (err_code != NRF_ERROR_BUSY)
                {
                    APP_ERROR_CHECK(err_code);
                }
    
                bps_enable_indication(p_bps);
                APP_ERROR_CHECK(err_code);
    
                NRF_LOG_INFO("Connected to device with BPS.");
                break;
        }
    }
    #endif //#if ATTEMPT_1
    
    /**@brief Heart Rate Collector Handler.
     */
    //static void hrs_c_evt_handler(ble_hrs_c_t * p_hrs_c, ble_hrs_c_evt_t * p_hrs_c_evt)
    static void bps_c_evt_handler(ble_bps_c_t * p_bps, ble_bps_c_evt_t const * ble_bps_evt)
    {
        ret_code_t err_code;
    
        switch (ble_bps_evt->evt_type)
        {
            case BLE_BPS_C_EVT_DISCOVERY_COMPLETE:
            {
                NRF_LOG_DEBUG("Heart rate service discovered.");
    
                err_code = ble_bps_c_handles_assign(p_bps,
                                                    ble_bps_evt->conn_handle,
                                                    &ble_bps_evt->params.peer_db);
                APP_ERROR_CHECK(err_code);
    
                // Initiate bonding.
                err_code = pm_conn_secure(ble_bps_evt->conn_handle, false);
                if (err_code != NRF_ERROR_BUSY)
                {
                    APP_ERROR_CHECK(err_code);
                }
    
                // Heart rate service discovered. Enable indication.
                err_code = ble_bps_c_meas_indication_enable(p_bps);
                APP_ERROR_CHECK(err_code);
            } break;
    
            case BLE_BPS_C_EVT_MEAS_INDICATION:
            {
                NRF_LOG_INFO("BP Meas example %f", ble_bps_evt->params.meas.blood_pressure_systolic);
                
            } break;
    
            default:
                break;
        }
    }
    
    
    static void bps_c_init(void)
    {
        ret_code_t       err_code;
        ble_bps_c_init_t   init;
    
        init.evt_handler   = bps_c_evt_handler;
        init.error_handler = bps_error_handler;
        init.p_gatt_queue  = &m_ble_gatt_queue;
    
        err_code = ble_bps_c_init(&m_bps_c, &init);
        APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function for initializing the BLE stack.
     *
     * @details Initializes the SoftDevice and the BLE event interrupts.
     */
    static void ble_stack_init(void)
    {
        ret_code_t err_code;
    
        err_code = nrf_sdh_enable_request();
        APP_ERROR_CHECK(err_code);
    
        // Configure the BLE stack using the default settings.
        // Fetch the start address of the application RAM.
        uint32_t ram_start = 0;
        err_code = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &ram_start);
        APP_ERROR_CHECK(err_code);
    
        // Enable BLE stack.
        err_code = nrf_sdh_ble_enable(&ram_start);
        APP_ERROR_CHECK(err_code);
    
        // Register a handler for BLE events.
        NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, ble_evt_handler, NULL);
    }
    
    /**@brief Function for handling Peer Manager events.
     *
     * @param[in] p_evt  Peer Manager event.
     */
    static void pm_evt_handler(pm_evt_t const * p_evt)
    {
        pm_handler_on_pm_evt(p_evt);
        pm_handler_flash_clean(p_evt);
    
        switch (p_evt->evt_id)
        {
            case PM_EVT_PEERS_DELETE_SUCCEEDED:
                // Bonds are deleted. Start scanning.
                scan_start();
                break;
    
            default:
                break;
        }
    }
    
    /**@brief Function for the Peer Manager initialization.
     */
    static void peer_manager_init(void)
    {
        ble_gap_sec_params_t sec_param;
        ret_code_t err_code;
    
        err_code = pm_init();
        APP_ERROR_CHECK(err_code);
    
        memset(&sec_param, 0, sizeof(ble_gap_sec_params_t));
    
        // Security parameters to be used for all security procedures.
        sec_param.bond           = SEC_PARAM_BOND;
        sec_param.mitm           = SEC_PARAM_MITM;
        sec_param.lesc           = SEC_PARAM_LESC;
        sec_param.keypress       = SEC_PARAM_KEYPRESS;
        sec_param.io_caps        = SEC_PARAM_IO_CAPABILITIES;
        sec_param.oob            = SEC_PARAM_OOB;
        sec_param.min_key_size   = SEC_PARAM_MIN_KEY_SIZE;
        sec_param.max_key_size   = SEC_PARAM_MAX_KEY_SIZE;
        sec_param.kdist_own.enc  = 1;
        sec_param.kdist_own.id   = 1;
        sec_param.kdist_peer.enc = 1;
        sec_param.kdist_peer.id  = 1;
    
        err_code = pm_sec_params_set(&sec_param);
        APP_ERROR_CHECK(err_code);
    
        err_code = pm_register(pm_evt_handler);
        APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function for handling events from the button handler module.
     *
     * @param[in] pin_no        The pin that the event applies to.
     * @param[in] button_action The button action (press or release).
     */
    static void button_event_handler(uint8_t pin_no, uint8_t button_action)
    {
        ret_code_t err_code;
    
        switch (pin_no)
        {
            case LEDBUTTON_BUTTON:
                //err_code = led_status_send_to_all(button_action);
                if (err_code == NRF_SUCCESS)
                {
                    NRF_LOG_INFO("LBS write LED state %d", button_action);
                }
                break;
    
            default:
                APP_ERROR_HANDLER(pin_no);
                break;
        }
    }
    
    
    /**@brief Function for initializing the button handler module.
     */
    static void buttons_init(void)
    {
        ret_code_t err_code;
    
       // The array must be static because a pointer to it is saved in the button handler module.
        static app_button_cfg_t buttons[] =
        {
            {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
        };
    
        err_code = app_button_init(buttons, ARRAY_SIZE(buttons), BUTTON_DETECTION_DELAY);
        APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function for handling database discovery events.
     *
     * @details This function is a callback function to handle events from the database discovery module.
     *          Depending on the UUIDs that are discovered, this function forwards the events
     *          to their respective services.
     *
     * @param[in] p_event  Pointer to the database discovery event.
     */
    static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
    {
        NRF_LOG_INFO("call to ble_bps_on_db_disc_evt for instance 0x%x and handle 0x%x!",
                      p_evt->params.p_db_instance,
                      p_evt->conn_handle);
    
        NRF_LOG_INFO("APP FOUND %d CHARACTERISTICS.", p_evt->params.discovered_db.char_count);
    
        ble_bps_on_db_disc_evt(&m_bps_c, p_evt);
    }
    
    #if BATT
    /**@brief Battery level Collector Handler.
     */
    static void bas_c_evt_handler(ble_bas_c_t * p_bas_c, ble_bas_c_evt_t * p_bas_c_evt)
    {
        ret_code_t err_code;
    
        switch (p_bas_c_evt->evt_type)
        {
            case BLE_BAS_C_EVT_DISCOVERY_COMPLETE:
            {
                err_code = ble_bas_c_handles_assign(p_bas_c,
                                                    p_bas_c_evt->conn_handle,
                                                    &p_bas_c_evt->params.bas_db);
                APP_ERROR_CHECK(err_code);
    
                // Battery service discovered. Enable notification of Battery Level.
                NRF_LOG_DEBUG("Battery Service discovered. Reading battery level.");
    
                err_code = ble_bas_c_bl_read(p_bas_c);
                APP_ERROR_CHECK(err_code);
    
                NRF_LOG_DEBUG("Enabling Battery Level Notification.");
                err_code = ble_bas_c_bl_notif_enable(p_bas_c);
                APP_ERROR_CHECK(err_code);
    
            } break;
    
            case BLE_BAS_C_EVT_BATT_NOTIFICATION:
                NRF_LOG_INFO("Battery Level received %d %%.", p_bas_c_evt->params.battery_level);
                break;
    
            case BLE_BAS_C_EVT_BATT_READ_RESP:
                NRF_LOG_INFO("Battery Level Read as %d %%.", p_bas_c_evt->params.battery_level);
                break;
    
            default:
                break;
        }
    }
    #endif //#if BAT
    /**@brief Function for handling the Heart Rate Service Client and Battery Service Client errors.
     *
     * @param[in]   nrf_error   Error code containing information about what went wrong.
     */
    static void service_error_handler(uint32_t nrf_error)
    {
        APP_ERROR_HANDLER(nrf_error);
    }
    
    #if BAT
    /**
     * @brief Battery level collector initialization.
     */
    static void bas_c_init(void)
    {
        ble_bas_c_init_t bas_c_init_obj;
    
        bas_c_init_obj.evt_handler   = bas_c_evt_handler;
        bas_c_init_obj.error_handler = service_error_handler;
        bas_c_init_obj.p_gatt_queue  = &m_ble_gatt_queue;
    
        ret_code_t err_code = ble_bas_c_init(&m_bas_c, &bas_c_init_obj);
        APP_ERROR_CHECK(err_code);
    }
    #endif //#if BAT
    
    /** @brief Database discovery initialization.
     */
    static void db_discovery_init(void)
    {
        ble_db_discovery_init_t db_init;
    
        memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
    
        db_init.evt_handler  = db_disc_handler;
        db_init.p_gatt_queue = &m_ble_gatt_queue;
    
        ret_code_t err_code = ble_db_discovery_init(&db_init);
        APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function for initializing power management.
     */
    static void power_management_init(void)
    {
        ret_code_t err_code;
        err_code = nrf_pwr_mgmt_init();
        APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function for handling the idle state (main loop).
     *
     * @details This function handles any pending log operations, then sleeps until the next event occurs.
     */
    static void idle_state_handle(void)
    {
        if (NRF_LOG_PROCESS() == false)
        {
            nrf_pwr_mgmt_run();
        }
    }
    
    
    /** @brief Function for initializing the log module.
     */
    static void log_init(void)
    {
        ret_code_t err_code = NRF_LOG_INIT(NULL);
        APP_ERROR_CHECK(err_code);
    
        NRF_LOG_DEFAULT_BACKENDS_INIT();
    }
    
    
    /** @brief Function for initializing the timer.
     */
    static void timer_init(void)
    {
        ret_code_t err_code = app_timer_init();
        APP_ERROR_CHECK(err_code);
    }
    
    /**@brief GATT module event handler.
     */
    static void gatt_evt_handler(nrf_ble_gatt_t * p_gatt, nrf_ble_gatt_evt_t const * p_evt)
    {
        switch (p_evt->evt_id)
        {
            case NRF_BLE_GATT_EVT_ATT_MTU_UPDATED:
            {
                NRF_LOG_INFO("GATT ATT MTU on connection 0x%x changed to %d.",
                             p_evt->conn_handle,
                             p_evt->params.att_mtu_effective);
            } break;
    
            case NRF_BLE_GATT_EVT_DATA_LENGTH_UPDATED:
            {
                NRF_LOG_INFO("Data length for connection 0x%x updated to %d.",
                             p_evt->conn_handle,
                             p_evt->params.data_length);
            } break;
    
            default:
                break;
        }
    }
    
    /**@brief Function for initializing the GATT module.
     */
    static void gatt_init(void)
    {
        ret_code_t err_code = nrf_ble_gatt_init(&m_gatt, gatt_evt_handler);
        APP_ERROR_CHECK(err_code);
    }
    
    
    int main(void)
    {
        // Initialize.
        log_init();
        timer_init();
        leds_init();
        buttons_init();
        db_discovery_init();
        power_management_init();
        ble_stack_init();
        gatt_init();
        bps_c_init();
        ble_conn_state_init();
        //bas_c_init();
        scan_init();
        peer_manager_init();
    
    
        // Start execution.
        NRF_LOG_INFO("C-Detect-LIKE example started.");
        scan_start();
    
        for (;;)
        {
            idle_state_handle();
        }
    }
    
    /**
     * Copyright (c) 2012 - 2019, Nordic Semiconductor ASA
     *
     * All rights reserved.
     *
     * Redistribution and use in source and binary forms, with or without modification,
     * are permitted provided that the following conditions are met:
     *
     * 1. Redistributions of source code must retain the above copyright notice, this
     *    list of conditions and the following disclaimer.
     *
     * 2. Redistributions in binary form, except as embedded into a Nordic
     *    Semiconductor ASA integrated circuit in a product or a software update for
     *    such product, must reproduce the above copyright notice, this list of
     *    conditions and the following disclaimer in the documentation and/or other
     *    materials provided with the distribution.
     *
     * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
     *    contributors may be used to endorse or promote products derived from this
     *    software without specific prior written permission.
     *
     * 4. This software, with or without modification, must only be used with a
     *    Nordic Semiconductor ASA integrated circuit.
     *
     * 5. Any software provided in binary form under this license must not be reverse
     *    engineered, decompiled, modified and/or disassembled.
     *
     * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
     * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
     * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
     * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
     * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
     * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     *
     */
    /**@cond To Make Doxygen skip documentation generation for this file.
     * @{
     */
    #include "sdk_common.h"
    //#if NRF_MODULE_ENABLED(BLE_BPS_C)
    #include "ble_bps_c.h"
    #include "ble_db_discovery.h"
    #include "ble_types.h"
    #include "ble_gattc.h"
    
    #define NRF_LOG_MODULE_NAME ble_bps_c
    #include "nrf_log.h"
    NRF_LOG_MODULE_REGISTER();
    
    #define HRM_FLAG_MASK_HR_16BIT  (0x01 << 0)           /**< Bit mask used to extract the type of heart rate value. This is used to find if the received heart rate is a 16 bit value or an 8 bit value. */
    #define HRM_FLAG_MASK_HR_RR_INT (0x01 << 4)           /**< Bit mask used to extract the presence of RR_INTERVALS. This is used to find if the received measurement includes RR_INTERVALS. */
    
    
    /**@brief Function for interception of the errors of GATTC and the BLE GATT Queue.
     *
     * @param[in] nrf_error   Error code.
     * @param[in] p_ctx       Parameter from the event handler.
     * @param[in] conn_handle Connection handle.
     */
    static void gatt_error_handler(uint32_t   nrf_error,
                                   void     * p_ctx,
                                   uint16_t   conn_handle)
    {
        ble_bps_c_t * p_ble_bps_c = (ble_bps_c_t *)p_ctx;
    
        NRF_LOG_DEBUG("A GATT Client error has occurred on conn_handle: 0X%X", conn_handle);
    
        if (p_ble_bps_c->error_handler != NULL)
        {
            p_ble_bps_c->error_handler(nrf_error);
        }
    }
    
    #if IS_NEEDED
    /**@brief     Function for handling Handle Value Notification received from the SoftDevice.
     *
     * @details   This function uses the Handle Value Notification received from the SoftDevice
     *            and checks whether it is a notification of the heart rate measurement from the peer. If
     *            it is, this function decodes the heart rate measurement and sends it to the
     *            application.
     *
     * @param[in] p_ble_bps_c Pointer to the Heart Rate Client structure.
     * @param[in] p_ble_evt   Pointer to the BLE event received.
     */
    static void on_hvx(ble_bps_c_t * p_ble_bps_c, const ble_evt_t * p_ble_evt)
    {
        // Check if the event is on the link for this instance.
        if (p_ble_bps_c->conn_handle != p_ble_evt->evt.gattc_evt.conn_handle)
        {
            NRF_LOG_DEBUG("Received HVX on link 0x%x, not associated to this instance. Ignore.",
                          p_ble_evt->evt.gattc_evt.conn_handle);
            return;
        }
    
        NRF_LOG_DEBUG("Received HVX on link 0x%x, hrm_handle 0x%x",
        p_ble_evt->evt.gattc_evt.params.hvx.handle,
        p_ble_bps_c->peer_bps_db.meas_handle);
    
        // Check if this is a heart rate notification.
        if (p_ble_evt->evt.gattc_evt.params.hvx.handle == p_ble_bps_c->peer_bps_db.meas_handle)
        {
            ble_bps_c_evt_t ble_bps_c_evt;
            uint32_t        index = 0;
    
            ble_bps_c_evt.evt_type                    = BLE_HRS_C_EVT_HRM_NOTIFICATION;
            ble_bps_c_evt.conn_handle                 = p_ble_bps_c->conn_handle;
            ble_bps_c_evt.params.meas.rr_intervals_cnt = 0;
    
            if (!(p_ble_evt->evt.gattc_evt.params.hvx.data[index++] & HRM_FLAG_MASK_HR_16BIT))
            {
                // 8-bit heart rate value received.
                ble_bps_c_evt.params.meas.hr_value = p_ble_evt->evt.gattc_evt.params.hvx.data[index++];  //lint !e415 suppress Lint Warning 415: Likely access out of bond
            }
            else
            {
                // 16-bit heart rate value received.
                ble_bps_c_evt.params.meas.hr_value =
                    uint16_decode(&(p_ble_evt->evt.gattc_evt.params.hvx.data[index]));
                index += sizeof(uint16_t);
            }
    
            if ((p_ble_evt->evt.gattc_evt.params.hvx.data[0] & HRM_FLAG_MASK_HR_RR_INT))
            {
                uint32_t i;
                /*lint --e{415} --e{416} --e{662} --e{661} -save suppress Warning 415: possible access out of bond */
                for (i = 0; i < BLE_HRS_C_RR_INTERVALS_MAX_CNT; i ++)
                {
                    if (index >= p_ble_evt->evt.gattc_evt.params.hvx.len)
                    {
                        break;
                    }
                    ble_bps_c_evt.params.meas.rr_intervals[i] =
                        uint16_decode(&(p_ble_evt->evt.gattc_evt.params.hvx.data[index]));
                    index += sizeof(uint16_t);
                }
                /*lint -restore*/
                ble_bps_c_evt.params.meas.rr_intervals_cnt = (uint8_t)i;
            }
            p_ble_bps_c->evt_handler(p_ble_bps_c, &ble_bps_c_evt);
        }
    }
    #endif //#if IS_NEEDED
    
    /**@brief     Function for handling Disconnected event received from the SoftDevice.
     *
     * @details   This function checks whether the disconnect event is happening on the link
     *            associated with the current instance of the module. If the event is happening, the function sets the instance's
     *            conn_handle to invalid.
     *
     * @param[in] p_ble_bps_c Pointer to the Heart Rate Client structure.
     * @param[in] p_ble_evt   Pointer to the BLE event received.
     */
    static void on_disconnected(ble_bps_c_t * p_ble_bps_c, const ble_evt_t * p_ble_evt)
    {
        if (p_ble_bps_c->conn_handle == p_ble_evt->evt.gap_evt.conn_handle)
        {
            p_ble_bps_c->conn_handle                 = BLE_CONN_HANDLE_INVALID;
            p_ble_bps_c->peer_bps_db.meas_cccd_handle = BLE_GATT_HANDLE_INVALID;
            p_ble_bps_c->peer_bps_db.feat_cccd_handle = BLE_GATT_HANDLE_INVALID;
            p_ble_bps_c->peer_bps_db.meas_handle      = BLE_GATT_HANDLE_INVALID;
            p_ble_bps_c->peer_bps_db.feat_handle      = BLE_GATT_HANDLE_INVALID;
        }
    }
    
    
    void ble_bps_on_db_disc_evt(ble_bps_c_t * p_ble_bps_c, const ble_db_discovery_evt_t * p_evt)
    {
        // Check if the 3t Rate Service was discovered.
        if (p_evt->evt_type == BLE_DB_DISCOVERY_COMPLETE &&
            p_evt->params.discovered_db.srv_uuid.uuid == BLE_UUID_BLOOD_PRESSURE_SERVICE &&
            p_evt->params.discovered_db.srv_uuid.type == BLE_UUID_TYPE_BLE)
        {
            // Find the CCCD Handle of the Heart Rate Measurement characteristic.
            uint32_t i;
    
            ble_bps_c_evt_t evt;
    
            evt.evt_type    = BLE_BPS_C_EVT_DISCOVERY_COMPLETE;
            evt.conn_handle = p_evt->conn_handle;
    
            for (i = 0; i < p_evt->params.discovered_db.char_count; i++)
            {
                if (p_evt->params.discovered_db.charateristics[i].characteristic.uuid.uuid ==
                    BLE_UUID_BLOOD_PRESSURE_MEASUREMENT_CHAR)
                {
                    // Found Heart Rate characteristic. Store CCCD handle and break.
                    evt.params.peer_db.meas_cccd_handle =
                        p_evt->params.discovered_db.charateristics[i].cccd_handle;
                    evt.params.peer_db.meas_cccd_handle =
                        p_evt->params.discovered_db.charateristics[i].characteristic.handle_value;
                    break;
                }
    
                if (p_evt->params.discovered_db.charateristics[i].characteristic.uuid.uuid ==
                    BLE_UUID_BLOOD_PRESSURE_FEATURE_CHAR)
                {
                    //TODO
                    break;
                }
            }
    
            NRF_LOG_DEBUG("Heart Rate Service discovered at peer.");
            //If the instance has been assigned prior to db_discovery, assign the db_handles.
            if (p_ble_bps_c->conn_handle != BLE_CONN_HANDLE_INVALID)
            {
                if ((p_ble_bps_c->peer_bps_db.meas_cccd_handle == BLE_GATT_HANDLE_INVALID)&&
                    (p_ble_bps_c->peer_bps_db.meas_handle == BLE_GATT_HANDLE_INVALID)&&
                    (p_ble_bps_c->peer_bps_db.feat_cccd_handle == BLE_GATT_HANDLE_INVALID)&&
                    (p_ble_bps_c->peer_bps_db.feat_handle == BLE_GATT_HANDLE_INVALID))
                {
                    p_ble_bps_c->peer_bps_db = evt.params.peer_db;
                }
            }
    
    
            p_ble_bps_c->evt_handler(p_ble_bps_c, &evt);
        }
    }
    
    
    uint32_t ble_bps_c_init(ble_bps_c_t * p_ble_bps_c, ble_bps_c_init_t * p_ble_bps_c_init)
    {
        VERIFY_PARAM_NOT_NULL(p_ble_bps_c);
        VERIFY_PARAM_NOT_NULL(p_ble_bps_c_init);
    
        ble_uuid_t bps_c_uuid;
    
        bps_c_uuid.type = BLE_UUID_TYPE_BLE;
        bps_c_uuid.uuid = BLE_UUID_BLOOD_PRESSURE_SERVICE;
    
        p_ble_bps_c->evt_handler                    = p_ble_bps_c_init->evt_handler;
        p_ble_bps_c->error_handler                  = p_ble_bps_c_init->error_handler;
        p_ble_bps_c->p_gatt_queue                   = p_ble_bps_c_init->p_gatt_queue;
        p_ble_bps_c->conn_handle                    = BLE_CONN_HANDLE_INVALID;
        p_ble_bps_c->peer_bps_db.meas_cccd_handle   = BLE_GATT_HANDLE_INVALID;
        p_ble_bps_c->peer_bps_db.feat_cccd_handle   = BLE_GATT_HANDLE_INVALID;
        p_ble_bps_c->peer_bps_db.meas_handle        = BLE_GATT_HANDLE_INVALID;
        p_ble_bps_c->peer_bps_db.feat_handle        = BLE_GATT_HANDLE_INVALID;
    
        return ble_db_discovery_evt_register(&bps_c_uuid);
    }
    
    void ble_bps_c_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_context)
    {
        ble_bps_c_t * p_ble_bps_c = (ble_bps_c_t *)p_context;
    
        if ((p_ble_bps_c == NULL) || (p_ble_evt == NULL))
        {
            return;
        }
    
        switch (p_ble_evt->header.evt_id)
        {
            case BLE_GATTC_EVT_HVX:
                //on_hvx(p_ble_bps_c, p_ble_evt);
                break;
    
            case BLE_GAP_EVT_DISCONNECTED:
                on_disconnected(p_ble_bps_c, p_ble_evt);
                break;
    
            default:
                break;
        }
    }
    
    
    /**@brief Function for creating a message for writing to the CCCD.
     */
    static uint32_t cccd_configure(ble_bps_c_t * p_ble_bps_c, bool enable)
    {
        NRF_LOG_DEBUG("Configuring CCCD. CCCD Handle = %d, Connection Handle = %d",
                      p_ble_bps_c->peer_bps_db.meas_cccd_handle,
                      p_ble_bps_c->conn_handle);
    
        nrf_ble_gq_req_t bps_c_req;
        uint8_t          cccd[BLE_CCCD_VALUE_LEN];
        uint16_t         cccd_val = enable ? BLE_GATT_HVX_INDICATION : 0;
    
        cccd[0] = LSB_16(cccd_val);
        cccd[1] = MSB_16(cccd_val);
    
        memset(&bps_c_req, 0, sizeof(bps_c_req));
    
        bps_c_req.type                        = NRF_BLE_GQ_REQ_GATTC_WRITE;
        bps_c_req.error_handler.cb            = gatt_error_handler;
        bps_c_req.error_handler.p_ctx         = p_ble_bps_c;
        bps_c_req.params.gattc_write.handle   = p_ble_bps_c->peer_bps_db.meas_cccd_handle;
        bps_c_req.params.gattc_write.len      = BLE_CCCD_VALUE_LEN;
        bps_c_req.params.gattc_write.p_value  = cccd;
        bps_c_req.params.gattc_write.write_op = BLE_GATT_OP_WRITE_REQ;
    
        return nrf_ble_gq_item_add(p_ble_bps_c->p_gatt_queue, &bps_c_req, p_ble_bps_c->conn_handle);
    }
    
    
    uint32_t ble_bps_c_meas_indication_enable(ble_bps_c_t * p_ble_bps_c)
    {
        VERIFY_PARAM_NOT_NULL(p_ble_bps_c);
    
        return cccd_configure(p_ble_bps_c, true);
    }
    
    
    uint32_t ble_bps_c_handles_assign(ble_bps_c_t    * p_ble_bps_c,
                                      uint16_t         conn_handle,
                                      const bps_c_db_t * p_peer_bps_handles)
    {
        VERIFY_PARAM_NOT_NULL(p_ble_bps_c);
    
        p_ble_bps_c->conn_handle = conn_handle;
        if (p_peer_bps_handles != NULL)
        {
            p_ble_bps_c->peer_bps_db = *p_peer_bps_handles;
        }
    
        return nrf_ble_gq_conn_handle_register(p_ble_bps_c->p_gatt_queue, conn_handle);
    }
    /** @}
     *  @endcond
     */
    //#endif // NRF_MODULE_ENABLED(BLE_HRS_C)
    

    3) Regarding the measurement structure, should I replace the ble_hrm_t structure with the ble_bps_meas_t (found in the ..\components\ble\ble_services\ble_bps\ble_bps.hble_bps.h)?

    4) Could you elaborate a bit more on your following comment "Then you have a second Blood Pressure Feature characteristic which only supports read, which means you don't need to worry about writing to the CCCD etc, but need to implement a function to read it out instead."  and provide more hints, example perhaps I should follow?

    5) Are you basically suggesting that I could have started my initial attempt using the example project "ble_app_hrs_c_pca10056_s140" instead of me using the "multilink_central_pca10056_s140" project?

    6) Lastly, you are mentioning "Blood Pressure Measurement characteristic" and "Heart Rate Measurement characteristic" and "Blood Pressure Feature characteristic" but to my understanding, I am planning to implement a Central application which should connect to the following:

    Blood Pressure Service (0x1810) which has two characteristics 1) Blood Pressure Measurement (0x2A35) and 2) Blood Pressure Feature (0x2A49). Is my understanding correct?

    Regards

    George

  • Hi George

    gliako said:
    1) Are you asking me to adopt the content of ble_hrs_c.c/.h and create similar functions for BPS Client module (i.e. ending up with two new files ble_bps_c.c/.h?

    Yes. You can copy these two files, rename them to ble_bps_c.c/h, and then proceed to alter the implementation like described earlier. 

    gliako said:
    2) If the answer to the above is "yes" then how should I treat the function static void on_hvx(ble_hrs_c_t * p_ble_hrs_c, const ble_evt_t * p_ble_evt) ? Do I need an equivalent for BPS Client module?

    Yes. This function is needed if you have any characteristics that support notifications or indications (HVX confusingly means Handle Value Notification/Indication).

    Like I mentioned earlier the main characteristic in the blood pressure service is quite similar to the one in the heart rate service, the main difference being that it uses indications rather than notifications. 

    gliako said:
    3) Regarding the measurement structure, should I replace the ble_hrm_t structure with the ble_bps_meas_t (found in the ..\components\ble\ble_services\ble_bps\ble_bps.hble_bps.h)?

    This makes sense, yes. In this case you can look at how the data is written to the characteristic in the ble_bps.c module, and try to replicate this on the client side by modifying the code used to read out the ble_hrm_t data. 

    You can then store the data in the same struct, no need to reimplement this from scratch. 

    gliako said:
    4) Could you elaborate a bit more on your following comment "Then you have a second Blood Pressure Feature characteristic which only supports read, which means you don't need to worry about writing to the CCCD etc, but need to implement a function to read it out instead."  and provide more hints, example perhaps I should follow?

    One difference between BPS and HRS is that the heart rate service only needs one characteristic, while the blood pressure service has two characteristics. The first one is very similar to the one in the heart rate service, in that it allows the server side to send updates with sensor values at regular intervals, but there is also one more characteristic which supports read only. This means that you have to initiate a read from the client side, the server can not send updates automatically using notifications or indications. 

    For an example you can look at how the Battery Level characteristic is handled in the ble_bas_c.h implementation. This characteristic supports read as well, and there is a function called ble_bas_c_bl_read(ble_bas_c_t * p_ble_bas_c) which allows you to read this characteristic when needed on the client side. 
    You should be able to implement the second characteristic in the blood pressure service in a similar way. 

    gliako said:
    5) Are you basically suggesting that I could have started my initial attempt using the example project "ble_app_hrs_c_pca10056_s140" instead of me using the "multilink_central_pca10056_s140" project?

    I think that would make more sense, yes. The multilink example is more about showing how to connect to multiple devices at the same time, which is not really what you are trying to do if I understand you correctly?

    The HRS client example should be a closer match, since it is essentially a very similar type of application (you're just replacing one medical style sensor with another). 

    gliako said:

    6) Lastly, you are mentioning "Blood Pressure Measurement characteristic" and "Heart Rate Measurement characteristic" and "Blood Pressure Feature characteristic" but to my understanding, I am planning to implement a Central application which should connect to the following:

    Blood Pressure Service (0x1810) which has two characteristics 1) Blood Pressure Measurement (0x2A35) and 2) Blood Pressure Feature (0x2A49). Is my understanding correct?

    Correct, you need to implement the Blood Pressure service, which contains the Blood Pressure Measurement and Blood Pressure Feature characteristics. 

    I guess the point I was trying to make with the Heart Rate Measurement characteristic is that you can use the client code for this characteristic as the basis for the Blood Pressure Measurement characteristic, since these two characteristics work quite similarly. 

    The Blood Pressure Feature characteristic doesn't have a direct equivalent in the Heart Rate service, but as mentioned above you can have a look at the Battery Level characteristic in the battery service instead.

    Best regards
    Torbjørn

  • HI Torbjørn,

    Many thanks again for the detailed answers.

    I have adopted all your suggestions and soon I will be sharing with you logs to show you my current status. Perhaps I will also share the new versions of the files involved. I believe that I still have an issue with the identification of the characteristics. But I have managed to sort out the issue with the "disconnection with reason 0x13" I was experiencing.

    Regards

    George

  • Hi Torbjørn,

    It looks like I got it working, thank you very much! I can see all the services and characteristics I have configured. Please check the latest files attached to see if I have followed your instruction correctly.

    /**
     * Copyright (c) 2014 - 2019, Nordic Semiconductor ASA
     *
     * All rights reserved.
     *
     * Redistribution and use in source and binary forms, with or without modification,
     * are permitted provided that the following conditions are met:
     *
     * 1. Redistributions of source code must retain the above copyright notice, this
     *    list of conditions and the following disclaimer.
     *
     * 2. Redistributions in binary form, except as embedded into a Nordic
     *    Semiconductor ASA integrated circuit in a product or a software update for
     *    such product, must reproduce the above copyright notice, this list of
     *    conditions and the following disclaimer in the documentation and/or other
     *    materials provided with the distribution.
     *
     * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
     *    contributors may be used to endorse or promote products derived from this
     *    software without specific prior written permission.
     *
     * 4. This software, with or without modification, must only be used with a
     *    Nordic Semiconductor ASA integrated circuit.
     *
     * 5. Any software provided in binary form under this license must not be reverse
     *    engineered, decompiled, modified and/or disassembled.
     *
     * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
     * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
     * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
     * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
     * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
     * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     *
     */
    /**
     * @brief BLE LED Button Service central and client application main file.
     *
     * This example can be a central for up to 8 peripherals.
     * The peripheral is called ble_app_blinky and can be found in the ble_peripheral
     * folder.
     */
    
    #include <stdint.h>
    #include <stdio.h>
    #include <string.h>
    #include "nordic_common.h"
    #include "nrf_sdh.h"
    #include "nrf_sdh_ble.h"
    #include "app_timer.h"
    #include "bsp_btn_ble.h"
    #include "ble.h"
    #include "ble_hci.h"
    #include "ble_advertising.h"
    #include "ble_conn_params.h"
    #include "ble_db_discovery.h"
    #include "ble_conn_state.h"
    #include "nrf_ble_gatt.h"
    #include "nrf_pwr_mgmt.h"
    #include "nrf_ble_scan.h"
    
    #include "nrf_log.h"
    #include "nrf_log_ctrl.h"
    #include "nrf_log_default_backends.h"
    
    #include "peer_manager.h"
    #include "peer_manager_handler.h"
    #include "fds.h"
    #include "nrf_fstorage.h"
    #include "ble_bps_c.h"
    #include "ble_bas_c.h"
    
    
    
    
    #define APP_BLE_CONN_CFG_TAG      1                                     /**< Tag that refers to the BLE stack configuration that is set with @ref sd_ble_cfg_set. The default tag is @ref APP_BLE_CONN_CFG_TAG. */
    #define APP_BLE_OBSERVER_PRIO     3                                     /**< BLE observer priority of the application. There is no need to modify this value. */
    
    #define CENTRAL_SCANNING_LED      BSP_BOARD_LED_0
    #define CENTRAL_CONNECTED_LED     BSP_BOARD_LED_1
    #define LEDBUTTON_LED             BSP_BOARD_LED_2                       /**< LED to indicate a change of state of the Button characteristic on the peer. */
    
    #define LEDBUTTON_BUTTON          BSP_BUTTON_0                          /**< Button that writes to the LED characteristic of the peer. */
    #define BUTTON_DETECTION_DELAY    APP_TIMER_TICKS(50)                   /**< Delay from a GPIOTE event until a button is reported as pushed (in number of timer ticks). */
    
    #define SEC_PARAM_BOND              1                                   /**< Perform bonding. */
    #define SEC_PARAM_MITM              0                                   /**< Man In The Middle protection not required. */
    #define SEC_PARAM_LESC              1                                   /**< LE Secure Connections enabled. */
    #define SEC_PARAM_KEYPRESS          0                                   /**< Keypress notifications not enabled. */
    #define SEC_PARAM_IO_CAPABILITIES   BLE_GAP_IO_CAPS_NONE                /**< No I/O capabilities. */
    #define SEC_PARAM_OOB               0                                   /**< Out Of Band data not available. */
    #define SEC_PARAM_MIN_KEY_SIZE      7                                   /**< Minimum encryption key size in octets. */
    #define SEC_PARAM_MAX_KEY_SIZE      16                                  /**< Maximum encryption key size in octets. */
    
    BLE_BPS_C_DEF(m_bps_c);
    BLE_BAS_C_DEF(m_bas_c);  
    NRF_BLE_GATT_DEF(m_gatt);                                               /**< GATT module instance. */
    BLE_DB_DISCOVERY_DEF(m_db_disc);                                        /**< Database discovery module instance. */
    NRF_BLE_SCAN_DEF(m_scan);                                               /**< Scanning Module instance. */
    NRF_BLE_GQ_DEF(m_ble_gatt_queue,                                        /**< BLE GATT Queue instance. */
                   NRF_SDH_BLE_CENTRAL_LINK_COUNT,
                   NRF_BLE_GQ_QUEUE_SIZE);
    
    static char const m_target_periph_name[] = "A&D_";             /**< Name of the device to try to connect to. This name is searched for in the scanning report data. */
    
    /**@brief BPS UUID. */
    static ble_uuid_t const m_bps_uuid =
    {
        .uuid = BLE_UUID_BLOOD_PRESSURE_SERVICE,
        .type = BLE_UUID_TYPE_BLE
    };
    
    
    /**@brief Function for handling asserts in the SoftDevice.
     *
     * @details This function is called in case of an assert in the SoftDevice.
     *
     * @warning This handler is only an example and is not meant for the final product. You need to analyze
     *          how your product is supposed to react in case of an assert.
     * @warning On assert from the SoftDevice, the system can only recover on reset.
     *
     * @param[in] line_num     Line number of the failing assert call.
     * @param[in] p_file_name  File name of the failing assert call.
     */
    void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name)
    {
        app_error_handler(0xDEADBEEF, line_num, p_file_name);
    }
    
    
    /**@brief Function for handling the LED Button Service Client errors.
     *
     * @param[in]   nrf_error   Error code containing information about what went wrong.
     */
    static void lbs_error_handler(uint32_t nrf_error)
    {
        APP_ERROR_HANDLER(nrf_error);
    }
    
    
    
    /**@brief Function for the LEDs initialization.
     *
     * @details Initializes all LEDs used by the application.
     */
    static void leds_init(void)
    {
        bsp_board_init(BSP_INIT_LEDS);
    }
    
    
    static void scan_evt_handler(scan_evt_t const * p_scan_evt)
    {
        ret_code_t err_code;
    
        switch(p_scan_evt->scan_evt_id)
        {
            case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
            {
                err_code = p_scan_evt->params.connecting_err.err_code;
                APP_ERROR_CHECK(err_code);
            } break;
    
            case NRF_BLE_SCAN_EVT_CONNECTED:
             {
                ble_gap_evt_connected_t const * p_connected =
                                 p_scan_evt->params.connected.p_connected;
                 // Scan is automatically stopped by the connection.
                 NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
                          p_connected->peer_addr.addr[0],
                          p_connected->peer_addr.addr[1],
                          p_connected->peer_addr.addr[2],
                          p_connected->peer_addr.addr[3],
                          p_connected->peer_addr.addr[4],
                          p_connected->peer_addr.addr[5]
                            );
             } break;
    
            default:
                break;
        }
    }
    
    
    /**@brief Function for initializing the scanning and setting the filters.
     */
    static void scan_init(void)
    {
        ret_code_t          err_code;
        nrf_ble_scan_init_t init_scan;
    
        memset(&init_scan, 0, sizeof(init_scan));
    
        init_scan.connect_if_match = true;
        init_scan.conn_cfg_tag     = APP_BLE_CONN_CFG_TAG;
    
        err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
        APP_ERROR_CHECK(err_code);
    
        err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_NAME_FILTER, m_target_periph_name);
        APP_ERROR_CHECK(err_code);
    
        err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_NAME_FILTER, false);
        APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function for starting scanning. */
    static void scan_start(void)
    {
        ret_code_t ret;
    
        NRF_LOG_INFO("Start scanning for device name %s.", (uint32_t)m_target_periph_name);
        ret = nrf_ble_scan_start(&m_scan);
        APP_ERROR_CHECK(ret);
        // Turn on the LED to signal scanning.
        bsp_board_led_on(CENTRAL_SCANNING_LED);
    }
    
    
    
    /**@brief Function for handling BLE events.
     *
     * @param[in]   p_ble_evt   Bluetooth stack event.
     * @param[in]   p_context   Unused.
     */
    static void ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context)
    {
        ret_code_t err_code;
        static uint16_t start_handle = 1;
        static uint16_t last = 0;
    
        // For readability.
        ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
    
        //NRF_LOG_INFO("EVT ID: 0x%x ", p_ble_evt->header.evt_id);
    
        switch (p_ble_evt->header.evt_id)
        {
            // Upon connection, check which peripheral is connected, initiate DB
            // discovery, update LEDs status, and resume scanning, if necessary.
            case BLE_GAP_EVT_CONNECTED:
            {
                NRF_LOG_INFO("Connection 0x%x established, starting DB discovery.",
                             p_ble_evt->evt.gap_evt.conn_handle);
    
                APP_ERROR_CHECK_BOOL(p_gap_evt->conn_handle < NRF_SDH_BLE_CENTRAL_LINK_COUNT);
    
                memset(&m_db_disc, 0, sizeof(m_db_disc));
                err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
    
                // Update LEDs status and check whether it is needed to look for more
                // peripherals to connect to.
                bsp_board_led_on(CENTRAL_CONNECTED_LED);
                if (ble_conn_state_central_conn_count() == NRF_SDH_BLE_CENTRAL_LINK_COUNT)
                {
                    bsp_board_led_off(CENTRAL_SCANNING_LED);
                }
                else
                {
                    // Resume scanning.
                    bsp_board_led_on(CENTRAL_SCANNING_LED);
                    scan_start();
                }
            } break; // BLE_GAP_EVT_CONNECTED
    
            // Upon disconnection, reset the connection handle of the peer that disconnected, update
            // the LEDs status and start scanning again.
            case BLE_GAP_EVT_DISCONNECTED:
            {
                NRF_LOG_INFO("Central link 0x%x disconnected (reason: 0x%x)",
                             p_gap_evt->conn_handle,
                             p_gap_evt->params.disconnected.reason);
    
                if (ble_conn_state_central_conn_count() == 0)
                {
                    err_code = app_button_disable();
                    APP_ERROR_CHECK(err_code);
    
                    // Turn off the LED that indicates the connection.
                    bsp_board_led_off(CENTRAL_CONNECTED_LED);
                }
    
                // Start scanning.
                scan_start();
    
                // Turn on the LED for indicating scanning.
                bsp_board_led_on(CENTRAL_SCANNING_LED);
    
                start_handle = 1;
                last = 0;
    
            } break;
    
            case BLE_GAP_EVT_TIMEOUT:
            {
                // Timeout for scanning is not specified, so only the connection requests can time out.
                if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
                {
                    NRF_LOG_DEBUG("Connection request timed out.");
                }
            } break;
    
            case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
            {
                NRF_LOG_DEBUG("BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST.");
                // Accept parameters requested by peer.
                err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
                                            &p_gap_evt->params.conn_param_update_request.conn_params);
                APP_ERROR_CHECK(err_code);
            } break;
    
            case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
            {
                NRF_LOG_DEBUG("PHY update request.");
                ble_gap_phys_t const phys =
                {
                    .rx_phys = BLE_GAP_PHY_AUTO,
                    .tx_phys = BLE_GAP_PHY_AUTO,
                };
                err_code = sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
                APP_ERROR_CHECK(err_code);
            } break;
    
            case BLE_GATTC_EVT_TIMEOUT:
            {
                // Disconnect on GATT client timeout event.
                NRF_LOG_DEBUG("GATT client timeout.");
                err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
                                                 BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
                APP_ERROR_CHECK(err_code);
            } break;
    
            case BLE_GATTS_EVT_TIMEOUT:
            {
                // Disconnect on GATT server timeout event.
                NRF_LOG_DEBUG("GATT server timeout.");
                err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
                                                 BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
                APP_ERROR_CHECK(err_code);
            } break;
    
             /*case BLE_GAP_EVT_AUTH_STATUS:
                 NRF_LOG_INFO("BLE_GAP_EVT_AUTH_STATUS: status=0x%x bond=0x%x lv4: %d kdist_own:0x%x kdist_peer:0x%x",
                              p_ble_evt->evt.gap_evt.params.auth_status.auth_status,
                              p_ble_evt->evt.gap_evt.params.auth_status.bonded,
                              p_ble_evt->evt.gap_evt.params.auth_status.sm1_levels.lv4,
                              *((uint8_t *)&p_ble_evt->evt.gap_evt.params.auth_status.kdist_own),
                              *((uint8_t *)&p_ble_evt->evt.gap_evt.params.auth_status.kdist_peer));
                break;
    
              /*case BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP:
                    	NRF_LOG_INFO("Found service");
                            NRF_LOG_INFO("Last handle %x , start handle %x ", last, start_handle);
    
                if (p_ble_evt->evt.gattc_evt.gatt_status != BLE_GATT_STATUS_ATTERR_ATTRIBUTE_NOT_FOUND)
                {
                  last = p_ble_evt->evt.gattc_evt.params.prim_srvc_disc_rsp.count - 1;
                  start_handle = p_ble_evt->evt.gattc_evt.params.prim_srvc_disc_rsp.services[last].handle_range.end_handle + 1;
                  err_code = sd_ble_gattc_primary_services_discover(p_gap_evt->conn_handle, start_handle, NULL);
                  APP_ERROR_CHECK(err_code);
                }
                else
                {
                  NRF_LOG_INFO("Got BLE_GATT_STATUS_ATTERR_ATTRIBUTE_NOT_FOUND");  
                }*/
    
                                
                break;
    
            default:
                // No implementation needed.
                break;
        }
    }
    
    /**@brief Function for handling the Nordic UART Service Client errors.
     *
     * @param[in]   nrf_error   Error code containing information about what went wrong.
     */
    static void bps_error_handler(uint32_t nrf_error)
    {
        APP_ERROR_HANDLER(nrf_error);
    }
    
    
    /**@brief Heart Rate Collector Handler.
     */
    //static void hrs_c_evt_handler(ble_hrs_c_t * p_hrs_c, ble_hrs_c_evt_t * p_hrs_c_evt)
    static void bps_c_evt_handler(ble_bps_c_t * p_bps, ble_bps_c_evt_t const * ble_bps_evt)
    {
        ret_code_t err_code;
    
        switch (ble_bps_evt->evt_type)
        {
            case BLE_BPS_C_EVT_DISCOVERY_COMPLETE:
            {
                NRF_LOG_DEBUG("Heart rate service discovered.");
    
                err_code = ble_bps_c_handles_assign(p_bps,
                                                    ble_bps_evt->conn_handle,
                                                    &ble_bps_evt->params.peer_db);
                APP_ERROR_CHECK(err_code);
    
                // Initiate bonding.
                err_code = pm_conn_secure(ble_bps_evt->conn_handle, false);
                if (err_code != NRF_ERROR_BUSY)
                {
                    APP_ERROR_CHECK(err_code);
                }
    
                // Heart rate service discovered. Enable indication.
                err_code = ble_bps_c_meas_indication_enable(p_bps);
                APP_ERROR_CHECK(err_code);
            } break;
    
            case BLE_BPS_C_EVT_MEAS_INDICATION:
            {
                NRF_LOG_INFO("BP Meas example %f", ble_bps_evt->params.meas.blood_pressure_systolic);
                
            } break;
    
            default:
                break;
        }
    }
    
    
    static void bps_c_init(void)
    {
        ret_code_t       err_code;
        ble_bps_c_init_t   init;
    
        init.evt_handler   = bps_c_evt_handler;
        init.error_handler = bps_error_handler;
        init.p_gatt_queue  = &m_ble_gatt_queue;
    
        err_code = ble_bps_c_init(&m_bps_c, &init);
        APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function for initializing the BLE stack.
     *
     * @details Initializes the SoftDevice and the BLE event interrupts.
     */
    static void ble_stack_init(void)
    {
        ret_code_t err_code;
    
        err_code = nrf_sdh_enable_request();
        APP_ERROR_CHECK(err_code);
    
        // Configure the BLE stack using the default settings.
        // Fetch the start address of the application RAM.
        uint32_t ram_start = 0;
        err_code = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &ram_start);
        APP_ERROR_CHECK(err_code);
    
        // Enable BLE stack.
        err_code = nrf_sdh_ble_enable(&ram_start);
        APP_ERROR_CHECK(err_code);
    
        // Register a handler for BLE events.
        NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, ble_evt_handler, NULL);
    }
    
    /**@brief Function for handling Peer Manager events.
     *
     * @param[in] p_evt  Peer Manager event.
     */
    static void pm_evt_handler(pm_evt_t const * p_evt)
    {
        pm_handler_on_pm_evt(p_evt);
        pm_handler_flash_clean(p_evt);
    
        switch (p_evt->evt_id)
        {
            case PM_EVT_PEERS_DELETE_SUCCEEDED:
                // Bonds are deleted. Start scanning.
                scan_start();
                break;
    
            default:
                break;
        }
    }
    
    /**@brief Function for the Peer Manager initialization.
     */
    static void peer_manager_init(void)
    {
        ble_gap_sec_params_t sec_param;
        ret_code_t err_code;
    
        err_code = pm_init();
        APP_ERROR_CHECK(err_code);
    
        memset(&sec_param, 0, sizeof(ble_gap_sec_params_t));
    
        // Security parameters to be used for all security procedures.
        sec_param.bond           = SEC_PARAM_BOND;
        sec_param.mitm           = SEC_PARAM_MITM;
        sec_param.lesc           = SEC_PARAM_LESC;
        sec_param.keypress       = SEC_PARAM_KEYPRESS;
        sec_param.io_caps        = SEC_PARAM_IO_CAPABILITIES;
        sec_param.oob            = SEC_PARAM_OOB;
        sec_param.min_key_size   = SEC_PARAM_MIN_KEY_SIZE;
        sec_param.max_key_size   = SEC_PARAM_MAX_KEY_SIZE;
        sec_param.kdist_own.enc  = 1;
        sec_param.kdist_own.id   = 1;
        sec_param.kdist_peer.enc = 1;
        sec_param.kdist_peer.id  = 1;
    
        err_code = pm_sec_params_set(&sec_param);
        APP_ERROR_CHECK(err_code);
    
        err_code = pm_register(pm_evt_handler);
        APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function for handling events from the button handler module.
     *
     * @param[in] pin_no        The pin that the event applies to.
     * @param[in] button_action The button action (press or release).
     */
    static void button_event_handler(uint8_t pin_no, uint8_t button_action)
    {
        ret_code_t err_code;
    
        switch (pin_no)
        {
            case LEDBUTTON_BUTTON:
                //err_code = led_status_send_to_all(button_action);
                if (err_code == NRF_SUCCESS)
                {
                    NRF_LOG_INFO("LBS write LED state %d", button_action);
                }
                break;
    
            default:
                APP_ERROR_HANDLER(pin_no);
                break;
        }
    }
    
    
    /**@brief Function for initializing the button handler module.
     */
    static void buttons_init(void)
    {
        ret_code_t err_code;
    
       // The array must be static because a pointer to it is saved in the button handler module.
        static app_button_cfg_t buttons[] =
        {
            {LEDBUTTON_BUTTON, false, BUTTON_PULL, button_event_handler}
        };
    
        err_code = app_button_init(buttons, ARRAY_SIZE(buttons), BUTTON_DETECTION_DELAY);
        APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function for handling database discovery events.
     *
     * @details This function is a callback function to handle events from the database discovery module.
     *          Depending on the UUIDs that are discovered, this function forwards the events
     *          to their respective services.
     *
     * @param[in] p_event  Pointer to the database discovery event.
     */
    static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
    {
        NRF_LOG_INFO("call to ble_bps_on_db_disc_evt for instance 0x%x and handle 0x%x!",
                      p_evt->params.p_db_instance,
                      p_evt->conn_handle);
    
        NRF_LOG_INFO("APP FOUND %d CHARACTERISTICS.", p_evt->params.discovered_db.char_count);
    
        NRF_LOG_INFO("APP FOUND SERVICE UUID 0x%x", p_evt->params.discovered_db.srv_uuid.uuid);
        ble_bps_on_db_disc_evt(&m_bps_c, p_evt);
        ble_bas_on_db_disc_evt(&m_bas_c, p_evt);
    }
    
    
    /**@brief Battery level Collector Handler.
     */
    static void bas_c_evt_handler(ble_bas_c_t * p_bas_c, ble_bas_c_evt_t * p_bas_c_evt)
    {
        ret_code_t err_code;
    
        switch (p_bas_c_evt->evt_type)
        {
            case BLE_BAS_C_EVT_DISCOVERY_COMPLETE:
            {
                err_code = ble_bas_c_handles_assign(p_bas_c,
                                                    p_bas_c_evt->conn_handle,
                                                    &p_bas_c_evt->params.bas_db);
                APP_ERROR_CHECK(err_code);
    
                // Battery service discovered. Enable notification of Battery Level.
                NRF_LOG_DEBUG("Battery Service discovered. Reading battery level.");
    
                err_code = ble_bas_c_bl_read(p_bas_c);
                APP_ERROR_CHECK(err_code);
    
                NRF_LOG_DEBUG("Enabling Battery Level Notification.");
                err_code = ble_bas_c_bl_notif_enable(p_bas_c);
                APP_ERROR_CHECK(err_code);
    
            } break;
    
            case BLE_BAS_C_EVT_BATT_NOTIFICATION:
                NRF_LOG_INFO("Battery Level received %d %%.", p_bas_c_evt->params.battery_level);
                break;
    
            case BLE_BAS_C_EVT_BATT_READ_RESP:
                NRF_LOG_INFO("Battery Level Read as %d %%.", p_bas_c_evt->params.battery_level);
                break;
    
            default:
                break;
        }
    }
    
    /**@brief Function for handling the Heart Rate Service Client and Battery Service Client errors.
     *
     * @param[in]   nrf_error   Error code containing information about what went wrong.
     */
    static void service_error_handler(uint32_t nrf_error)
    {
        APP_ERROR_HANDLER(nrf_error);
    }
    
    
    /**
     * @brief Battery level collector initialization.
     */
    static void bas_c_init(void)
    {
        ble_bas_c_init_t bas_c_init_obj;
    
        bas_c_init_obj.evt_handler   = bas_c_evt_handler;
        bas_c_init_obj.error_handler = service_error_handler;
        bas_c_init_obj.p_gatt_queue  = &m_ble_gatt_queue;
    
        ret_code_t err_code = ble_bas_c_init(&m_bas_c, &bas_c_init_obj);
        APP_ERROR_CHECK(err_code);
    }
    
    
    /** @brief Database discovery initialization.
     */
    static void db_discovery_init(void)
    {
        ble_db_discovery_init_t db_init;
    
        memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
    
        db_init.evt_handler  = db_disc_handler;
        db_init.p_gatt_queue = &m_ble_gatt_queue;
    
        ret_code_t err_code = ble_db_discovery_init(&db_init);
        APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function for initializing power management.
     */
    static void power_management_init(void)
    {
        ret_code_t err_code;
        err_code = nrf_pwr_mgmt_init();
        APP_ERROR_CHECK(err_code);
    }
    
    
    /**@brief Function for handling the idle state (main loop).
     *
     * @details This function handles any pending log operations, then sleeps until the next event occurs.
     */
    static void idle_state_handle(void)
    {
        if (NRF_LOG_PROCESS() == false)
        {
            nrf_pwr_mgmt_run();
        }
    }
    
    
    /** @brief Function for initializing the log module.
     */
    static void log_init(void)
    {
        ret_code_t err_code = NRF_LOG_INIT(NULL);
        APP_ERROR_CHECK(err_code);
    
        NRF_LOG_DEFAULT_BACKENDS_INIT();
    }
    
    
    /** @brief Function for initializing the timer.
     */
    static void timer_init(void)
    {
        ret_code_t err_code = app_timer_init();
        APP_ERROR_CHECK(err_code);
    }
    
    /**@brief GATT module event handler.
     */
    static void gatt_evt_handler(nrf_ble_gatt_t * p_gatt, nrf_ble_gatt_evt_t const * p_evt)
    {
        switch (p_evt->evt_id)
        {
            case NRF_BLE_GATT_EVT_ATT_MTU_UPDATED:
            {
                NRF_LOG_INFO("GATT ATT MTU on connection 0x%x changed to %d.",
                             p_evt->conn_handle,
                             p_evt->params.att_mtu_effective);
            } break;
    
            case NRF_BLE_GATT_EVT_DATA_LENGTH_UPDATED:
            {
                NRF_LOG_INFO("Data length for connection 0x%x updated to %d.",
                             p_evt->conn_handle,
                             p_evt->params.data_length);
            } break;
    
            default:
                break;
        }
    }
    
    /**@brief Function for initializing the GATT module.
     */
    static void gatt_init(void)
    {
        ret_code_t err_code = nrf_ble_gatt_init(&m_gatt, gatt_evt_handler);
        APP_ERROR_CHECK(err_code);
    }
    
    
    int main(void)
    {
        // Initialize.
        log_init();
        timer_init();
        leds_init();
        buttons_init();
        db_discovery_init();
        power_management_init();
        ble_stack_init();
        gatt_init();
        bps_c_init();
        ble_conn_state_init();
        bas_c_init();
        scan_init();
        peer_manager_init();
    
    
        // Start execution.
        NRF_LOG_INFO("C-Detect-LIKE example started.");
        scan_start();
    
        for (;;)
        {
            idle_state_handle();
        }
    }
    
    0676.ble_bps_c.h
    /**
     * Copyright (c) 2012 - 2019, Nordic Semiconductor ASA
     *
     * All rights reserved.
     *
     * Redistribution and use in source and binary forms, with or without modification,
     * are permitted provided that the following conditions are met:
     *
     * 1. Redistributions of source code must retain the above copyright notice, this
     *    list of conditions and the following disclaimer.
     *
     * 2. Redistributions in binary form, except as embedded into a Nordic
     *    Semiconductor ASA integrated circuit in a product or a software update for
     *    such product, must reproduce the above copyright notice, this list of
     *    conditions and the following disclaimer in the documentation and/or other
     *    materials provided with the distribution.
     *
     * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
     *    contributors may be used to endorse or promote products derived from this
     *    software without specific prior written permission.
     *
     * 4. This software, with or without modification, must only be used with a
     *    Nordic Semiconductor ASA integrated circuit.
     *
     * 5. Any software provided in binary form under this license must not be reverse
     *    engineered, decompiled, modified and/or disassembled.
     *
     * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
     * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
     * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
     * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
     * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
     * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     *
     */
    /**@cond To Make Doxygen skip documentation generation for this file.
     * @{
     */
    #include "sdk_common.h"
    //#if NRF_MODULE_ENABLED(BLE_BPS_C)
    #include "ble_bps_c.h"
    #include "ble_db_discovery.h"
    #include "ble_types.h"
    #include "ble_gattc.h"
    
    #define NRF_LOG_MODULE_NAME ble_bps_c
    #include "nrf_log.h"
    NRF_LOG_MODULE_REGISTER();
    
    #define HRM_FLAG_MASK_HR_16BIT  (0x01 << 0)           /**< Bit mask used to extract the type of heart rate value. This is used to find if the received heart rate is a 16 bit value or an 8 bit value. */
    #define HRM_FLAG_MASK_HR_RR_INT (0x01 << 4)           /**< Bit mask used to extract the presence of RR_INTERVALS. This is used to find if the received measurement includes RR_INTERVALS. */
    
    
    /**@brief Function for interception of the errors of GATTC and the BLE GATT Queue.
     *
     * @param[in] nrf_error   Error code.
     * @param[in] p_ctx       Parameter from the event handler.
     * @param[in] conn_handle Connection handle.
     */
    static void gatt_error_handler(uint32_t   nrf_error,
                                   void     * p_ctx,
                                   uint16_t   conn_handle)
    {
        ble_bps_c_t * p_ble_bps_c = (ble_bps_c_t *)p_ctx;
    
        NRF_LOG_DEBUG("A GATT Client error has occurred on conn_handle: 0X%X", conn_handle);
    
        if (p_ble_bps_c->error_handler != NULL)
        {
            p_ble_bps_c->error_handler(nrf_error);
        }
    }
    
    
    /**@brief     Function for handling Handle Value Indication received from the SoftDevice.
     *
     * @details   This function uses the Handle Value Indication received from the SoftDevice
     *            and checks whether it is a notification of the heart rate measurement from the peer. If
     *            it is, this function decodes the heart rate measurement and sends it to the
     *            application.
     *
     * @param[in] p_ble_bps_c Pointer to the Blood Pressure Client structure.
     * @param[in] p_ble_evt   Pointer to the BLE event received.
     */
    static void on_hvx(ble_bps_c_t * p_ble_bps_c, const ble_evt_t * p_ble_evt)
    {
        // Check if the event is on the link for this instance.
        if (p_ble_bps_c->conn_handle != p_ble_evt->evt.gattc_evt.conn_handle)
        {
            NRF_LOG_DEBUG("Received HVX on link 0x%x, not associated to this instance. Ignore.",
                          p_ble_evt->evt.gattc_evt.conn_handle);
            return;
        }
    
        NRF_LOG_DEBUG("Received HVX on link 0x%x, hrm_handle 0x%x",
        p_ble_evt->evt.gattc_evt.params.hvx.handle,
        p_ble_bps_c->peer_bps_db.meas_handle);
    
        // Check if this is a heart rate indication.
        if (p_ble_evt->evt.gattc_evt.params.hvx.handle == p_ble_bps_c->peer_bps_db.meas_handle)
        {
            ble_bps_c_evt_t ble_bps_c_evt;
            uint32_t        index = 0;
    
            ble_bps_c_evt.evt_type                    = BLE_BPS_C_EVT_MEAS_INDICATION;
            ble_bps_c_evt.conn_handle                 = p_ble_bps_c->conn_handle;
            //not exist ble_bps_c_evt.params.meas.rr_intervals_cnt = 0;
    
            if (!(p_ble_evt->evt.gattc_evt.params.hvx.data[index++] & HRM_FLAG_MASK_HR_16BIT))
            {
                // 8-bit heart rate value received.
                // needs looking at ble_bps_c_evt.params.meas.hr_value = p_ble_evt->evt.gattc_evt.params.hvx.data[index++];  //lint !e415 suppress Lint Warning 415: Likely access out of bond
            }
            else
            {
                // 16-bit heart rate value received.
                // needs looking at ble_bps_c_evt.params.meas.hr_value = uint16_decode(&(p_ble_evt->evt.gattc_evt.params.hvx.data[index]));
                index += sizeof(uint16_t);
            }
    #if NOT_NEEDED_FOR_BPS
            if ((p_ble_evt->evt.gattc_evt.params.hvx.data[0] & HRM_FLAG_MASK_HR_RR_INT))
            {
    
                uint32_t i;
                lint --e{415} --e{416} --e{662} --e{661} -save suppress Warning 415: possible access out of bond */
                for (i = 0; i < BLE_HRS_C_RR_INTERVALS_MAX_CNT; i ++)
                {
                    if (index >= p_ble_evt->evt.gattc_evt.params.hvx.len)
                    {
                        break;
                    }
                    ble_bps_c_evt.params.meas.rr_intervals[i] =
                        uint16_decode(&(p_ble_evt->evt.gattc_evt.params.hvx.data[index]));
                    index += sizeof(uint16_t);
                }
                /*lint -restore*/
                ble_bps_c_evt.params.meas.rr_intervals_cnt = (uint8_t)i;
                
            }
    #endif //#if NOT_NEEDED_FOR_BPS
            p_ble_bps_c->evt_handler(p_ble_bps_c, &ble_bps_c_evt);
        }
    
    }
    
    
    /**@brief     Function for handling Disconnected event received from the SoftDevice.
     *
     * @details   This function checks whether the disconnect event is happening on the link
     *            associated with the current instance of the module. If the event is happening, the function sets the instance's
     *            conn_handle to invalid.
     *
     * @param[in] p_ble_bps_c Pointer to the Blood Pressure Client structure.
     * @param[in] p_ble_evt   Pointer to the BLE event received.
     */
    static void on_disconnected(ble_bps_c_t * p_ble_bps_c, const ble_evt_t * p_ble_evt)
    {
        if (p_ble_bps_c->conn_handle == p_ble_evt->evt.gap_evt.conn_handle)
        {
            p_ble_bps_c->conn_handle                 = BLE_CONN_HANDLE_INVALID;
            p_ble_bps_c->peer_bps_db.meas_cccd_handle = BLE_GATT_HANDLE_INVALID;
            p_ble_bps_c->peer_bps_db.feat_cccd_handle = BLE_GATT_HANDLE_INVALID;
            p_ble_bps_c->peer_bps_db.meas_handle      = BLE_GATT_HANDLE_INVALID;
            p_ble_bps_c->peer_bps_db.feat_handle      = BLE_GATT_HANDLE_INVALID;
        }
    }
    
    
    void ble_bps_on_db_disc_evt(ble_bps_c_t * p_ble_bps_c, const ble_db_discovery_evt_t * p_evt)
    {
        ble_bps_c_evt_t bps_c_evt;
        memset(&bps_c_evt,0,sizeof(ble_bps_c_evt_t));
    
        ble_gatt_db_char_t * p_chars = p_evt->params.discovered_db.charateristics;
    
        // Check if the Blood Pressure Service was discovered.
        if (p_evt->evt_type == BLE_DB_DISCOVERY_COMPLETE &&
            p_evt->params.discovered_db.srv_uuid.uuid == BLE_UUID_BLOOD_PRESSURE_SERVICE &&
            p_evt->params.discovered_db.srv_uuid.type == BLE_UUID_TYPE_BLE)
        {
            // Find the CCCD Handle of the Blood Pressure Measurement characteristic.
            uint32_t i;
    
            ble_bps_c_evt_t evt;
    
            evt.evt_type    = BLE_BPS_C_EVT_DISCOVERY_COMPLETE;
            evt.conn_handle = p_evt->conn_handle;
    
            for (i = 0; i < p_evt->params.discovered_db.char_count; i++)
            {
                switch (p_chars[i].characteristic.uuid.uuid)
                {
                    /*case MJR_LE_NOTIFYCATION_UUID:
    
                        nus_c_evt.handles.nus_rx_handle = p_chars[i].characteristic.handle_value;
                        break;
    
                    case MJR_LE_WRITE_NO_RESPONSE_UUID:
    
                        nus_c_evt.handles.nus_tx_handle = p_chars[i].characteristic.handle_value;
                        nus_c_evt.handles.nus_tx_cccd_handle = p_chars[i].cccd_handle;
                        break;*/
    
                    default:
                        NRF_LOG_INFO("I can see Characteristic with UUID 0x%x", p_chars[i].characteristic.uuid.uuid);
                        break;
                }
            }
    
            NRF_LOG_DEBUG("Blood Pressure Service discovered at peer.");
            //If the instance has been assigned prior to db_discovery, assign the db_handles.
            if (p_ble_bps_c->conn_handle != BLE_CONN_HANDLE_INVALID)
            {
                if ((p_ble_bps_c->peer_bps_db.meas_cccd_handle == BLE_GATT_HANDLE_INVALID)&&
                    (p_ble_bps_c->peer_bps_db.meas_handle == BLE_GATT_HANDLE_INVALID)&&
                    (p_ble_bps_c->peer_bps_db.feat_cccd_handle == BLE_GATT_HANDLE_INVALID)&&
                    (p_ble_bps_c->peer_bps_db.feat_handle == BLE_GATT_HANDLE_INVALID))
                {
                    p_ble_bps_c->peer_bps_db = evt.params.peer_db;
                }
            }
    
    
            p_ble_bps_c->evt_handler(p_ble_bps_c, &evt);
        }
    }
    
    
    uint32_t ble_bps_c_init(ble_bps_c_t * p_ble_bps_c, ble_bps_c_init_t * p_ble_bps_c_init)
    {
        VERIFY_PARAM_NOT_NULL(p_ble_bps_c);
        VERIFY_PARAM_NOT_NULL(p_ble_bps_c_init);
    
        ble_uuid_t bps_c_uuid;
    
        bps_c_uuid.type = BLE_UUID_TYPE_BLE;
        bps_c_uuid.uuid = BLE_UUID_BLOOD_PRESSURE_SERVICE;
    
        p_ble_bps_c->evt_handler                    = p_ble_bps_c_init->evt_handler;
        p_ble_bps_c->error_handler                  = p_ble_bps_c_init->error_handler;
        p_ble_bps_c->p_gatt_queue                   = p_ble_bps_c_init->p_gatt_queue;
        p_ble_bps_c->conn_handle                    = BLE_CONN_HANDLE_INVALID;
        p_ble_bps_c->peer_bps_db.meas_cccd_handle   = BLE_GATT_HANDLE_INVALID;
        p_ble_bps_c->peer_bps_db.feat_cccd_handle   = BLE_GATT_HANDLE_INVALID;
        p_ble_bps_c->peer_bps_db.meas_handle        = BLE_GATT_HANDLE_INVALID;
        p_ble_bps_c->peer_bps_db.feat_handle        = BLE_GATT_HANDLE_INVALID;
    
        return ble_db_discovery_evt_register(&bps_c_uuid);
    }
    
    
    void ble_bps_c_on_ble_evt(ble_evt_t const * p_ble_evt, void * p_context)
    {
        ble_bps_c_t * p_ble_bps_c = (ble_bps_c_t *)p_context;
    
        if ((p_ble_bps_c == NULL) || (p_ble_evt == NULL))
        {
            return;
        }
    
        switch (p_ble_evt->header.evt_id)
        {
            case BLE_GATTC_EVT_HVX:
                on_hvx(p_ble_bps_c, p_ble_evt);
                break;
    
            case BLE_GAP_EVT_DISCONNECTED:
                on_disconnected(p_ble_bps_c, p_ble_evt);
                break;
    
            default:
                break;
        }
    }
    
    
    /**@brief Function for creating a message for writing to the CCCD.
     */
    static uint32_t cccd_configure(ble_bps_c_t * p_ble_bps_c, bool enable)
    {
        NRF_LOG_DEBUG("Configuring CCCD. CCCD Handle = %d, Connection Handle = %d",
                      p_ble_bps_c->peer_bps_db.meas_cccd_handle,
                      p_ble_bps_c->conn_handle);
    
        nrf_ble_gq_req_t bps_c_req;
        uint8_t          cccd[BLE_CCCD_VALUE_LEN];
        uint16_t         cccd_val = enable ? BLE_GATT_HVX_INDICATION : 0;
    
        cccd[0] = LSB_16(cccd_val);
        cccd[1] = MSB_16(cccd_val);
    
        memset(&bps_c_req, 0, sizeof(bps_c_req));
    
        bps_c_req.type                        = NRF_BLE_GQ_REQ_GATTC_WRITE;
        bps_c_req.error_handler.cb            = gatt_error_handler;
        bps_c_req.error_handler.p_ctx         = p_ble_bps_c;
        bps_c_req.params.gattc_write.handle   = p_ble_bps_c->peer_bps_db.meas_cccd_handle;
        bps_c_req.params.gattc_write.len      = BLE_CCCD_VALUE_LEN;
        bps_c_req.params.gattc_write.p_value  = cccd;
        bps_c_req.params.gattc_write.write_op = BLE_GATT_OP_WRITE_REQ;
    
        return nrf_ble_gq_item_add(p_ble_bps_c->p_gatt_queue, &bps_c_req, p_ble_bps_c->conn_handle);
    }
    
    
    uint32_t ble_bps_c_meas_indication_enable(ble_bps_c_t * p_ble_bps_c)
    {
        VERIFY_PARAM_NOT_NULL(p_ble_bps_c);
    
        return cccd_configure(p_ble_bps_c, true);
    }
    
    
    uint32_t ble_bps_c_handles_assign(ble_bps_c_t    * p_ble_bps_c,
                                      uint16_t         conn_handle,
                                      const bps_c_db_t * p_peer_bps_handles)
    {
        VERIFY_PARAM_NOT_NULL(p_ble_bps_c);
    
        p_ble_bps_c->conn_handle = conn_handle;
        if (p_peer_bps_handles != NULL)
        {
            p_ble_bps_c->peer_bps_db = *p_peer_bps_handles;
        }
    
        return nrf_ble_gq_conn_handle_register(p_ble_bps_c->p_gatt_queue, conn_handle);
    }
    /** @}
     *  @endcond
     */
    //#endif // NRF_MODULE_ENABLED(BLE_HRS_C)
    

    Before we close this ticket, could you point me to an example on how to (considering I am working on the central device):


    a) Read the battery level upon connection once (not using notifications like the hrs example).

    b) Write to the BLE_UUID_DATE_TIME_CHAR upon connection (obviously it can be a different characteristic).

     

    If you wish not to respond me, I will understand and close positively the ticket regardless since you have accomplished the main goal.

    Thanks in advance.

    George

Related