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();
}
}
/**
* 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