This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

Device does not sleep after disconnection.

Hi,

 

I’m trying to measure the current on NRF52840, SDK 17.0.2.

I have modified the HeartRate Measurement example’s advertising parameters as PLper my requirement.

I observe that while my device is advertising, the current is around 40 Micro Amps and the sleep current is 3.2 Micro Amps.

Once I connect and disconnect to the device using NrfConnect, the current is 30 Micro Amps and does not drop back to 3.2 Micro Amps.

Why is my device not going to sleep after disconnection?

 

 

Thanks,

Chitra

Parents
  • Thanks for your reply, Vidar.

    I’m not using the ble_advertising_init(), I have modified the advertising_init(), to use sd_ble_gap_adv_set_configure() as followed in the ble_app_blinky example.

    Also, I have modified the application to transmit the beacon once every minute.

    With my changes, the device sleep current is around 3.2 Micro Amps(with logging turned off)  which seems reasonable.

    But, why does my device fail to go to sleep after a Connect and Disconnect?

    Kind Regards,

    Chitra

Reply
  • Thanks for your reply, Vidar.

    I’m not using the ble_advertising_init(), I have modified the advertising_init(), to use sd_ble_gap_adv_set_configure() as followed in the ble_app_blinky example.

    Also, I have modified the application to transmit the beacon once every minute.

    With my changes, the device sleep current is around 3.2 Micro Amps(with logging turned off)  which seems reasonable.

    But, why does my device fail to go to sleep after a Connect and Disconnect?

    Kind Regards,

    Chitra

