/Blinker/BlinkerBLE.c

https://github.com/blinker-iot/blinker-nRF52 · C · 1030 lines · 555 code · 193 blank · 282 comment · 40 complexity · cca63ed3c43316795d35f0b6d968c06e MD5 · raw file

  1. /**
  2. * Copyright (c) 2017 - 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. /** @brief GATT Service client example application main file.
  41. @details This file contains the main source code for a sample client application that uses the
  42. GATT Service. This client can be used to receive Service Changed indications. This is
  43. needed if your application interacts with GATT servers that modify, remove or add
  44. services. A typical course of action if a Service Changed indication is received is to
  45. rediscover the database on the peer device.
  46. For more information about the GATT Service, see "Defined Generic Attribute Profile Service"
  47. in Bluetooth Specification Version 5.0 Vol 3, Part G Section 7.
  48. */
  49. #include "BlinkerBle.h"
  50. #if NRF_MODULE_ENABLED(BLINKER_BLE)
  51. // #include "app_adv.h"
  52. #include "nordic_common.h"
  53. #include "nrf.h"
  54. #include "app_error.h"
  55. #include "ble.h"
  56. #include "ble_srv_common.h"
  57. #include "ble_advdata.h"
  58. #include "ble_advertising.h"
  59. #include "nrf_sdh.h"
  60. #include "nrf_sdh_soc.h"
  61. #include "nrf_sdh_ble.h"
  62. #include "app_timer.h"
  63. #include "bsp.h"
  64. #include "bsp_btn_ble.h"
  65. #include "nrf_ble_gatts_c.h"
  66. #include "boards.h"
  67. #include "ble_gap.h"
  68. #include "nrf_ble_gatt.h"
  69. #include "nrf_ble_qwr.h"
  70. #include "peer_manager.h"
  71. #include "peer_manager_handler.h"
  72. #include "fds.h"
  73. #include "ble_conn_state.h"
  74. #include "nrf_pwr_mgmt.h"
  75. #include "app_adv.h"
  76. #include "ble_advdata.h"
  77. #include "ble_advertising.h"
  78. #include "bsp.h"
  79. #include "peer_manager.h"
  80. #include "nrf_sdh.h"
  81. #include "nrf_sdh_soc.h"
  82. #include "nrf_sdh_ble.h"
  83. #include "nrf_log.h"
  84. #include "nrf_log_ctrl.h"
  85. #include "nrf_log_default_backends.h"
  86. #define APP_BLE_OBSERVER_PRIO 3 /**< Application's BLE observer priority. You shouldn't need to modify this value. */
  87. #define APP_BLE_CONN_CFG_TAG 1 /**< A tag identifying the SoftDevice BLE configuration. */
  88. #define DEAD_BEEF 0xDEADBEEF /**< Value used as error code on stack dump, can be used to identify stack location on stack unwind. */
  89. #define APP_ADV_FAST_INTERVAL 0x0028 /**< Fast advertising interval (in units of 0.625 ms. This value corresponds to 25 ms.). */
  90. #define APP_ADV_SLOW_INTERVAL 0x0C80 /**< Slow advertising interval (in units of 0.625 ms. This value corrsponds to 2 seconds). */
  91. #define APP_ADV_FAST_DURATION 0 /**< The advertising duration (180 seconds) in units of 10 milliseconds. */
  92. // #define APP_ADV_SLOW_DURATION 18000 /**< The advertising duration of slow advertising in units of 10 milliseconds. */
  93. #define MIN_CONN_INTERVAL MSEC_TO_UNITS(50, UNIT_1_25_MS) /**< Minimum acceptable connection interval (20 ms), Connection interval uses 1.25 ms units. */
  94. #define MAX_CONN_INTERVAL MSEC_TO_UNITS(100, UNIT_1_25_MS) /**< Maximum acceptable connection interval (75 ms), Connection interval uses 1.25 ms units. */
  95. #define SLAVE_LATENCY 0 /**< Slave latency. */
  96. #define CONN_SUP_TIMEOUT MSEC_TO_UNITS(4000, UNIT_10_MS) /**< Connection supervisory timeout (4 seconds), Supervision Timeout uses 10 ms units. */
  97. #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). */
  98. #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). */
  99. #define MAX_CONN_PARAMS_UPDATE_COUNT 3 /**< Number of attempts before giving up the connection parameter negotiation. */
  100. #define BTS_SERVICE_UUID_TYPE BLE_UUID_TYPE_VENDOR_BEGIN /**< UUID type for the Nordic UART Service (vendor specific). */
  101. #define APP_BLE_CONN_CFG_TAG 1 /**< A tag for a BLE stack configuration .*/
  102. #define APP_ADV_DURATION BLE_GAP_ADV_TIMEOUT_GENERAL_UNLIMITED /**< The advertising duration in units of 10 milliseconds. */
  103. BLE_BTS_DEF(m_bts, NRF_SDH_BLE_TOTAL_LINK_COUNT); /**< Link Loss service instance. */
  104. NRF_BLE_GATT_DEF(m_gatt); /**< GATT module instance. */
  105. NRF_BLE_GATTS_C_DEF(m_gatts_c); /**< GATT Service client instance. Handles Service Changed indications from the peer. */
  106. NRF_BLE_QWR_DEF(m_qwr); /**< Context for the Queued Write module.*/
  107. BLE_DB_DISCOVERY_DEF(m_ble_db_discovery); /**< DB discovery module instance. */
  108. NRF_BLE_GQ_DEF(m_ble_gatt_queue, /**< BLE GATT Queue instance. */
  109. NRF_SDH_BLE_PERIPHERAL_LINK_COUNT,
  110. NRF_BLE_GQ_QUEUE_SIZE);
  111. BLE_ADVERTISING_DEF(m_advertising); /**< Advertising module instance. */
  112. static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; /**< Handle of the current connection. */
  113. static uint16_t m_ble_bts_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - 3; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
  114. static bool m_erase_bonds; /**< Bool to determine if bonds should be erased before advertising starts. Based on button push upon startup. */
  115. static ble_uuid_t m_adv_uuids[] = /**< Universally unique service identifiers. */
  116. {
  117. {0xFFE0, BLE_UUID_TYPE_BLE},
  118. // {BLE_UUID_IMMEDIATE_ALERT_SERVICE, BLE_UUID_TYPE_BLE},
  119. // {BLE_UUID_BATTERY_SERVICE, BLE_UUID_TYPE_BLE},
  120. // // {BLE_UUID_TX_POWER_SERVICE, BLE_UUID_TYPE_BLE},
  121. // {BLE_UUID_LINK_LOSS_SERVICE, BLE_UUID_TYPE_BLE}
  122. };
  123. static uint8_t m_pm_peer_srv_buffer[ALIGN_NUM(4, sizeof(ble_gatt_db_srv_t))] = {0}; /**< Data written to flash by peer manager must be aligned on 4 bytes.
  124. When loading and storing we will treat this byte array as a ble_gatt_db_srv_t.
  125. We use a static variable because it is written asynchronously. */
  126. blinker_callback_with_string_arg_t blinker_parse_func = NULL;
  127. static bool ble_connect_state = false;
  128. static char ble_buf[BLINKER_MAX_READ_SIZE];
  129. static bool ble_fresh = false;
  130. static bool ble_avail = false;
  131. static uint32_t ble_buf_len;
  132. bool blinker_ble_connect(void) { return ble_connect_state; }
  133. bool blinker_ble_connected(void) { return ble_connect_state; }
  134. void blinker_ble_disconnect(void) { advertising_start(&m_erase_bonds); }
  135. bool blinker_ble_avaliable(void)
  136. {
  137. if (ble_avail)
  138. {
  139. ble_avail = false;
  140. return true;
  141. }
  142. else
  143. {
  144. return false;
  145. }
  146. }
  147. char * blinker_ble_lastread(void) { return ble_buf;}
  148. void blinker_ble_flush(void)
  149. {
  150. if (ble_fresh)
  151. {
  152. NRF_LOG_INFO("blinker ble flush");
  153. // free(ble_buf);
  154. ble_fresh = false;
  155. ble_avail = false;
  156. }
  157. }
  158. /**@brief Function for handling the data from the Nordic UART Service.
  159. *
  160. * @details This function will process the data received from the Nordic UART BLE Service and send
  161. * it to the UART module.
  162. *
  163. * @param[in] p_evt Nordic UART Service event.
  164. */
  165. /**@snippet [Handling the data received over BLE] */
  166. static void bts_data_handler(ble_bts_evt_t * p_evt)
  167. {
  168. if (p_evt->evt_type == BLE_BTS_EVT_RX_DATA)
  169. {
  170. // uint32_t err_code;
  171. if (p_evt->params.rx_data.length > 0)
  172. {
  173. // if (!ble_buf_len)
  174. // {
  175. // ble_buf = (char*)malloc((p_evt->params.rx_data.length + 1)*sizeof(char));
  176. // }
  177. // else
  178. // {
  179. // free(ble_buf);
  180. // ble_buf = (char*)malloc((p_evt->params.rx_data.length + 1)*sizeof(char));
  181. // }
  182. strcpy(ble_buf, p_evt->params.rx_data.p_data);
  183. ble_buf_len = p_evt->params.rx_data.length;
  184. ble_buf[ble_buf_len] = '\0';
  185. }
  186. ble_fresh = true;
  187. ble_avail = true;
  188. if (ble_buf[ble_buf_len - 1] == '\n') ble_buf[ble_buf_len - 1] = '\0';
  189. if (ble_buf[ble_buf_len - 2] == '\r') ble_buf[ble_buf_len - 2] = '\0';
  190. NRF_LOG_INFO("get data: %s, len: %d", ble_buf, ble_buf_len);
  191. // NRF_LOG_INFO("get data: %s, len: %d", p_evt->params.rx_data.p_data, p_evt->params.rx_data.length);
  192. // NRF_LOG_INFO("heap: %d", xPortGetFreeHeapSize());
  193. if (blinker_parse_func) blinker_parse_func(ble_buf);
  194. // NRF_LOG_DEBUG("Received data from BLE BTS. Writing data on UART.");
  195. // NRF_LOG_HEXDUMP_DEBUG(p_evt->params.rx_data.p_data, p_evt->params.rx_data.length);
  196. // for (uint32_t i = 0; i < p_evt->params.rx_data.length; i++)
  197. // {
  198. // do
  199. // {
  200. // err_code = app_uart_put(p_evt->params.rx_data.p_data[i]);
  201. // if ((err_code != NRF_SUCCESS) && (err_code != NRF_ERROR_BUSY))
  202. // {
  203. // NRF_LOG_ERROR("Failed receiving BTS message. Error 0x%x. ", err_code);
  204. // APP_ERROR_CHECK(err_code);
  205. // }
  206. // } while (err_code == NRF_ERROR_BUSY);
  207. // }
  208. // if (p_evt->params.rx_data.p_data[p_evt->params.rx_data.length - 1] == '\r')
  209. // {
  210. // while (app_uart_put('\n') == NRF_ERROR_BUSY);
  211. // }
  212. }
  213. // static uint8_t data_array[BLE_BTS_MAX_DATA_LEN];
  214. // static uint8_t index;
  215. // uint32_t err_code;
  216. // static char data_buf[BLE_BTS_MAX_DATA_LEN] = { 0 };
  217. // memcpy(data_buf, p_evt->params.rx_data.p_data, p_evt->params.rx_data.length);
  218. // strcpy(data_array, data_buf);
  219. // strcat(data_array, "\r\n");
  220. // NRF_LOG_INFO("bts_data_handler: %s, %d", data_buf, p_evt->params.rx_data.length);
  221. // index = p_evt->params.rx_data.length + 2;
  222. // NRF_LOG_INFO("bts_data_handler end");
  223. // if (index > 0)
  224. // {
  225. // if ((data_array[index - 1] == '\n') ||
  226. // (data_array[index - 1] == '\r') ||
  227. // (index >= m_ble_bts_max_data_len))
  228. // {
  229. // if (index > 1)
  230. // {
  231. // NRF_LOG_DEBUG("Ready to send data over BLE BTS");
  232. // NRF_LOG_HEXDUMP_DEBUG(data_array, index);
  233. // NRF_LOG_INFO("send data over BLE BTS: len: %d, %s", index, data_array);
  234. // do
  235. // {
  236. // NRF_LOG_INFO("m_conn_handle %d.", m_conn_handle);
  237. // uint16_t length = (uint16_t)index;
  238. // err_code = ble_bts_data_send(&m_bts, data_array, &length, m_conn_handle);
  239. // if ((err_code != NRF_ERROR_INVALID_STATE) &&
  240. // (err_code != NRF_ERROR_RESOURCES) &&
  241. // (err_code != NRF_ERROR_NOT_FOUND))
  242. // {
  243. // APP_ERROR_CHECK(err_code);
  244. // NRF_LOG_INFO("Failed...err_code: %d", err_code);
  245. // }
  246. // // blinker_ble_print(data_array, false);
  247. // } while (err_code == NRF_ERROR_RESOURCES);
  248. // // blinker_ble_print(data_array, false);
  249. // }
  250. // index = 0;
  251. // }
  252. // }
  253. }
  254. void blinker_ble_print(char * data, bool need_check)
  255. {
  256. NRF_LOG_INFO("response: %s, len: %d", data, strlen(data));
  257. if (ble_connect_state && strlen(data))
  258. {
  259. uint32_t err_code;
  260. uint16_t length = (uint16_t)strlen(data);
  261. uint16_t send_len = 0;
  262. uint8_t parts = length / 20 + 1;
  263. char s_send[23] = {0};
  264. for (uint8_t num = 0; num < parts; num++)
  265. {
  266. if ((num + 1) == parts)
  267. {
  268. blinker_substring(s_send, data, num*(20), length);
  269. send_len = length - num*(20);
  270. }
  271. else
  272. {
  273. blinker_substring(s_send, data, num*(20), (num+1)*20);
  274. send_len = 20;
  275. }
  276. do
  277. {
  278. err_code = ble_bts_data_send(&m_bts, s_send, &send_len, m_conn_handle);
  279. if ((err_code != NRF_ERROR_INVALID_STATE) &&
  280. (err_code != NRF_ERROR_RESOURCES) &&
  281. (err_code != NRF_ERROR_NOT_FOUND))
  282. {
  283. APP_ERROR_CHECK(err_code);
  284. }
  285. } while (err_code == NRF_ERROR_RESOURCES);
  286. }
  287. NRF_LOG_INFO("Success...");
  288. }
  289. else
  290. {
  291. NRF_LOG_INFO("Failed... Disconnected");
  292. }
  293. }
  294. /**@brief Function for handling advertising events.
  295. @details This function will be called for advertising events which are passed to the application.
  296. @param[in] ble_adv_evt Advertising event.
  297. */
  298. void on_adv_evt(ble_adv_evt_t ble_adv_evt)
  299. {
  300. ret_code_t err_code;
  301. switch (ble_adv_evt)
  302. {
  303. case BLE_ADV_EVT_FAST:
  304. NRF_LOG_INFO("Fast advertising.");
  305. err_code = bsp_indication_set(BSP_INDICATE_ADVERTISING);
  306. APP_ERROR_CHECK(err_code);
  307. break;
  308. case BLE_ADV_EVT_IDLE:
  309. NRF_LOG_INFO("Advertising stopped.");
  310. break;
  311. default:
  312. break;
  313. }
  314. }
  315. /**@brief Function for initializing the Advertising functionality.
  316. @details Encodes the required advertising data and passes it to the stack.
  317. Also builds a structure to be passed to the stack when starting advertising.
  318. */
  319. void advertising_init(void)
  320. {
  321. ret_code_t err_code;
  322. ble_advertising_init_t init;
  323. memset(&init, 0, sizeof(init));
  324. ble_gap_addr_t ble_addr;
  325. sd_ble_gap_addr_get(&ble_addr);
  326. // FICR->DEVICEADDR[x]
  327. ble_advdata_manuf_data_t manuf_data; //Variable to hold manufacturer specific data
  328. // uint8_t data[] = "blinker test!"; //Our data to advertise
  329. manuf_data.company_identifier = 0x4444; //Nordics company ID
  330. manuf_data.data.p_data = ble_addr.addr;//data;
  331. manuf_data.data.size = sizeof(ble_addr.addr);//sizeof(data);
  332. init.advdata.p_manuf_specific_data = &manuf_data;
  333. init.advdata.name_type = BLE_ADVDATA_FULL_NAME;
  334. init.advdata.include_appearance = true;
  335. init.advdata.flags = BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE;
  336. init.advdata.uuids_complete.uuid_cnt = sizeof(m_adv_uuids) / sizeof(m_adv_uuids[0]);
  337. init.advdata.uuids_complete.p_uuids = m_adv_uuids;
  338. init.config.ble_adv_fast_enabled = true;
  339. init.config.ble_adv_fast_interval = ADV_INTERVAL;
  340. init.config.ble_adv_fast_timeout = APP_ADV_DURATION;
  341. init.evt_handler = on_adv_evt;
  342. err_code = ble_advertising_init(&m_advertising, &init);
  343. APP_ERROR_CHECK(err_code);
  344. ble_advertising_conn_cfg_tag_set(&m_advertising, APP_BLE_CONN_CFG_TAG);
  345. }
  346. /**@brief Function for starting advertising, or instead trigger it from peer manager (after
  347. deleting bonds).
  348. @param[in] erase_bonds Bool to determine if bonds will be deleted before advertising.
  349. */
  350. void advertising_start(bool erase_bonds)
  351. {
  352. ret_code_t err_code;
  353. if (erase_bonds == true)
  354. {
  355. // Advertising is started by the PM_EVT_PEERS_DELETE_SUCCEEDED event.
  356. NRF_LOG_INFO("Erase bonds.");
  357. err_code = pm_peers_delete();
  358. APP_ERROR_CHECK(err_code);
  359. }
  360. else
  361. {
  362. err_code = ble_advertising_start(&m_advertising, BLE_ADV_MODE_FAST);
  363. APP_ERROR_CHECK(err_code);
  364. }
  365. }
  366. /**@brief Function for assert macro callback.
  367. @details This function will be called in case of an assert in the SoftDevice.
  368. @warning This handler is an example only and does not fit a final product. You need to analyze
  369. how your product is supposed to react in case of Assert.
  370. @warning On assert from the SoftDevice, the system can only recover on reset.
  371. @param[in] line_num Line number of the failing ASSERT call.
  372. @param[in] p_file_name File name of the failing ASSERT call.
  373. */
  374. void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name)
  375. {
  376. app_error_handler(DEAD_BEEF, line_num, p_file_name);
  377. }
  378. /**@brief Function for handling the GATT Service Client errors.
  379. *
  380. * @param[in] nrf_error Error code containing information about what went wrong.
  381. */
  382. static void gatt_c_error_handler(uint32_t nrf_error)
  383. {
  384. APP_ERROR_HANDLER(nrf_error);
  385. }
  386. /**@brief Function for the LEDs initialization.
  387. @details Initializes all LEDs used by the application.
  388. */
  389. static void leds_init(void)
  390. {
  391. bsp_board_init(BSP_INIT_LEDS);
  392. }
  393. /**@brief Function for the Timer initialization.
  394. @details Initializes the timer module.
  395. */
  396. static void timers_init(void)
  397. {
  398. ret_code_t err_code;
  399. err_code = app_timer_init();
  400. APP_ERROR_CHECK(err_code);
  401. }
  402. /**@brief Function for the GAP initialization.
  403. @details This function sets up all the necessary GAP (Generic Access Profile) parameters of the
  404. device including the device name, appearance, and the preferred connection parameters.
  405. */
  406. static void gap_params_init(void)
  407. {
  408. ret_code_t err_code;
  409. ble_gap_conn_params_t gap_conn_params;
  410. ble_gap_conn_sec_mode_t sec_mode;
  411. BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode);
  412. err_code = sd_ble_gap_device_name_set(&sec_mode,
  413. (const uint8_t *)DEVICE_NAME,
  414. strlen(DEVICE_NAME));
  415. APP_ERROR_CHECK(err_code);
  416. memset(&gap_conn_params, 0, sizeof(gap_conn_params));
  417. gap_conn_params.min_conn_interval = MSEC_TO_UNITS(MIN_CONN_INTERVAL_MSEC, UNIT_1_25_MS);
  418. gap_conn_params.max_conn_interval = MSEC_TO_UNITS(MAX_CONN_INTERVAL_MSEC, UNIT_1_25_MS);
  419. gap_conn_params.slave_latency = SLAVE_LATENCY;
  420. gap_conn_params.conn_sup_timeout = MSEC_TO_UNITS(CONN_SUP_TIMEOUT_MSEC, UNIT_10_MS);
  421. err_code = sd_ble_gap_ppcp_set(&gap_conn_params);
  422. APP_ERROR_CHECK(err_code);
  423. }
  424. /**@brief Function for initializing buttons and leds.
  425. @param[out] p_erase_bonds Boolean that will be set to true if the device is
  426. woken up by the BSP_EVENT_CLEAR_BONDING_DATA event.
  427. */
  428. static void buttons_leds_init(bool * p_erase_bonds)
  429. {
  430. ret_code_t err_code;
  431. bsp_event_t startup_event;
  432. err_code = bsp_init(BSP_INIT_LEDS | BSP_INIT_BUTTONS, NULL);
  433. APP_ERROR_CHECK(err_code);
  434. err_code = bsp_btn_ble_init(NULL, &startup_event);
  435. APP_ERROR_CHECK(err_code);
  436. *p_erase_bonds = (startup_event == BSP_EVENT_CLEAR_BONDING_DATA);
  437. }
  438. /**@brief Function for handling events from the GATT Servive client module.
  439. @param[in] p_evt GATT Service event.
  440. */
  441. static void gatts_evt_handler(nrf_ble_gatts_c_evt_t * p_evt)
  442. {
  443. ret_code_t err_code;
  444. switch (p_evt->evt_type)
  445. {
  446. case NRF_BLE_GATTS_C_EVT_DISCOVERY_COMPLETE:
  447. {
  448. NRF_LOG_INFO("GATT Service and Service Changed characteristic found on server.");
  449. err_code = nrf_ble_gatts_c_handles_assign(&m_gatts_c,
  450. p_evt->conn_handle,
  451. &p_evt->params.srv_changed_char);
  452. APP_ERROR_CHECK(err_code);
  453. pm_peer_id_t peer_id;
  454. err_code = pm_peer_id_get(p_evt->conn_handle, &peer_id);
  455. APP_ERROR_CHECK(err_code);
  456. ble_gatt_db_srv_t srv_db_to_store;
  457. srv_db_to_store.charateristics[0] = p_evt->params.srv_changed_char;
  458. memcpy(m_pm_peer_srv_buffer, &srv_db_to_store, sizeof(ble_gatt_db_srv_t));
  459. err_code = pm_peer_data_remote_db_store(peer_id,
  460. (ble_gatt_db_srv_t *)m_pm_peer_srv_buffer,
  461. sizeof(m_pm_peer_srv_buffer),
  462. NULL);
  463. if (err_code == NRF_ERROR_STORAGE_FULL)
  464. {
  465. err_code = fds_gc();
  466. }
  467. APP_ERROR_CHECK(err_code);
  468. err_code = nrf_ble_gatts_c_enable_indication(&m_gatts_c, true);
  469. APP_ERROR_CHECK(err_code);
  470. } break;
  471. case NRF_BLE_GATTS_C_EVT_DISCOVERY_FAILED:
  472. NRF_LOG_INFO("GATT Service or Service Changed characteristic not found on server.");
  473. break;
  474. case NRF_BLE_GATTS_C_EVT_DISCONN_COMPLETE:
  475. NRF_LOG_INFO("GATTS Service client disconnected connection handle %i.", p_evt->conn_handle);
  476. break;
  477. case NRF_BLE_GATTS_C_EVT_SRV_CHANGED:
  478. NRF_LOG_INFO("Service Changed indication received.");
  479. NRF_LOG_INFO("Handle range start: %04x", p_evt->params.handle_range.start_handle);
  480. NRF_LOG_INFO("Handle range end: %04x", p_evt->params.handle_range.end_handle);
  481. break;
  482. default:
  483. break;
  484. }
  485. }
  486. /**@brief Function for handling Peer Manager events.
  487. *
  488. * @param[in] p_evt Peer Manager event.
  489. */
  490. static void pm_evt_handler(pm_evt_t const * p_evt)
  491. {
  492. ret_code_t err_code;
  493. pm_handler_on_pm_evt(p_evt);
  494. pm_handler_flash_clean(p_evt);
  495. switch (p_evt->evt_id)
  496. {
  497. case PM_EVT_BONDED_PEER_CONNECTED:
  498. {
  499. pm_peer_id_t peer_id;
  500. err_code = pm_peer_id_get(p_evt->conn_handle, &peer_id);
  501. APP_ERROR_CHECK(err_code);
  502. if (peer_id != PM_PEER_ID_INVALID)
  503. {
  504. ble_gatt_db_srv_t * remote_db;
  505. remote_db = (ble_gatt_db_srv_t *)m_pm_peer_srv_buffer;
  506. uint32_t data_len = sizeof(m_pm_peer_srv_buffer);
  507. err_code = pm_peer_data_remote_db_load(peer_id, remote_db, &data_len);
  508. if (err_code == NRF_ERROR_NOT_FOUND)
  509. {
  510. NRF_LOG_DEBUG("Could not find the remote database in flash.");
  511. err_code = nrf_ble_gatts_c_handles_assign(&m_gatts_c, p_evt->conn_handle, NULL);
  512. APP_ERROR_CHECK(err_code);
  513. // Discover peer's services.
  514. memset(&m_ble_db_discovery, 0x00, sizeof(m_ble_db_discovery));
  515. err_code = ble_db_discovery_start(&m_ble_db_discovery, p_evt->conn_handle);
  516. APP_ERROR_CHECK(err_code);
  517. }
  518. else
  519. {
  520. // Check if the load was successful.
  521. NRF_LOG_INFO("Remote Database loaded from flash.");
  522. APP_ERROR_CHECK(err_code);
  523. // Assign the loaded handles to the GATT Service client module.
  524. ble_gatt_db_char_t service_changed_handles = remote_db->charateristics[0];
  525. err_code = nrf_ble_gatts_c_handles_assign(&m_gatts_c,
  526. p_evt->conn_handle,
  527. &service_changed_handles);
  528. APP_ERROR_CHECK(err_code);
  529. // Enable indications.
  530. err_code = nrf_ble_gatts_c_enable_indication(&m_gatts_c, true);
  531. APP_ERROR_CHECK(err_code);
  532. }
  533. }
  534. } break;
  535. case PM_EVT_CONN_SEC_SUCCEEDED:
  536. // Check it the Service Changed characteristic handle exists in our client instance.
  537. // If it is invalid, we know service discovery is needed.
  538. // (No database was loaded during @ref PM_EVT_BONDED_PEER_CONNECTED)
  539. if (m_gatts_c.srv_changed_char.characteristic.handle_value == BLE_GATT_HANDLE_INVALID)
  540. {
  541. err_code = nrf_ble_gatts_c_handles_assign(&m_gatts_c, p_evt->conn_handle, NULL);
  542. APP_ERROR_CHECK(err_code);
  543. // Discover peer's services.
  544. memset(&m_ble_db_discovery, 0x00, sizeof(m_ble_db_discovery));
  545. err_code = ble_db_discovery_start(&m_ble_db_discovery, p_evt->conn_handle);
  546. APP_ERROR_CHECK(err_code);
  547. }
  548. break;
  549. case PM_EVT_PEERS_DELETE_SUCCEEDED:
  550. // Peer data was cleared from the flash. Start advertising with an empty list of peers.
  551. advertising_start(false);
  552. break;
  553. default:
  554. // No implementation needed.
  555. break;
  556. }
  557. }
  558. /**@brief Function for initializing the Peer Manager.
  559. */
  560. void peer_manager_init(void)
  561. {
  562. ret_code_t err_code;
  563. ble_gap_sec_params_t sec_param;
  564. err_code = pm_init();
  565. APP_ERROR_CHECK(err_code);
  566. memset(&sec_param, 0, sizeof(ble_gap_sec_params_t));
  567. // Security parameters to be used for all security procedures.
  568. sec_param.bond = SEC_PARAM_BOND;
  569. sec_param.mitm = SEC_PARAM_MITM;
  570. sec_param.io_caps = SEC_PARAM_IO_CAPABILITIES;
  571. sec_param.oob = SEC_PARAM_OOB;
  572. sec_param.min_key_size = SEC_PARAM_MIN_KEY_SIZE;
  573. sec_param.max_key_size = SEC_PARAM_MAX_KEY_SIZE;
  574. sec_param.kdist_own.enc = 1;
  575. sec_param.kdist_own.id = 1;
  576. sec_param.kdist_peer.enc = 1;
  577. sec_param.kdist_peer.id = 1;
  578. err_code = pm_sec_params_set(&sec_param);
  579. APP_ERROR_CHECK(err_code);
  580. err_code = pm_register(pm_evt_handler);
  581. APP_ERROR_CHECK(err_code);
  582. }
  583. /**@brief Function for handling database discovery events.
  584. @details This function is callback function to handle events from the database discovery module.
  585. Depending on the UUIDs that are discovered, this function should forward the events
  586. to their respective services.
  587. @param[in] p_event Pointer to the database discovery event.
  588. */
  589. static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
  590. {
  591. nrf_ble_gatts_c_on_db_disc_evt(&m_gatts_c, p_evt);
  592. }
  593. /**@brief Function for handling connection events.
  594. @param[in] p_ble_evt Bluetooth stack event.
  595. */
  596. static void on_connect(ble_evt_t const * p_ble_evt)
  597. {
  598. ret_code_t err_code;
  599. NRF_LOG_INFO("Connected.");
  600. err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
  601. APP_ERROR_CHECK(err_code);
  602. m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
  603. err_code = nrf_ble_qwr_conn_handle_assign(&m_qwr, m_conn_handle);
  604. APP_ERROR_CHECK(err_code);
  605. ble_connect_state = true;
  606. }
  607. /**@brief Function for handling timeout BLE stack events.
  608. @param[in] p_ble_evt Bluetooth stack event.
  609. */
  610. static void on_timeout(ble_evt_t const * p_ble_evt)
  611. {
  612. ret_code_t err_code;
  613. switch (p_ble_evt->header.evt_id)
  614. {
  615. case BLE_GATTC_EVT_TIMEOUT:
  616. NRF_LOG_DEBUG("GATT Client Timeout.");
  617. err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
  618. BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  619. APP_ERROR_CHECK(err_code);
  620. break;
  621. case BLE_GATTS_EVT_TIMEOUT:
  622. NRF_LOG_DEBUG("GATT Server Timeout.");
  623. err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
  624. BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  625. APP_ERROR_CHECK(err_code);
  626. break;
  627. default:
  628. // No implementation needed.
  629. break;
  630. }
  631. }
  632. /**@brief Function for handling BLE events.
  633. *
  634. * @param[in] p_ble_evt Bluetooth stack event.
  635. * @param[in] p_context Unused.
  636. */
  637. static void ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context)
  638. {
  639. ret_code_t err_code;
  640. pm_handler_secure_on_connection(p_ble_evt);
  641. switch (p_ble_evt->header.evt_id)
  642. {
  643. case BLE_GAP_EVT_CONNECTED:
  644. {
  645. on_connect(p_ble_evt);
  646. } break;
  647. case BLE_GAP_EVT_DISCONNECTED:
  648. NRF_LOG_INFO("Disconnected.");
  649. m_conn_handle = BLE_CONN_HANDLE_INVALID;
  650. ble_connect_state = false;
  651. break;
  652. case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
  653. {
  654. NRF_LOG_DEBUG("PHY update request.");
  655. ble_gap_phys_t const phys =
  656. {
  657. .rx_phys = BLE_GAP_PHY_AUTO,
  658. .tx_phys = BLE_GAP_PHY_AUTO,
  659. };
  660. err_code = sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
  661. APP_ERROR_CHECK(err_code);
  662. } break;
  663. case BLE_GATTS_EVT_SYS_ATTR_MISSING:
  664. // No system attributes have been stored.
  665. err_code = sd_ble_gatts_sys_attr_set(p_ble_evt->evt.gatts_evt.conn_handle, NULL, 0, 0);
  666. APP_ERROR_CHECK(err_code);
  667. break;
  668. case BLE_GATTC_EVT_TIMEOUT:
  669. // fall-through.
  670. case BLE_GATTS_EVT_TIMEOUT:
  671. on_timeout(p_ble_evt);
  672. break;
  673. default:
  674. // No implementation needed.
  675. break;
  676. }
  677. }
  678. /**@brief Function for initializing the BLE stack.
  679. @details Initializes the SoftDevice and the BLE event interrupt.
  680. */
  681. static void ble_stack_init(void)
  682. {
  683. ret_code_t err_code;
  684. err_code = nrf_sdh_enable_request();
  685. APP_ERROR_CHECK(err_code);
  686. // Configure the BLE stack using the default settings.
  687. // Fetch the start address of the application RAM.
  688. uint32_t ram_start = 0;
  689. err_code = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &ram_start);
  690. APP_ERROR_CHECK(err_code);
  691. // Enable BLE stack.
  692. err_code = nrf_sdh_ble_enable(&ram_start);
  693. APP_ERROR_CHECK(err_code);
  694. // Register handler for BLE events.
  695. NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, ble_evt_handler, NULL);
  696. }
  697. /** @brief Database discovery initialization.
  698. */
  699. static void db_discovery_init(void)
  700. {
  701. ble_db_discovery_init_t db_init;
  702. memset(&db_init, 0, sizeof(db_init));
  703. db_init.evt_handler = db_disc_handler;
  704. db_init.p_gatt_queue = &m_ble_gatt_queue;
  705. ret_code_t err_code = ble_db_discovery_init(&db_init);
  706. APP_ERROR_CHECK(err_code);
  707. }
  708. /**@brief Function for initializing the nrf log module.
  709. */
  710. static void log_init(void)
  711. {
  712. ret_code_t err_code = NRF_LOG_INIT(NULL);
  713. APP_ERROR_CHECK(err_code);
  714. NRF_LOG_DEFAULT_BACKENDS_INIT();
  715. }
  716. /**@brief Function for initializing power management.
  717. */
  718. static void power_management_init(void)
  719. {
  720. ret_code_t err_code;
  721. err_code = nrf_pwr_mgmt_init();
  722. APP_ERROR_CHECK(err_code);
  723. }
  724. /**@brief Function for handling the idle state (main loop). If there is no pending log operation,
  725. then sleep until next the next event occurs.
  726. */
  727. static void idle_state_handle(void)
  728. {
  729. if (NRF_LOG_PROCESS() == false)
  730. {
  731. nrf_pwr_mgmt_run();
  732. }
  733. }
  734. /**@brief Function for initializing the GATT module.
  735. */
  736. static void gatt_init(void)
  737. {
  738. ret_code_t err_code = nrf_ble_gatt_init(&m_gatt, NULL);
  739. APP_ERROR_CHECK(err_code);
  740. }
  741. /**@brief Function for handling Queued Write Module errors.
  742. *
  743. * @details A pointer to this function will be passed to each service which may need to inform the
  744. * application about an error.
  745. *
  746. * @param[in] nrf_error Error code containing information about what went wrong.
  747. */
  748. static void nrf_qwr_error_handler(uint32_t nrf_error)
  749. {
  750. APP_ERROR_HANDLER(nrf_error);
  751. }
  752. /**@brief Function for initializing services that will be used by the application.
  753. */
  754. static void services_init(void)
  755. {
  756. ret_code_t err_code;
  757. nrf_ble_gatts_c_init_t gatts_c_init = {0};
  758. nrf_ble_qwr_init_t qwr_init = {0};
  759. ble_bts_init_t bts_init_obj;
  760. // Initialize Link Loss Service
  761. memset(&bts_init_obj, 0, sizeof(bts_init_obj));
  762. // bts_init_obj.evt_handler = on_bts_evt;
  763. // bts_init_obj.error_handler = service_error_handler;
  764. // bts_init_obj.initial_alert_level = INITIAL_BTS_ALERT_LEVEL;
  765. bts_init_obj.data_handler = bts_data_handler;
  766. // bts_init_obj.alert_level_rd_sec = SEC_JUST_WORKS;
  767. // bts_init_obj.alert_level_wr_sec = SEC_JUST_WORKS;
  768. err_code = ble_bts_init(&m_bts, &bts_init_obj);
  769. APP_ERROR_CHECK(err_code);
  770. // Initialize Queued Write Module.
  771. qwr_init.error_handler = nrf_qwr_error_handler;
  772. err_code = nrf_ble_qwr_init(&m_qwr, &qwr_init);
  773. APP_ERROR_CHECK(err_code);
  774. // Initialize GATTS Client Module.
  775. gatts_c_init.evt_handler = gatts_evt_handler;
  776. gatts_c_init.err_handler = gatt_c_error_handler;
  777. gatts_c_init.p_gatt_queue = &m_ble_gatt_queue;
  778. err_code = nrf_ble_gatts_c_init(&m_gatts_c, &gatts_c_init);
  779. APP_ERROR_CHECK(err_code);
  780. }
  781. /**@brief Function for initializing all the modules used in this example application.
  782. */
  783. static void modules_init(void)
  784. {
  785. log_init();
  786. leds_init();
  787. timers_init();
  788. buttons_leds_init(&m_erase_bonds);
  789. power_management_init();
  790. ble_stack_init();
  791. gap_params_init();
  792. gatt_init();
  793. db_discovery_init();
  794. services_init();
  795. advertising_init();
  796. peer_manager_init();
  797. }
  798. /**@brief Function for application main entry.
  799. */
  800. void blinker_ble_init(blinker_callback_with_string_arg_t func)
  801. // int blinker_ble_init(void)
  802. {
  803. blinker_parse_func = func;
  804. // Initialize.
  805. modules_init();
  806. // Start execution.
  807. NRF_LOG_INFO("GATT Service client started.");
  808. advertising_start(m_erase_bonds);
  809. // Enter main loop.
  810. for (;;)
  811. {
  812. idle_state_handle();
  813. }
  814. }
  815. /**
  816. * @}
  817. */
  818. #endif