Guest User

Untitled

a guest
Apr 28th, 2019
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 27.71 KB | None | 0 0
  1. /**
  2.  * Copyright (c) 2014 - 2019, Nordic Semiconductor ASA
  3.  *
  4.  * All rights reserved.
  5.  *
  6.  * Redistribution and use in source and binary forms, with or without modification,
  7.  * are permitted provided that the following conditions are met:
  8.  *
  9.  * 1. Redistributions of source code must retain the above copyright notice, this
  10.  *    list of conditions and the following disclaimer.
  11.  *
  12.  * 2. Redistributions in binary form, except as embedded into a Nordic
  13.  *    Semiconductor ASA integrated circuit in a product or a software update for
  14.  *    such product, must reproduce the above copyright notice, this list of
  15.  *    conditions and the following disclaimer in the documentation and/or other
  16.  *    materials provided with the distribution.
  17.  *
  18.  * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
  19.  *    contributors may be used to endorse or promote products derived from this
  20.  *    software without specific prior written permission.
  21.  *
  22.  * 4. This software, with or without modification, must only be used with a
  23.  *    Nordic Semiconductor ASA integrated circuit.
  24.  *
  25.  * 5. Any software provided in binary form under this license must not be reverse
  26.  *    engineered, decompiled, modified and/or disassembled.
  27.  *
  28.  * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
  29.  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  30.  * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
  31.  * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
  32.  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  33.  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  34.  * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  35.  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  36.  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  37.  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  38.  *
  39.  */
  40. /** @file
  41.  *
  42.  * @defgroup ble_sdk_app_template_main main.c
  43.  * @{
  44.  * @ingroup ble_sdk_app_template
  45.  * @brief Template project main file.
  46.  *
  47.  * This file contains a template for creating a new application. It has the code necessary to wakeup
  48.  * from button, advertise, get a connection restart advertising on disconnect and if no new
  49.  * connection created go back to system-off mode.
  50.  * It can easily be used as a starting point for creating a new application, the comments identified
  51.  * with 'YOUR_JOB' indicates where and how you can customize.
  52.  */
  53.  
  54. #include <stdbool.h>
  55. #include <stdint.h>
  56. #include <string.h>
  57.  
  58. #include "nordic_common.h"
  59. #include "nrf.h"
  60. #include "app_error.h"
  61. #include "ble.h"
  62. #include "ble_hci.h"
  63. #include "ble_srv_common.h"
  64. #include "ble_advdata.h"
  65. #include "ble_advertising.h"
  66. #include "ble_conn_params.h"
  67. #include "nrf_sdh.h"
  68. #include "nrf_sdh_soc.h"
  69. #include "nrf_sdh_ble.h"
  70. #include "app_timer.h"
  71. #include "fds.h"
  72. #include "peer_manager.h"
  73. #include "peer_manager_handler.h"
  74. #include "bsp_btn_ble.h"
  75. #include "sensorsim.h"
  76. #include "ble_conn_state.h"
  77. #include "nrf_ble_gatt.h"
  78. #include "nrf_ble_qwr.h"
  79. #include "nrf_pwr_mgmt.h"
  80.  
  81. #include "nrf_log.h"
  82. #include "nrf_log_ctrl.h"
  83. #include "nrf_log_default_backends.h"
  84. #include "ble_cus.h"
  85.  
  86.  
  87. #define DEVICE_NAME                     "MagiCoil"                       /**< Name of device. Will be included in the advertising data. */
  88. #define MANUFACTURER_NAME               "NordicSemiconductor"                   /**< Manufacturer. Will be passed to Device Information Service. */
  89. #define APP_ADV_INTERVAL                300                                     /**< The advertising interval (in units of 0.625 ms. This value corresponds to 187.5 ms). */
  90.  
  91. #define APP_ADV_DURATION                18000                                   /**< The advertising duration (180 seconds) in units of 10 milliseconds. */
  92. #define APP_BLE_OBSERVER_PRIO           3                                       /**< Application's BLE observer priority. You shouldn't need to modify this value. */
  93. #define APP_BLE_CONN_CFG_TAG            1                                       /**< A tag identifying the SoftDevice BLE configuration. */
  94.  
  95. #define CONN_INTERVAL_DEFAULT           (uint16_t)(MSEC_TO_UNITS(7.5, UNIT_1_25_MS))
  96. #define MIN_CONN_INTERVAL               (uint16_t)(MSEC_TO_UNITS(7.5, UNIT_1_25_MS))    /**< Minimum acceptable connection interval, in units of 1.25 ms. */
  97. #define MAX_CONN_INTERVAL               (uint16_t)(MSEC_TO_UNITS(500, UNIT_1_25_MS))    /**< Maximum acceptable connection interval, in units of 1.25 ms. */
  98. #define CONN_SUP_TIMEOUT                (uint16_t)(MSEC_TO_UNITS(4000,  UNIT_10_MS))    /**< Connection supervisory timeout (4 seconds). */
  99. #define SLAVE_LATENCY 0
  100.  
  101. #define DATA_LENGTH_DEFAULT 27
  102. #define DATA_LENGTH_MAX 251
  103.  
  104. #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). */
  105. #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). */
  106. #define MAX_CONN_PARAMS_UPDATE_COUNT    3                                       /**< Number of attempts before giving up the connection parameter negotiation. */
  107.  
  108. #define SEC_PARAM_BOND                  1                                       /**< Perform bonding. */
  109. #define SEC_PARAM_MITM                  0                                       /**< Man In The Middle protection not required. */
  110. #define SEC_PARAM_LESC                  0                                       /**< LE Secure Connections not enabled. */
  111. #define SEC_PARAM_KEYPRESS              0                                       /**< Keypress notifications not enabled. */
  112. #define SEC_PARAM_IO_CAPABILITIES       BLE_GAP_IO_CAPS_NONE                    /**< No I/O capabilities. */
  113. #define SEC_PARAM_OOB                   0                                       /**< Out Of Band data not available. */
  114. #define SEC_PARAM_MIN_KEY_SIZE          7                                       /**< Minimum encryption key size. */
  115. #define SEC_PARAM_MAX_KEY_SIZE          16                                      /**< Maximum encryption key size. */
  116.  
  117. #define DEAD_BEEF                       0xDEADBEEF                              /**< Value used as error code on stack dump, can be used to identify stack location on stack unwind. */
  118.  
  119. NRF_BLE_GATT_DEF(m_gatt);                                                       /**< GATT module instance. */
  120. NRF_BLE_QWR_DEF(m_qwr);                                                         /**< Context for the Queued Write module.*/
  121. BLE_CUS_DEF(m_cus);
  122. BLE_ADVERTISING_DEF(m_advertising);                                             /**< Advertising module instance. */
  123.  
  124. static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID;                        /**< Handle of the current connection. */
  125.  
  126. /* YOUR_JOB: Declare all services structure your application is using
  127.  *  BLE_XYZ_DEF(m_xyz);
  128.  */
  129.  
  130. // YOUR_JOB: Use UUIDs for service(s) used in your application.
  131. static ble_uuid_t m_adv_uuids[] =                                               /**< Universally unique service identifiers. */
  132. {
  133.     {BLE_UUID_DEVICE_INFORMATION_SERVICE, BLE_UUID_TYPE_BLE}
  134. };
  135.  
  136.  
  137. static void advertising_start(bool erase_bonds);
  138.  
  139.  
  140. /**@brief Callback function for asserts in the SoftDevice.
  141.  *
  142.  * @details This function will be called in case of an assert in the SoftDevice.
  143.  *
  144.  * @warning This handler is an example only and does not fit a final product. You need to analyze
  145.  *          how your product is supposed to react in case of Assert.
  146.  * @warning On assert from the SoftDevice, the system can only recover on reset.
  147.  *
  148.  * @param[in] line_num   Line number of the failing ASSERT call.
  149.  * @param[in] file_name  File name of the failing ASSERT call.
  150.  */
  151. void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name)
  152. {
  153.     app_error_handler(DEAD_BEEF, line_num, p_file_name);
  154. }
  155.  
  156.  
  157. /**@brief Function for handling Peer Manager events.
  158.  *
  159.  * @param[in] p_evt  Peer Manager event.
  160.  */
  161. static void pm_evt_handler(pm_evt_t const * p_evt)
  162. {
  163.     pm_handler_on_pm_evt(p_evt);
  164.     pm_handler_flash_clean(p_evt);
  165.  
  166.     switch (p_evt->evt_id)
  167.     {
  168.         case PM_EVT_PEERS_DELETE_SUCCEEDED:
  169.             advertising_start(false);
  170.             break;
  171.  
  172.         default:
  173.             break;
  174.     }
  175. }
  176.  
  177.  
  178. /**@brief Function for the Timer initialization.
  179.  *
  180.  * @details Initializes the timer module. This creates and starts application timers.
  181.  */
  182. static void timers_init(void)
  183. {
  184.     // Initialize timer module.
  185.     ret_code_t err_code = app_timer_init();
  186.     APP_ERROR_CHECK(err_code);
  187.  
  188.     // Create timers.
  189.  
  190.     /* YOUR_JOB: Create any timers to be used by the application.
  191.                  Below is an example of how to create a timer.
  192.                  For every new timer needed, increase the value of the macro APP_TIMER_MAX_TIMERS by
  193.                  one.
  194.        ret_code_t err_code;
  195.        err_code = app_timer_create(&m_app_timer_id, APP_TIMER_MODE_REPEATED, timer_timeout_handler);
  196.        APP_ERROR_CHECK(err_code); */
  197. }
  198.  
  199.  
  200. /**@brief Function for the GAP initialization.
  201.  *
  202.  * @details This function sets up all the necessary GAP (Generic Access Profile) parameters of the
  203.  *          device including the device name, appearance, and the preferred connection parameters.
  204.  */
  205. static void gap_params_init(void)
  206. {
  207.     ret_code_t              err_code;
  208.     ble_gap_conn_params_t   gap_conn_params;
  209.     ble_gap_conn_sec_mode_t sec_mode;
  210.  
  211.     BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode);
  212.  
  213.     err_code = sd_ble_gap_device_name_set(&sec_mode,
  214.                                           (const uint8_t *)DEVICE_NAME,
  215.                                           strlen(DEVICE_NAME));
  216.     APP_ERROR_CHECK(err_code);
  217.  
  218.     /* YOUR_JOB: Use an appearance value matching the application's use case.
  219.        err_code = sd_ble_gap_appearance_set(BLE_APPEARANCE_);
  220.        APP_ERROR_CHECK(err_code); */
  221.  
  222.     memset(&gap_conn_params, 0, sizeof(gap_conn_params));
  223.  
  224.     gap_conn_params.min_conn_interval = MIN_CONN_INTERVAL;
  225.     gap_conn_params.max_conn_interval = MAX_CONN_INTERVAL;
  226.     gap_conn_params.slave_latency     = SLAVE_LATENCY;
  227.     gap_conn_params.conn_sup_timeout  = CONN_SUP_TIMEOUT;
  228.  
  229.     err_code = sd_ble_gap_ppcp_set(&gap_conn_params);
  230.    
  231.     APP_ERROR_CHECK(err_code);
  232. }
  233.  
  234. void gatt_evt_handler(nrf_ble_gatt_t * p_gatt, nrf_ble_gatt_evt_t const * p_evt)
  235. {
  236.     if ((p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED))
  237.     {
  238.         printf("MTU size is set to %d", p_evt->params.att_mtu_effective);
  239.     }
  240.  
  241.     if ( (p_evt->evt_id == NRF_BLE_GATT_EVT_DATA_LENGTH_UPDATED))
  242.     {
  243.          printf("LL packet size is set to %d", p_gatt->data_length);
  244.     }
  245. }
  246.  
  247. /**@brief Function for initializing the GATT module.
  248.  */
  249. static void gatt_init(void)
  250. {  
  251.     ret_code_t err_code = nrf_ble_gatt_init(&m_gatt, gatt_evt_handler);
  252.     printf("GATT SUCCESS: %d\n",err_code);
  253.     APP_ERROR_CHECK(err_code);
  254.  
  255.     //nrf_ble_gatt_data_length_set(&m_gatt, BLE_CONN_HANDLE_INVALID, 251);
  256.     nrf_ble_gatt_att_mtu_periph_set(&m_gatt, 247);
  257.     //nrf_ble_gatt_att_mtu_central_set(&m_gatt, 247);
  258.  
  259. }
  260.  
  261.  
  262.  
  263.  
  264. /**@brief Function for handling Queued Write Module errors.
  265.  *
  266.  * @details A pointer to this function will be passed to each service which may need to inform the
  267.  *          application about an error.
  268.  *
  269.  * @param[in]   nrf_error   Error code containing information about what went wrong.
  270.  */
  271. static void nrf_qwr_error_handler(uint32_t nrf_error)
  272. {
  273.     APP_ERROR_HANDLER(nrf_error);
  274. }
  275.  
  276.  
  277. /**@brief Function for handling the YYY Service events.
  278.  * YOUR_JOB implement a service handler function depending on the event the service you are using can generate
  279.  *
  280.  * @details This function will be called for all YY Service events which are passed to
  281.  *          the application.
  282.  *
  283.  * @param[in]   p_yy_service   YY Service structure.
  284.  * @param[in]   p_evt          Event received from the YY Service.
  285.  *
  286.  *
  287. static void on_yys_evt(ble_yy_service_t     * p_yy_service,
  288.                        ble_yy_service_evt_t * p_evt)
  289. {
  290.     switch (p_evt->evt_type)
  291.     {
  292.         case BLE_YY_NAME_EVT_WRITE:
  293.             APPL_LOG("[APPL]: charact written with value %s. ", p_evt->params.char_xx.value.p_str);
  294.             break;
  295.  
  296.         default:
  297.             // No implementation needed.
  298.             break;
  299.     }
  300. }
  301. */
  302.  
  303. static void on_cus_evt(ble_cus_t     * p_cus_service,
  304.                        ble_cus_evt_t * p_evt)
  305. {
  306.    
  307. }
  308.  
  309. /**@brief Function for initializing services that will be used by the application.
  310.  */
  311. static void services_init(void)
  312. {
  313.        ret_code_t          err_code;
  314.         nrf_ble_qwr_init_t  qwr_init = {0};
  315.         ble_cus_init_t      cus_init = {0};
  316.  
  317.         // Initialize Queued Write Module.
  318.         qwr_init.error_handler = nrf_qwr_error_handler;
  319.  
  320.         err_code = nrf_ble_qwr_init(&m_qwr, &qwr_init);
  321.         APP_ERROR_CHECK(err_code);
  322.  
  323.          // Initialize CUS Service init structure to zero.
  324.         cus_init.evt_handler                = on_cus_evt;
  325.    
  326.         BLE_GAP_CONN_SEC_MODE_SET_OPEN(&cus_init.custom_value_char_attr_md.cccd_write_perm);
  327.         BLE_GAP_CONN_SEC_MODE_SET_OPEN(&cus_init.custom_value_char_attr_md.read_perm);
  328.         BLE_GAP_CONN_SEC_MODE_SET_OPEN(&cus_init.custom_value_char_attr_md.write_perm);
  329.    
  330.         err_code = ble_cus_init(&m_cus, &cus_init);
  331.         APP_ERROR_CHECK(err_code);
  332.  
  333.     /* YOUR_JOB: Add code to initialize the services used by the application.
  334.        ble_xxs_init_t                     xxs_init;
  335.        ble_yys_init_t                     yys_init;
  336.  
  337.        // Initialize XXX Service.
  338.        memset(&xxs_init, 0, sizeof(xxs_init));
  339.  
  340.        xxs_init.evt_handler                = NULL;
  341.        xxs_init.is_xxx_notify_supported    = true;
  342.        xxs_init.ble_xx_initial_value.level = 100;
  343.  
  344.        err_code = ble_bas_init(&m_xxs, &xxs_init);
  345.        APP_ERROR_CHECK(err_code);
  346.  
  347.        // Initialize YYY Service.
  348.        memset(&yys_init, 0, sizeof(yys_init));
  349.        yys_init.evt_handler                  = on_yys_evt;
  350.        yys_init.ble_yy_initial_value.counter = 0;
  351.  
  352.        err_code = ble_yy_service_init(&yys_init, &yy_init);
  353.        APP_ERROR_CHECK(err_code);
  354.      */
  355. }
  356.  
  357.  
  358. /**@brief Function for handling the Connection Parameters Module.
  359.  *
  360.  * @details This function will be called for all events in the Connection Parameters Module which
  361.  *          are passed to the application.
  362.  *          @note All this function does is to disconnect. This could have been done by simply
  363.  *                setting the disconnect_on_fail config parameter, but instead we use the event
  364.  *                handler mechanism to demonstrate its use.
  365.  *
  366.  * @param[in] p_evt  Event received from the Connection Parameters Module.
  367.  */
  368. static void on_conn_params_evt(ble_conn_params_evt_t * p_evt)
  369. {
  370.     ret_code_t err_code;
  371.  
  372.     if (p_evt->evt_type == BLE_CONN_PARAMS_EVT_FAILED)
  373.     {
  374.         err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_CONN_INTERVAL_UNACCEPTABLE);
  375.         APP_ERROR_CHECK(err_code);
  376.     }
  377. }
  378.  
  379.  
  380. /**@brief Function for handling a Connection Parameters error.
  381.  *
  382.  * @param[in] nrf_error  Error code containing information about what went wrong.
  383.  */
  384. static void conn_params_error_handler(uint32_t nrf_error)
  385. {
  386.     APP_ERROR_HANDLER(nrf_error);
  387. }
  388.  
  389.  
  390. /**@brief Function for initializing the Connection Parameters module.
  391.  */
  392. static void conn_params_init(void)
  393. {
  394.     ret_code_t             err_code;
  395.     ble_conn_params_init_t cp_init;
  396.  
  397.     memset(&cp_init, 0, sizeof(cp_init));
  398.  
  399.     cp_init.p_conn_params                  = NULL;
  400.     cp_init.first_conn_params_update_delay = FIRST_CONN_PARAMS_UPDATE_DELAY;
  401.     cp_init.next_conn_params_update_delay  = NEXT_CONN_PARAMS_UPDATE_DELAY;
  402.     cp_init.max_conn_params_update_count   = MAX_CONN_PARAMS_UPDATE_COUNT;
  403.     cp_init.start_on_notify_cccd_handle    = BLE_GATT_HANDLE_INVALID;
  404.     cp_init.disconnect_on_fail             = false;
  405.     cp_init.evt_handler                    = on_conn_params_evt;
  406.     cp_init.error_handler                  = conn_params_error_handler;
  407.  
  408.     err_code = ble_conn_params_init(&cp_init);
  409.     APP_ERROR_CHECK(err_code);
  410. }
  411.  
  412.  
  413. /**@brief Function for starting timers.
  414.  */
  415. static void application_timers_start(void)
  416. {
  417.     /* YOUR_JOB: Start your timers. below is an example of how to start a timer.
  418.        ret_code_t err_code;
  419.        err_code = app_timer_start(m_app_timer_id, TIMER_INTERVAL, NULL);
  420.        APP_ERROR_CHECK(err_code); */
  421.  
  422. }
  423.  
  424.  
  425. /**@brief Function for putting the chip into sleep mode.
  426.  *
  427.  * @note This function will not return.
  428.  */
  429. static void sleep_mode_enter(void)
  430. {
  431.     ret_code_t err_code;
  432.  
  433.     err_code = bsp_indication_set(BSP_INDICATE_IDLE);
  434.     APP_ERROR_CHECK(err_code);
  435.  
  436.     // Prepare wakeup buttons.
  437.     err_code = bsp_btn_ble_sleep_mode_prepare();
  438.     APP_ERROR_CHECK(err_code);
  439.  
  440.     // Go to system-off mode (this function will not return; wakeup will cause a reset).
  441.     err_code = sd_power_system_off();
  442.     APP_ERROR_CHECK(err_code);
  443. }
  444.  
  445.  
  446. /**@brief Function for handling advertising events.
  447.  *
  448.  * @details This function will be called for advertising events which are passed to the application.
  449.  *
  450.  * @param[in] ble_adv_evt  Advertising event.
  451.  */
  452. static void on_adv_evt(ble_adv_evt_t ble_adv_evt)
  453. {
  454.     ret_code_t err_code;
  455.  
  456.     switch (ble_adv_evt)
  457.     {
  458.         case BLE_ADV_EVT_FAST:
  459.             NRF_LOG_INFO("Fast advertising.");
  460.             err_code = bsp_indication_set(BSP_INDICATE_ADVERTISING);
  461.             APP_ERROR_CHECK(err_code);
  462.             break;
  463.  
  464.         case BLE_ADV_EVT_IDLE:
  465.             sleep_mode_enter();
  466.             break;
  467.  
  468.         default:
  469.             break;
  470.     }
  471. }
  472.  
  473.  
  474. /**@brief Function for handling BLE events.
  475.  *
  476.  * @param[in]   p_ble_evt   Bluetooth stack event.
  477.  * @param[in]   p_context   Unused.
  478.  */
  479. static void ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context)
  480. {
  481.     ret_code_t err_code = NRF_SUCCESS;
  482.  
  483.     switch (p_ble_evt->header.evt_id)
  484.     {
  485.         case BLE_GAP_EVT_DISCONNECTED:
  486.             NRF_LOG_INFO("Disconnected.");
  487.             // LED indication will be changed when advertising starts.
  488.             break;
  489.  
  490.         case BLE_GAP_EVT_CONNECTED:
  491.             NRF_LOG_INFO("Connected.");
  492.  
  493.             ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
  494.             m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
  495.  
  496.             sd_ble_gap_phy_update(p_gap_evt->conn_handle, BLE_GAP_PHY_2MBPS | BLE_GAP_PHY_1MBPS);
  497.  
  498.             /*err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
  499.             APP_ERROR_CHECK(err_code);
  500.            
  501.             err_code = nrf_ble_qwr_conn_handle_assign(&m_qwr, m_conn_handle);
  502.             APP_ERROR_CHECK(err_code);
  503.  
  504.             //err_code = nrf_ble_gatt_data_length_set(&m_gatt, BLE_CONN_HANDLE_INVALID, 244);
  505.             //printf("data_length update code: %d",err_code);*/
  506.  
  507.  
  508.             break;
  509.         case BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST:
  510.             printf("mtu request\n");
  511.             sd_ble_gatts_exchange_mtu_reply(p_ble_evt->evt.gap_evt.conn_handle, 247);
  512.             break;
  513.         case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
  514.         {
  515.             ble_gap_conn_params_t params;
  516.             params = p_gap_evt->params.conn_param_update_request.conn_params;
  517.             err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle, &params);
  518.             APP_ERROR_CHECK(err_code);
  519.         } break;
  520.  
  521.         case BLE_GATTC_EVT_TIMEOUT:
  522.             // Disconnect on GATT Client timeout event.
  523.             NRF_LOG_DEBUG("GATT Client Timeout.");
  524.             err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
  525.                                              BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  526.             APP_ERROR_CHECK(err_code);
  527.             break;
  528.  
  529.         case BLE_GATTS_EVT_TIMEOUT:
  530.             // Disconnect on GATT Server timeout event.
  531.             NRF_LOG_DEBUG("GATT Server Timeout.");
  532.             err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
  533.                                              BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  534.             APP_ERROR_CHECK(err_code);
  535.             break;
  536.         case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
  537.             err_code = sd_ble_gap_phy_update(p_gap_evt->conn_handle, BLE_GAP_PHY_2MBPS | BLE_GAP_PHY_1MBPS);
  538.             break;
  539.         default:
  540.             // No implementation needed.
  541.             break;
  542.     }
  543. }
  544. void data_len_set(uint8_t value)
  545. {
  546.     ret_code_t err_code;
  547.     err_code = nrf_ble_gatt_data_length_set(&m_gatt, BLE_CONN_HANDLE_INVALID, value);
  548.     printf("Updating length: %d",err_code);
  549.     APP_ERROR_CHECK(err_code);
  550. }
  551.  
  552. /**@brief Function for initializing the BLE stack.
  553.  *
  554.  * @details Initializes the SoftDevice and the BLE event interrupt.
  555.  */
  556. static void ble_stack_init(void)
  557. {
  558.     ret_code_t err_code;
  559.  
  560.     err_code = nrf_sdh_enable_request();
  561.     APP_ERROR_CHECK(err_code);
  562.  
  563.     // Configure the BLE stack using the default settings.
  564.     // Fetch the start address of the application RAM.
  565.     uint32_t ram_start = 0;
  566.     err_code = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &ram_start);
  567.     printf("defaults: %d\n",err_code);
  568.     //APP_ERROR_CHECK(err_code);
  569.  
  570.     // Update perhiperal
  571.  
  572.     // Enable BLE stack.
  573.     err_code = nrf_sdh_ble_enable(&ram_start);
  574.     APP_ERROR_CHECK(err_code);
  575.     // Register a handler for BLE events.
  576.     NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, ble_evt_handler, NULL);
  577.  
  578. }
  579.  
  580. void gatt_mtu_set(uint16_t att_mtu)
  581. {
  582.     ret_code_t err_code;
  583.  
  584.     //m_test_params.att_mtu = att_mtu;
  585.  
  586.     err_code = nrf_ble_gatt_att_mtu_periph_set(&m_gatt, att_mtu);
  587.     APP_ERROR_CHECK(err_code);
  588.  
  589.     //err_code = nrf_ble_gatt_att_mtu_central_set(&m_gatt, att_mtu);
  590.     //APP_ERROR_CHECK(err_code);
  591. }
  592.  
  593.  
  594.  
  595. /**@brief Function for the Peer Manager initialization.
  596.  */
  597. static void peer_manager_init(void)
  598. {
  599.     ble_gap_sec_params_t sec_param;
  600.     ret_code_t           err_code;
  601.  
  602.     err_code = pm_init();
  603.     APP_ERROR_CHECK(err_code);
  604.  
  605.     memset(&sec_param, 0, sizeof(ble_gap_sec_params_t));
  606.  
  607.     // Security parameters to be used for all security procedures.
  608.     sec_param.bond           = SEC_PARAM_BOND;
  609.     sec_param.mitm           = SEC_PARAM_MITM;
  610.     sec_param.lesc           = SEC_PARAM_LESC;
  611.     sec_param.keypress       = SEC_PARAM_KEYPRESS;
  612.     sec_param.io_caps        = SEC_PARAM_IO_CAPABILITIES;
  613.     sec_param.oob            = SEC_PARAM_OOB;
  614.     sec_param.min_key_size   = SEC_PARAM_MIN_KEY_SIZE;
  615.     sec_param.max_key_size   = SEC_PARAM_MAX_KEY_SIZE;
  616.     sec_param.kdist_own.enc  = 1;
  617.     sec_param.kdist_own.id   = 1;
  618.     sec_param.kdist_peer.enc = 1;
  619.     sec_param.kdist_peer.id  = 1;
  620.  
  621.     err_code = pm_sec_params_set(&sec_param);
  622.     APP_ERROR_CHECK(err_code);
  623.  
  624.     err_code = pm_register(pm_evt_handler);
  625.     APP_ERROR_CHECK(err_code);
  626. }
  627.  
  628.  
  629. /**@brief Clear bond information from persistent storage.
  630.  */
  631. static void delete_bonds(void)
  632. {
  633.     ret_code_t err_code;
  634.  
  635.     NRF_LOG_INFO("Erase bonds!");
  636.  
  637.     err_code = pm_peers_delete();
  638.     APP_ERROR_CHECK(err_code);
  639. }
  640.  
  641.  
  642. /**@brief Function for handling events from the BSP module.
  643.  *
  644.  * @param[in]   event   Event generated when button is pressed.
  645.  */
  646. static void bsp_event_handler(bsp_event_t event)
  647. {
  648.     ret_code_t err_code;
  649.  
  650.     switch (event)
  651.     {
  652.         case BSP_EVENT_SLEEP:
  653.             sleep_mode_enter();
  654.             break; // BSP_EVENT_SLEEP
  655.  
  656.         case BSP_EVENT_DISCONNECT:
  657.             err_code = sd_ble_gap_disconnect(m_conn_handle,
  658.                                              BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  659.             if (err_code != NRF_ERROR_INVALID_STATE)
  660.             {
  661.                 APP_ERROR_CHECK(err_code);
  662.             }
  663.             break; // BSP_EVENT_DISCONNECT
  664.  
  665.         case BSP_EVENT_WHITELIST_OFF:
  666.             if (m_conn_handle == BLE_CONN_HANDLE_INVALID)
  667.             {
  668.                 err_code = ble_advertising_restart_without_whitelist(&m_advertising);
  669.                 if (err_code != NRF_ERROR_INVALID_STATE)
  670.                 {
  671.                     APP_ERROR_CHECK(err_code);
  672.                 }
  673.             }
  674.             break; // BSP_EVENT_KEY_0
  675.  
  676.         default:
  677.             break;
  678.     }
  679. }
  680.  
  681.  
  682. /**@brief Function for initializing the Advertising functionality.
  683.  */
  684. static void advertising_init(void)
  685. {
  686.     ret_code_t             err_code;
  687.     ble_advertising_init_t init;
  688.  
  689.     memset(&init, 0, sizeof(init));
  690.  
  691.     init.advdata.name_type               = BLE_ADVDATA_FULL_NAME;
  692.     init.advdata.include_appearance      = true;
  693.     init.advdata.flags                   = BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE;
  694.     init.advdata.uuids_complete.uuid_cnt = sizeof(m_adv_uuids) / sizeof(m_adv_uuids[0]);
  695.     init.advdata.uuids_complete.p_uuids  = m_adv_uuids;
  696.  
  697.     init.config.ble_adv_fast_enabled  = true;
  698.     init.config.ble_adv_fast_interval = APP_ADV_INTERVAL;
  699.     init.config.ble_adv_fast_timeout  = APP_ADV_DURATION;
  700.  
  701.     init.evt_handler = on_adv_evt;
  702.  
  703.     err_code = ble_advertising_init(&m_advertising, &init);
  704.     APP_ERROR_CHECK(err_code);
  705.  
  706.     ble_advertising_conn_cfg_tag_set(&m_advertising, APP_BLE_CONN_CFG_TAG);
  707. }
  708.  
  709.  
  710. /**@brief Function for initializing buttons and leds.
  711.  *
  712.  * @param[out] p_erase_bonds  Will be true if the clear bonding button was pressed to wake the application up.
  713.  */
  714. static void buttons_leds_init(bool * p_erase_bonds)
  715. {
  716.     ret_code_t err_code;
  717.     bsp_event_t startup_event;
  718.  
  719.     err_code = bsp_init(BSP_INIT_LEDS | BSP_INIT_BUTTONS, bsp_event_handler);
  720.     APP_ERROR_CHECK(err_code);
  721.  
  722.     err_code = bsp_btn_ble_init(NULL, &startup_event);
  723.     APP_ERROR_CHECK(err_code);
  724.  
  725.     *p_erase_bonds = (startup_event == BSP_EVENT_CLEAR_BONDING_DATA);
  726. }
  727.  
  728.  
  729. /**@brief Function for initializing the nrf log module.
  730.  */
  731. static void log_init(void)
  732. {
  733.     ret_code_t err_code = NRF_LOG_INIT(NULL);
  734.     APP_ERROR_CHECK(err_code);
  735.  
  736.     NRF_LOG_DEFAULT_BACKENDS_INIT();
  737. }
  738.  
  739.  
  740. /**@brief Function for initializing power management.
  741.  */
  742. static void power_management_init(void)
  743. {
  744.     ret_code_t err_code;
  745.     err_code = nrf_pwr_mgmt_init();
  746.     APP_ERROR_CHECK(err_code);
  747. }
  748.  
  749.  
  750. /**@brief Function for handling the idle state (main loop).
  751.  *
  752.  * @details If there is no pending log operation, then sleep until next the next event occurs.
  753.  */
  754. static void idle_state_handle(void)
  755. {
  756.     if (NRF_LOG_PROCESS() == false)
  757.     {
  758.         nrf_pwr_mgmt_run();
  759.     }
  760. }
  761.  
  762.  
  763. /**@brief Function for starting advertising.
  764.  */
  765. static void advertising_start(bool erase_bonds)
  766. {
  767.     if (erase_bonds == true)
  768.     {
  769.         delete_bonds();
  770.         // Advertising is started by PM_EVT_PEERS_DELETED_SUCEEDED event
  771.     }
  772.     else
  773.     {
  774.         ret_code_t err_code = ble_advertising_start(&m_advertising, BLE_ADV_MODE_FAST);
  775.  
  776.         APP_ERROR_CHECK(err_code);
  777.     }
  778. }
  779.  
  780.  
  781. /**@brief Function for application main entry.
  782.  */
  783. int main(void)
  784. {
  785.     bool erase_bonds;
  786.  
  787.     // Initialize.
  788.     log_init();
  789.     timers_init();
  790.     buttons_leds_init(&erase_bonds);
  791.     power_management_init();
  792.     ble_stack_init();
  793.     gap_params_init();
  794.     gatt_init();
  795.     advertising_init();
  796.     services_init();
  797.     conn_params_init();
  798.     peer_manager_init();
  799.  
  800.     // Start execution.
  801.     NRF_LOG_INFO("Template example started.");
  802.     application_timers_start();
  803.  
  804.     data_len_set(251);
  805.  
  806.     ble_opt_t opt;
  807.     memset(&opt, 0x00, sizeof(opt));
  808.     opt.common_opt.conn_evt_ext.enable = 1;
  809.     sd_ble_opt_set(BLE_COMMON_OPT_CONN_EVT_EXT, &opt);
  810.  
  811.  
  812.  
  813.     advertising_start(erase_bonds);
  814.  
  815.     // Enter main loop.
  816.     for (;;)
  817.     {
  818.         idle_state_handle();
  819.     }
  820. }
  821.  
  822.  
  823. /**
  824.  * @}
  825.  */
Add Comment
Please, Sign In to add comment