Children
  • Thanks for the clarification. I assumed you were using the Advertising Module like in the original example.

    Unless you have already removed the module's source file from the build, please ensure you have the 'BLE_ADVERTISING_ENABLED' configuration setting disabled in sdk_Config. This will prevent the module from receiving BLE events such as connect and disconnect.

    Best regards,

    Vidar

  • Thanks,

     

    I tried disabling the ‘BLE_ADVERTISING_ENABLED’ configuration setting in the sdk_config.h, it did not fix the issue.

    Regards,

    Chitra

  • I'm afraid I'm starting to run out of ideas. Would be easier if I could see the code. Any chance you could share it here or in a PM?

    Thanks,

    Vidar

  • Here is the code.

    /**
     * Copyright (c) 2014 - 2020, 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.
     *
     */
    /** @example examples/ble_peripheral/ble_app_hrs/main.c
     *
     * @brief Heart Rate Service Sample Application main file.
     *
     * This file contains the source code for a sample application using the Heart Rate service
     * (and also Battery and Device Information services). This application uses the
     * @ref srvlib_conn_params module.
     */
    
    #include "app_error.h"
    #include "app_timer.h"
    #include "ble.h"
    #include "ble_advdata.h"
    #include "ble_advertising.h"
    #include "ble_bas.h"
    #include "ble_conn_params.h"
    #include "ble_conn_state.h"
    #include "ble_dis.h"
    #include "ble_err.h"
    #include "ble_gap.h"
    #include "ble_hci.h"
    #include "ble_hrs.h"
    #include "ble_srv_common.h"
    #include "bsp_btn_ble.h"
    #include "fds.h"
    #include "nordic_common.h"
    #include "nrf.h"
    #include "nrf_ble_gatt.h"
    #include "nrf_ble_lesc.h"
    #include "nrf_ble_qwr.h"
    #include "nrf_pwr_mgmt.h"
    #include "nrf_sdh.h"
    #include "nrf_sdh_ble.h"
    #include "nrf_sdh_soc.h"
    #include "nrf_sdm.h"
    #include "peer_manager.h"
    #include "peer_manager_handler.h"
    #include "sensorsim.h"
    #include <stdint.h>
    #include <string.h>
    #include <stdlib.h>
    
    #include "nrf_log.h"
    #include "nrf_log_ctrl.h"
    #include "nrf_log_default_backends.h"
    
    #define DEVICE_NAME "Nordic_HRM"                /**< Name of device. Will be included in the advertising data. */
    #define MANUFACTURER_NAME "NordicSemiconductor" /**< Manufacturer. Will be passed to Device Information Service. */
    
    #define APP_ADV_INTERVAL MSEC_TO_UNITS(500, UNIT_0_625_MS)
    
    #define APP_ADV_DURATION MSEC_TO_UNITS(10000, UNIT_10_MS)
    #define APP_BLE_CONN_CFG_TAG 1  /**< A tag identifying the SoftDevice BLE configuration. */
    #define APP_BLE_OBSERVER_PRIO 3 /**< Application's BLE observer priority. You shouldn't need to modify this value. */
    
    #define BATTERY_LEVEL_MEAS_INTERVAL APP_TIMER_TICKS(30000) /**< Battery level measurement interval (ticks). */
    #define MIN_BATTERY_LEVEL 81                               /**< Minimum simulated battery level. */
    #define MAX_BATTERY_LEVEL 100                              /**< Maximum simulated 7battery level. */
    #define BATTERY_LEVEL_INCREMENT 1                          /**< Increment between each simulated battery level measurement. */
    
    #define HEART_RATE_MEAS_INTERVAL APP_TIMER_TICKS(10000) /**< Heart rate measurement interval (ticks). */
    #define MIN_HEART_RATE 140                              /**< Minimum heart rate as returned by the simulated measurement function. */
    #define MAX_HEART_RATE 300                              /**< Maximum heart rate as returned by the simulated measurement function. */
    #define HEART_RATE_INCREMENT 10                         /**< Value by which the heart rate is incremented/decremented for each call to the simulated measurement function. */
    
    
    #define MIN_CONN_INTERVAL MSEC_TO_UNITS(400, UNIT_1_25_MS) /**< Minimum acceptable connection interval (0.4 seconds). */
    #define MAX_CONN_INTERVAL MSEC_TO_UNITS(650, UNIT_1_25_MS) /**< Maximum acceptable connection interval (0.65 second). */
    #define SLAVE_LATENCY 0                                    /**< Slave latency. */
    #define CONN_SUP_TIMEOUT MSEC_TO_UNITS(4000, UNIT_10_MS)   /**< Connection supervisory timeout (4 seconds). */
    
    #define FIRST_CONN_PARAMS_UPDATE_DELAY APP_TIMER_TICKS(5000) /**< Time from initiating event (connect or start of notification) to first time sd_ble_gap_conn_param_update is called (5 seconds). */
    #define NEXT_CONN_PARAMS_UPDATE_DELAY APP_TIMER_TICKS(30000) /**< Time between each call to sd_ble_gap_conn_param_update after the first call (30 seconds). */
    #define MAX_CONN_PARAMS_UPDATE_COUNT 3                       /**< Number of attempts before giving up the connection parameter negotiation. */
    
    #define LESC_DEBUG_MODE 0 /**< Set to 1 to use LESC debug keys, allows you to use a sniffer to inspect traffic. */
    
    #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. */
    #define SEC_PARAM_MAX_KEY_SIZE 16                      /**< Maximum encryption key size. */
    
    #define DEAD_BEEF 0xDEADBEEF /**< Value used as error code on stack dump, can be used to identify stack location on stack unwind. */
    
    #define TICK_CHAR_UUID 0x1701
    #define RATE_CHAR_UUID 0x1702
    #define OWN_CHAR_UUID 0x1703
    
    typedef struct ble_tag_s ble_tag_t;
    
    BLE_HRS_DEF(m_hrs);                       /**< Heart rate service instance. */
    BLE_BAS_DEF(m_bas);                       /**< Structure used to identify the battery service. */
    NRF_BLE_GATT_DEF(m_gatt);                 /**< GATT module instance. */
    NRF_BLE_QWR_DEF(m_qwr);                   /**< Context for the Queued Write module.*/
    //BLE_ADVERTISING_DEF(m_advertising);       /**< Advertising module instance. */
    APP_TIMER_DEF(m_battery_timer_id);        /**< Battery timer. */
    APP_TIMER_DEF(m_heart_rate_timer_id);     /**< Heart rate measurement timer. */
    
    void ble_tag_on_ble_evt(ble_evt_t const *p_ble_evt, void *p_context);
    static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; /**< Handle of the current connection. */
    static bool m_rr_interval_enabled = true;                /**< Flag for enabling and disabling the registration of new RR interval measurements (the purpose of disabling this is just to test sending HRM without RR interval data. */
    static volatile bool advertising_on = true;
    
    #define TAG_ADV_DATA_ID 0x01
    
    static uint8_t m_adv_handle = BLE_GAP_ADV_SET_HANDLE_NOT_SET;
    static bool advertising = false;
    static ble_advdata_manuf_data_t manuf_data;
    static ble_gap_adv_params_t adv_params;
    static uint8_t m_enc_advdata[BLE_GAP_ADV_SET_DATA_SIZE_MAX];
    static uint8_t m_enc_scan_response_data[BLE_GAP_ADV_SET_DATA_SIZE_MAX];
    static void idle_state_handle(void);
    
    #define TAG_UUID_BASE                               \
      { 0x91, 0xD1, 0xFA, 0x59, 0x93, 0x7D, 0x4E, 0xB2, \
        0xBB, 0x81, 0x36, 0xAF, 0x92, 0x21, 0xF0, 0x8E }
    
    #define TAG_SERVICE_UUID 0x1700
    
    static ble_gap_adv_data_t m_adv_data =
        {
            .adv_data =
                {
                    .p_data = m_enc_advdata,
                    .len = BLE_GAP_ADV_SET_DATA_SIZE_MAX},
            .scan_rsp_data =
                {
                    .p_data = m_enc_scan_response_data,
                    .len = BLE_GAP_ADV_SET_DATA_SIZE_MAX
    
                }};
    
    typedef enum {
      BLE_TAG_EVT_NOTIFICATION_ENABLED,
      BLE_TAG_EVT_NOTIFICATION_DISABLED,
      BLE_TAG_EVT_DISCONNECTED,
      BLE_TAG_EVT_CONNECTED,
      BLE_TAG_EVT_WRITE
    } ble_tag_evt_type_t;
    
    typedef struct
    {
      ble_tag_evt_type_t evt_type;
      uint8_t const *p_data;
    } ble_tag_evt_t;
    
    typedef void (*ble_tag_evt_handler_t)(ble_tag_t *p_tag, ble_tag_evt_t *p_evt);
    
    typedef struct
    {
      ble_tag_evt_handler_t evt_handler;
      uint8_t *p_initial_measurements;
      ble_srv_cccd_security_mode_t custom_value_char_attr_md;
    } ble_tag_init_t;
    
    struct ble_tag_s {
      ble_tag_evt_handler_t evt_handler;
      uint16_t service_handle;
      ble_gatts_char_handles_t tick_handle;
      ble_gatts_char_handles_t rate_handle;
      ble_gatts_char_handles_t own_handle;
      uint16_t conn_handle;
      uint8_t uuid_type;
    };
    
    #define BLE_TAG_DEF(_name)          \
      static ble_tag_t _name;           \
      NRF_SDH_BLE_OBSERVER(_name##_obs, \
          BLE_HRS_BLE_OBSERVER_PRIO,    \
          ble_tag_on_ble_evt, &_name)
    
    BLE_TAG_DEF(m_tag);
    
    static void application_timers_start(void);
    static void application_timers_stop(void);
    
    
    /**@brief Callback function for asserts in the SoftDevice.
     *
     * @details This function will be called in case of an assert in the SoftDevice.
     *
     * @warning This handler is an example only and does not fit a final product. You need to analyze
     *          how your product is supposed to react in case of 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] 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(DEAD_BEEF, line_num, p_file_name);
    }
    
    /**@brief Clear bond information from persistent storage.
     */
    static void delete_bonds(void) {
      ret_code_t err_code;
    
      NRF_LOG_INFO("Erase bonds!");
    
      err_code = pm_peers_delete();
      APP_ERROR_CHECK(err_code);
    }
    
    void ble_tag_on_ble_evt(ble_evt_t const *p_ble_evt, void *p_context) {
      ble_tag_t *p_tag = (ble_tag_t *)p_context;
      ret_code_t err_code;
    
      if (p_tag == NULL || p_ble_evt == NULL) {
        return;
      }
    
      switch (p_ble_evt->header.evt_id) {
      case BLE_GAP_EVT_CONNECTED:
        
        p_tag->conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
        break;
    
      case BLE_GAP_EVT_DISCONNECTED:
         p_tag->conn_handle = BLE_CONN_HANDLE_INVALID;
         break;
    
      case BLE_GATTS_EVT_WRITE:
         break;
    
      default:
        break;
      }
    }
    
    /**@brief Function for starting advertising.
     */
    void advertising_start(bool erase_bonds) {
      ret_code_t err_code;
    
      if (erase_bonds) {
        delete_bonds();
      } else {
        err_code = sd_ble_gap_adv_start(m_adv_handle, APP_BLE_CONN_CFG_TAG);
        if (err_code != NRF_ERROR_INVALID_STATE &&
            err_code != NRF_ERROR_CONN_COUNT) {
          APP_ERROR_CHECK(err_code);
        }
      }
    
    }
    
    /**@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:
        advertising_start(false);
        break;
    
      default:
        break;
      }
    }
    
    /**@brief Function for handling the Battery measurement timer timeout.
     *
     * @details This function will be called each time the battery level measurement timer expires.
     *
     * @param[in] p_context  Pointer used for passing some arbitrary information (context) from the
     *                       app_start_timer() call to the timeout handler.
     */
    static void battery_level_meas_timeout_handler(void *p_context) {
      UNUSED_PARAMETER(p_context);
      // battery_level_update();
        if (!advertising_on) {
        NRF_LOG_INFO("Start advertising");
        advertising_start(NULL);
      } else {
        NRF_LOG_INFO("Stop advertising!!");
        (void)sd_ble_gap_adv_stop(m_adv_handle);
      }
      advertising_on = !advertising_on;
     
    }
    
    void advertising_stop(void) {
      ret_code_t err_code;
    
      err_code = sd_ble_gap_adv_stop(m_adv_handle);
      if (err_code != NRF_ERROR_INVALID_STATE &&
          err_code != NRF_SUCCESS) {
        APP_ERROR_CHECK(err_code);
      }
    
    }
    
    
    
    /**@brief Function for handling the Heart rate measurement timer timeout.
     *
     * @details This function will be called each time the heart rate measurement timer expires.
     *          It will exclude RR Interval data from every third measurement.
     *
     * @param[in] p_context  Pointer used for passing some arbitrary information (context) from the
     *                       app_start_timer() call to the timeout handler.
     */
    static void heart_rate_meas_timeout_handler(void *p_context) {
    
      UNUSED_PARAMETER(p_context);
     
    }
    
    /**@brief Function for the Timer initialization.
     *
     * @details Initializes the timer module. This creates and starts application timers.
     */
    static void timers_init(void) {
      ret_code_t err_code;
    
      // Initialize timer module.
      err_code = app_timer_init();
      APP_ERROR_CHECK(err_code);
    
      // Create timers.
      err_code = app_timer_create(&m_battery_timer_id,
          APP_TIMER_MODE_REPEATED,
          battery_level_meas_timeout_handler);
      APP_ERROR_CHECK(err_code);
    
      err_code = app_timer_create(&m_heart_rate_timer_id,
          APP_TIMER_MODE_REPEATED,
          heart_rate_meas_timeout_handler);
      APP_ERROR_CHECK(err_code);
    }
    
    /**@brief Function for the GAP initialization.
     *
     * @details This function sets up all the necessary GAP (Generic Access Profile) parameters of the
     *          device including the device name, appearance, and the preferred connection parameters.
     */
    static void gap_params_init(void) {
    
      ret_code_t err_code;
      ble_gap_conn_params_t gap_conn_params;
      ble_gap_conn_sec_mode_t sec_mode;
    
      BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode);
    
      memset(&gap_conn_params, 0, sizeof(gap_conn_params));
    
      gap_conn_params.min_conn_interval = MIN_CONN_INTERVAL;
      gap_conn_params.max_conn_interval = MAX_CONN_INTERVAL;
      gap_conn_params.conn_sup_timeout = CONN_SUP_TIMEOUT;
      gap_conn_params.slave_latency = SLAVE_LATENCY;
    
      err_code = sd_ble_gap_ppcp_set(&gap_conn_params);
      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);
    }
    
    /**@brief Function for handling Queued Write Module errors.
     *
     * @details A pointer to this function will be passed to each service which may need to inform the
     *          application about an error.
     *
     * @param[in]   nrf_error   Error code containing information about what went wrong.
     */
    static void nrf_qwr_error_handler(uint32_t nrf_error) {
      APP_ERROR_HANDLER(nrf_error);
    }
    
    static uint32_t custom_value_char_add(ble_tag_t *p_tag, const ble_tag_init_t *p_tag_init) {
      uint32_t err_code;
      ble_gatts_char_md_t char_md;
      ble_gatts_attr_md_t cccd_md;
      ble_gatts_attr_t attr_char_value;
      ble_uuid_t ble_uuid;
      ble_gatts_attr_md_t attr_md;
    
      memset(&cccd_md, 0, sizeof(cccd_md));
    
      BLE_GAP_CONN_SEC_MODE_SET_OPEN(&cccd_md.read_perm);
      BLE_GAP_CONN_SEC_MODE_SET_OPEN(&cccd_md.write_perm);
    
      cccd_md.vloc = BLE_GATTS_VLOC_STACK;
    
      memset(&char_md, 0, sizeof(char_md));
    
      char_md.char_props.notify = 0;
      char_md.char_props.read = 0;
      char_md.char_props.write = 1;
      char_md.p_char_user_desc = NULL;
      char_md.p_user_desc_md = NULL;
      char_md.p_cccd_md = &cccd_md;
      char_md.p_sccd_md = NULL;
    
      memset(&attr_md, 0, sizeof(attr_md));
    
      attr_md.read_perm = p_tag_init->custom_value_char_attr_md.read_perm;
      attr_md.write_perm = p_tag_init->custom_value_char_attr_md.write_perm;
      attr_md.vloc = BLE_GATTS_VLOC_STACK;
      attr_md.rd_auth = 0;
      attr_md.wr_auth = 0;
      attr_md.vlen = 0;
    
      ble_uuid.type = p_tag->uuid_type;
      ble_uuid.uuid = TICK_CHAR_UUID;
    
      memset(&attr_char_value, 0, sizeof(attr_char_value));
    
      attr_char_value.p_uuid = &ble_uuid;
      attr_char_value.p_attr_md = &attr_md;
      attr_char_value.init_len = 2;
      attr_char_value.init_offs = 0;
      attr_char_value.max_len = sizeof(uint16_t);
    
      err_code = sd_ble_gatts_characteristic_add(p_tag->service_handle,
          &char_md,
          &attr_char_value,
          &p_tag->tick_handle);
    
      ble_uuid.type = p_tag->uuid_type;
      ble_uuid.uuid = RATE_CHAR_UUID;
    
      memset(&attr_char_value, 0, sizeof(attr_char_value));
    
      attr_char_value.p_uuid = &ble_uuid;
      attr_char_value.p_attr_md = &attr_md;
      attr_char_value.init_len = 1;
      attr_char_value.init_offs = 0;
      attr_char_value.max_len = sizeof(uint8_t);
    
      err_code = sd_ble_gatts_characteristic_add(p_tag->service_handle,
          &char_md,
          &attr_char_value,
          &p_tag->rate_handle);
    
      memset(&char_md, 0, sizeof(char_md));
    
      char_md.char_props.write = 1;
      char_md.p_char_user_desc = NULL;
      char_md.p_user_desc_md = NULL;
      char_md.p_cccd_md = &cccd_md;
      char_md.p_sccd_md = NULL;
    
      ble_uuid.type = p_tag->uuid_type;
      ble_uuid.uuid = OWN_CHAR_UUID;
    
      memset(&attr_char_value, 0, sizeof(attr_char_value));
    
      attr_char_value.p_uuid = &ble_uuid;
      attr_char_value.p_attr_md = &attr_md;
      attr_char_value.init_len = 6;
      attr_char_value.init_offs = 0;
      attr_char_value.max_len = 6;
    
      err_code = sd_ble_gatts_characteristic_add(p_tag->service_handle,
          &char_md,
          &attr_char_value,
          &p_tag->own_handle);
    
      return err_code;
    }
    
    uint32_t ble_tag_init(ble_tag_t *p_tag, ble_tag_init_t const *p_tag_init) {
      if (p_tag == NULL || p_tag_init == NULL) {
        return NRF_ERROR_NULL;
      }
    
      memset(p_tag, 0, sizeof(*p_tag));
    
      uint32_t err_code;
      ble_uuid_t ble_uuid;
    
      p_tag->evt_handler = p_tag_init->evt_handler;
      p_tag->conn_handle = BLE_CONN_HANDLE_INVALID;
    
      const ble_uuid128_t base_uuid = TAG_UUID_BASE;
      err_code = sd_ble_uuid_vs_add(&base_uuid, &p_tag->uuid_type);
      VERIFY_SUCCESS(err_code);
    
      ble_uuid.uuid = TAG_SERVICE_UUID;
      ble_uuid.type = p_tag->uuid_type;
    
      err_code = sd_ble_gatts_service_add(BLE_GATTS_SRVC_TYPE_PRIMARY, &ble_uuid, &p_tag->service_handle);
      if (err_code != NRF_SUCCESS) {
        return err_code;
      }
    
      return custom_value_char_add(p_tag, p_tag_init);
    }
    
    static void on_tag_evt(ble_tag_t *p_tag_service,
        ble_tag_evt_t *p_evt) {
      switch (p_evt->evt_type) {
      case BLE_TAG_EVT_NOTIFICATION_ENABLED:
        break;
    
      case BLE_TAG_EVT_NOTIFICATION_DISABLED:
        break;
    
      case BLE_TAG_EVT_CONNECTED:
        break;
    
      case BLE_TAG_EVT_DISCONNECTED:
        break;
    
      default:
        break;
      }
    }
    
    /**@brief Function for initializing services that will be used by the application.
     *
     * @details Initialize the Heart Rate, Battery and Device Information services.
     */
    static void services_init(void) {
    
      ret_code_t err_code;
      nrf_ble_qwr_init_t qwr_init = {0};
      ble_tag_init_t tag_init;
    
      qwr_init.error_handler = nrf_qwr_error_handler;
    
      err_code = nrf_ble_qwr_init(&m_qwr, &qwr_init);
      APP_ERROR_CHECK(err_code);
    
      memset(&tag_init, 0, sizeof(tag_init));
    
      tag_init.evt_handler = on_tag_evt;
      tag_init.p_initial_measurements = NULL;
    
      BLE_GAP_CONN_SEC_MODE_SET_OPEN(&tag_init.custom_value_char_attr_md.read_perm);
      BLE_GAP_CONN_SEC_MODE_SET_OPEN(&tag_init.custom_value_char_attr_md.write_perm);
    
      err_code = ble_tag_init(&m_tag, &tag_init);
      APP_ERROR_CHECK(err_code);
    
    }
    
    
    
    /**@brief Function for starting application timers.
     */
    static void application_timers_start(void) {
      ret_code_t err_code;
    
      // Start application timers.
      err_code = app_timer_start(m_battery_timer_id, BATTERY_LEVEL_MEAS_INTERVAL, NULL);
      APP_ERROR_CHECK(err_code);
    
      err_code = app_timer_start(m_heart_rate_timer_id, HEART_RATE_MEAS_INTERVAL, NULL);
      APP_ERROR_CHECK(err_code);
    
    }
    
    /**@brief Function for handling the Connection Parameters Module.
     *
     * @details This function will be called for all events in the Connection Parameters Module which
     *          are passed to the application.
     *          @note All this function does is to disconnect. This could have been done by simply
     *                setting the disconnect_on_fail config parameter, but instead we use the event
     *                handler mechanism to demonstrate its use.
     *
     * @param[in] p_evt  Event received from the Connection Parameters Module.
     */
    static void on_conn_params_evt(ble_conn_params_evt_t *p_evt) {
      ret_code_t err_code;
    
      if (p_evt->evt_type == BLE_CONN_PARAMS_EVT_FAILED) {
        err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_CONN_INTERVAL_UNACCEPTABLE);
        APP_ERROR_CHECK(err_code);
      }
    }
    
    /**@brief Function for handling a Connection Parameters error.
     *
     * @param[in] nrf_error  Error code containing information about what went wrong.
     */
    static void conn_params_error_handler(uint32_t nrf_error) {
      APP_ERROR_HANDLER(nrf_error);
    }
    
    /**@brief Function for initializing the Connection Parameters module.
     */
    static void conn_params_init(void) {
      ret_code_t err_code;
      ble_conn_params_init_t cp_init;
    
      memset(&cp_init, 0, sizeof(cp_init));
    
      cp_init.p_conn_params = NULL;
      cp_init.first_conn_params_update_delay = FIRST_CONN_PARAMS_UPDATE_DELAY;
      cp_init.next_conn_params_update_delay = NEXT_CONN_PARAMS_UPDATE_DELAY;
      cp_init.max_conn_params_update_count = MAX_CONN_PARAMS_UPDATE_COUNT;
      cp_init.start_on_notify_cccd_handle = BLE_GATT_HANDLE_INVALID;
      cp_init.disconnect_on_fail = false;
      cp_init.evt_handler = on_conn_params_evt;
      cp_init.error_handler = conn_params_error_handler;
    
      err_code = ble_conn_params_init(&cp_init);
      APP_ERROR_CHECK(err_code);
    }
    
    /**@brief Function for putting the chip into sleep mode.
     *
     * @note This function will not return.
     */
    static void sleep_mode_enter(void) {
      ret_code_t err_code;
    #if 0
      err_code = bsp_indication_set(BSP_INDICATE_IDLE);
      APP_ERROR_CHECK(err_code);
    
      // Prepare wakeup buttons.
      err_code = bsp_btn_ble_sleep_mode_prepare();
      APP_ERROR_CHECK(err_code);
     #endif
    
      // Go to system-off mode (this function will not return; wakeup will cause a reset).
      err_code = sd_power_system_off();
      APP_ERROR_CHECK(err_code);
    }
    
    /**@brief Function for handling advertising events.
     *
     * @details This function will be called for advertising events which are passed to the application.
     *
     * @param[in] ble_adv_evt  Advertising event.
     */
    static void on_adv_evt(ble_adv_evt_t ble_adv_evt) {
      ret_code_t err_code;
    
      switch (ble_adv_evt) {
      case BLE_ADV_EVT_FAST:
        NRF_LOG_INFO("Fast advertising.");
        #if 0
        err_code = bsp_indication_set(BSP_INDICATE_ADVERTISING);
        APP_ERROR_CHECK(err_code);
        #endif
        break;
    
      case BLE_ADV_EVT_IDLE:
        // sleep_mode_enter();
        idle_state_handle();
        break;
    
      default:
        break;
      }
    }
    
    /**@brief Function for initializing the BLE stack.
     *
     * @details Initializes the SoftDevice and the BLE event interrupt.
     */
    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 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 initializing the Advertising functionality.
     */
    static void advertising_init(void) {
      ret_code_t err_code;
      ble_advdata_t advdata;
    
    
      uint8_t data[1] = {TAG_ADV_DATA_ID};
    
      memset(&manuf_data, 0, sizeof(manuf_data));
      manuf_data.company_identifier = 0xFFFF;
      manuf_data.data.p_data = data;
      manuf_data.data.size = 12; 
    
      memset(&advdata, 0, sizeof(advdata));
      
      advdata.p_manuf_specific_data = &manuf_data;
    
      err_code = ble_advdata_encode(&advdata, m_adv_data.adv_data.p_data, &m_adv_data.adv_data.len);
      APP_ERROR_CHECK(err_code);
    
      memset(&adv_params, 0, sizeof(adv_params));
    
      adv_params.primary_phy = BLE_GAP_PHY_1MBPS;
      adv_params.duration = APP_ADV_DURATION;
      adv_params.properties.type = BLE_GAP_ADV_TYPE_CONNECTABLE_SCANNABLE_UNDIRECTED;
      adv_params.p_peer_addr = NULL;
      adv_params.filter_policy = BLE_GAP_ADV_FP_ANY;
      adv_params.interval = APP_ADV_INTERVAL;
      adv_params.scan_req_notification = 1;
    
      err_code = sd_ble_gap_adv_set_configure(&m_adv_handle, &m_adv_data, &adv_params);
      APP_ERROR_CHECK(err_code);
    }
    
    /**@brief Function for initializing the nrf 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 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 If there is no pending log operation, then sleep until next the next event occurs.
     */
    static void idle_state_handle(void) {
      ret_code_t err_code;
    
      //   err_code = nrf_ble_lesc_request_handler();
      //  APP_ERROR_CHECK(err_code);
    
      if (NRF_LOG_PROCESS() == false) {
        nrf_pwr_mgmt_run();
        // sd_app_evt_wait();
      }
    }
    
    /**@brief Function for application main entry.
     */
    int main(void) {
      bool erase_bonds;
    
      // Initialize.
      log_init();
      timers_init();
      //  buttons_leds_init(&erase_bonds);
      power_management_init();
      ble_stack_init();
      gap_params_init();
      gatt_init();
    
      advertising_init();
      services_init();
      // sensor_simulator_init();
      conn_params_init();
      peer_manager_init();
    
      // Start execution.
      NRF_LOG_INFO("Heart Rate Sensor example started.");
    
      
      advertising_start(erase_bonds);
      application_timers_start();
    
      // Enter main loop.
      for (;;) {
        idle_state_handle();
        
      }
    }

    Thanks,

    Chitra

  • Thanks for posting the code! I tried it with the ble_app_hrs project in nRF SDK 17.0.2. Unfortunately, for some reason I'm not able replicate the high idle current you described. The sleep current was always the same before and after connection.

    Measurements with Power profiler kit:

    System ON Idle (sleep)

    Advertising @ 500 ms intervals with LDO regulator

    Connection @ 400 ms

    Test project

    nRF5_SDK17.0.2_ble_app_hrs_current.zip

    Once I connect and disconnect to the device using NrfConnect, the current is 30 Micro Amps and does not drop back to 3.2 Micro Amps.

     Try to turn off Bluetooth on the phone in case there is a chance that it may still be connected in the background.

    Best regards,

    Vidar

Related