You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

732 lines
24 KiB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
  1. /**
  2. * Copyright (c) 2016 - 2021, 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. #include <stdio.h>
  41. #include <stdint.h>
  42. #include <stdbool.h>
  43. #include "nordic_common.h"
  44. #include "app_error.h"
  45. #include "app_uart.h"
  46. #include "ble_db_discovery.h"
  47. #include "app_timer.h"
  48. #include "app_util.h"
  49. #include "bsp_btn_ble.h"
  50. #include "ble.h"
  51. #include "ble_gap.h"
  52. #include "ble_hci.h"
  53. #include "nrf_sdh.h"
  54. #include "nrf_sdh_ble.h"
  55. #include "nrf_sdh_soc.h"
  56. #include "zble_nus_c.h"
  57. #include "nrf_ble_gatt.h"
  58. #include "nrf_pwr_mgmt.h"
  59. #include "nrf_ble_scan.h"
  60. #include "nrf_log.h"
  61. #include "nrf_log_ctrl.h"
  62. #include "nrf_log_default_backends.h"
  63. #define APP_BLE_CONN_CFG_TAG 1 /**< Tag that refers to the BLE stack configuration set with @ref sd_ble_cfg_set. The default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
  64. #define APP_BLE_OBSERVER_PRIO 3 /**< BLE observer priority of the application. There is no need to modify this value. */
  65. #define UART_TX_BUF_SIZE 256 /**< UART TX buffer size. */
  66. #define UART_RX_BUF_SIZE 256 /**< UART RX buffer size. */
  67. #define NUS_SERVICE_UUID_TYPE BLE_UUID_TYPE_VENDOR_BEGIN /**< UUID type for the Nordic UART Service (vendor specific). */
  68. #define ECHOBACK_BLE_UART_DATA 0 /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
  69. BLE_NUS_C_DEF(m_ble_nus_c); /**< BLE Nordic UART Service (NUS) client instance. */
  70. NRF_BLE_GATT_DEF(m_gatt); /**< GATT module instance. */
  71. BLE_DB_DISCOVERY_DEF(m_db_disc); /**< Database discovery module instance. */
  72. NRF_BLE_SCAN_DEF(m_scan); /**< Scanning Module instance. */
  73. NRF_BLE_GQ_DEF(m_ble_gatt_queue, /**< BLE GATT Queue instance. */
  74. NRF_SDH_BLE_CENTRAL_LINK_COUNT,
  75. NRF_BLE_GQ_QUEUE_SIZE);
  76. static uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - OPCODE_LENGTH - HANDLE_LENGTH; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
  77. /**@brief NUS UUID. */
  78. static ble_uuid_t const m_nus_uuid =
  79. {
  80. .uuid = BLE_UUID_NUS_SERVICE,
  81. .type = NUS_SERVICE_UUID_TYPE
  82. };
  83. /**@brief Function for handling asserts in the SoftDevice.
  84. *
  85. * @details This function is called in case of an assert in the SoftDevice.
  86. *
  87. * @warning This handler is only an example and is not meant for the final product. You need to analyze
  88. * how your product is supposed to react in case of assert.
  89. * @warning On assert from the SoftDevice, the system can only recover on reset.
  90. *
  91. * @param[in] line_num Line number of the failing assert call.
  92. * @param[in] p_file_name File name of the failing assert call.
  93. */
  94. void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name)
  95. {
  96. app_error_handler(0xDEADBEEF, line_num, p_file_name);
  97. }
  98. /**@brief Function for handling the Nordic UART Service Client errors.
  99. *
  100. * @param[in] nrf_error Error code containing information about what went wrong.
  101. */
  102. static void nus_error_handler(uint32_t nrf_error)
  103. {
  104. APP_ERROR_HANDLER(nrf_error);
  105. }
  106. /**@brief Function to start scanning. */
  107. static void scan_start(void)
  108. {
  109. ret_code_t ret;
  110. ret = nrf_ble_scan_start(&m_scan);
  111. APP_ERROR_CHECK(ret);
  112. ret = bsp_indication_set(BSP_INDICATE_SCANNING);
  113. APP_ERROR_CHECK(ret);
  114. }
  115. /**@brief Function for handling Scanning Module events.
  116. */
  117. static void scan_evt_handler(scan_evt_t const * p_scan_evt)
  118. {
  119. ret_code_t err_code;
  120. switch(p_scan_evt->scan_evt_id)
  121. {
  122. case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
  123. {
  124. err_code = p_scan_evt->params.connecting_err.err_code;
  125. APP_ERROR_CHECK(err_code);
  126. } break;
  127. case NRF_BLE_SCAN_EVT_CONNECTED:
  128. {
  129. ble_gap_evt_connected_t const * p_connected =
  130. p_scan_evt->params.connected.p_connected;
  131. // Scan is automatically stopped by the connection.
  132. NRF_LOG_INFO("Connecting to target %02x%02x%02x%02x%02x%02x",
  133. p_connected->peer_addr.addr[0],
  134. p_connected->peer_addr.addr[1],
  135. p_connected->peer_addr.addr[2],
  136. p_connected->peer_addr.addr[3],
  137. p_connected->peer_addr.addr[4],
  138. p_connected->peer_addr.addr[5]
  139. );
  140. } break;
  141. case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
  142. {
  143. NRF_LOG_INFO("Scan timed out.");
  144. scan_start();
  145. } break;
  146. default:
  147. break;
  148. }
  149. }
  150. /**@brief Function for initializing the scanning and setting the filters.
  151. */
  152. static char m_target_periph_name0[20] = "M1002"; /**< Name of the device we try to connect to. This name is searched in the scan report data*/
  153. static char m_target_periph_name1[20] = "M1001"; /**< Name of the device we try to connect to. This name is searched in the scan report data*/
  154. static char m_target_periph_name2[20] = "iflytop"; /**< Name of the device we try to connect to. This name is searched in the scan report data*/
  155. static void scan_init(void)
  156. {
  157. ret_code_t err_code;
  158. nrf_ble_scan_init_t init_scan;
  159. memset(&init_scan, 0, sizeof(init_scan));
  160. init_scan.connect_if_match = true;
  161. init_scan.conn_cfg_tag = APP_BLE_CONN_CFG_TAG;
  162. err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
  163. APP_ERROR_CHECK(err_code);
  164. // err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &m_nus_uuid);
  165. // APP_ERROR_CHECK(err_code);
  166. APP_ERROR_CHECK(nrf_ble_scan_filter_set(&m_scan, SCAN_NAME_FILTER, m_target_periph_name0));
  167. APP_ERROR_CHECK(nrf_ble_scan_filter_set(&m_scan, SCAN_NAME_FILTER, m_target_periph_name1));
  168. APP_ERROR_CHECK(nrf_ble_scan_filter_set(&m_scan, SCAN_NAME_FILTER, m_target_periph_name2));
  169. // err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_NAME_FILTER, false);
  170. // APP_ERROR_CHECK(err_code);
  171. err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_NAME_FILTER, false);
  172. APP_ERROR_CHECK(err_code);
  173. }
  174. /**@brief Function for handling database discovery events.
  175. *
  176. * @details This function is a callback function to handle events from the database discovery module.
  177. * Depending on the UUIDs that are discovered, this function forwards the events
  178. * to their respective services.
  179. *
  180. * @param[in] p_event Pointer to the database discovery event.
  181. */
  182. static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
  183. {
  184. ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
  185. }
  186. /**@brief Function for handling characters received by the Nordic UART Service (NUS).
  187. *
  188. * @details This function takes a list of characters of length data_len and prints the characters out on UART.
  189. * If @ref ECHOBACK_BLE_UART_DATA is set, the data is sent back to sender.
  190. */
  191. static void ble_nus_chars_received_uart_print(uint8_t * p_data, uint16_t data_len,bool raw)
  192. {
  193. ret_code_t ret_val;
  194. NRF_LOG_DEBUG("Receiving data.");
  195. NRF_LOG_HEXDUMP_DEBUG(p_data, data_len);
  196. // app_uart_put(0x5A);
  197. // app_uart_put(data_len);
  198. for (uint32_t i = 0; i < data_len; i++)
  199. {
  200. do
  201. {
  202. ret_val = app_uart_put(p_data[i]);
  203. if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
  204. {
  205. NRF_LOG_ERROR("app_uart_put failed for index 0x%04x.", i);
  206. APP_ERROR_CHECK(ret_val);
  207. }
  208. } while (ret_val == NRF_ERROR_BUSY);
  209. }
  210. if(!raw){
  211. app_uart_put(0x5A);
  212. app_uart_put(0xA5);
  213. }
  214. // if (p_data[data_len-1] == '\r')
  215. // {
  216. // while (app_uart_put('\n') == NRF_ERROR_BUSY);
  217. // }
  218. if (ECHOBACK_BLE_UART_DATA)
  219. {
  220. // Send data back to the peripheral.
  221. do
  222. {
  223. ret_val = ble_nus_c_string_send(&m_ble_nus_c, p_data, data_len);
  224. if ((ret_val != NRF_SUCCESS) && (ret_val != NRF_ERROR_BUSY))
  225. {
  226. NRF_LOG_ERROR("Failed sending NUS message. Error 0x%x. ", ret_val);
  227. APP_ERROR_CHECK(ret_val);
  228. }
  229. } while (ret_val == NRF_ERROR_BUSY);
  230. }
  231. }
  232. /**@brief Function for handling app_uart events.
  233. *
  234. * @details This function receives a single character from the app_uart module and appends it to
  235. * a string. The string is sent over BLE when the last character received is a
  236. * 'new line' '\n' (hex 0x0A) or if the string reaches the maximum data length.
  237. */
  238. static uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
  239. static uint16_t data_array_index = 0;
  240. // static uint32_t
  241. void uart_event_handle(app_uart_evt_t * p_event)
  242. {
  243. uint32_t ret_val;
  244. switch (p_event->evt_type)
  245. {
  246. /**@snippet [Handling data from UART] */
  247. case APP_UART_DATA_READY:
  248. UNUSED_VARIABLE(app_uart_get(&data_array[data_array_index]));
  249. data_array_index++;
  250. if (
  251. data_array_index >= (m_ble_nus_max_data_len))
  252. {
  253. NRF_LOG_DEBUG("Ready to send data over BLE NUS");
  254. NRF_LOG_HEXDUMP_DEBUG(data_array, data_array_index);
  255. do
  256. {
  257. ret_val = ble_nus_c_string_send(&m_ble_nus_c, data_array, data_array_index);
  258. if ( (ret_val != NRF_ERROR_INVALID_STATE) && (ret_val != NRF_ERROR_RESOURCES) )
  259. {
  260. APP_ERROR_CHECK(ret_val);
  261. }
  262. } while (ret_val == NRF_ERROR_RESOURCES);
  263. data_array_index = 0;
  264. }
  265. break;
  266. /**@snippet [Handling data from UART] */
  267. case APP_UART_COMMUNICATION_ERROR:
  268. NRF_LOG_ERROR("Communication error occurred while handling UART.");
  269. APP_ERROR_HANDLER(p_event->data.error_communication);
  270. break;
  271. case APP_UART_FIFO_ERROR:
  272. NRF_LOG_ERROR("Error occurred in FIFO module used by UART.");
  273. APP_ERROR_HANDLER(p_event->data.error_code);
  274. break;
  275. default:
  276. break;
  277. }
  278. }
  279. /**@brief Callback handling Nordic UART Service (NUS) client events.
  280. *
  281. * @details This function is called to notify the application of NUS client events.
  282. *
  283. * @param[in] p_ble_nus_c NUS client handle. This identifies the NUS client.
  284. * @param[in] p_ble_nus_evt Pointer to the NUS client event.
  285. */
  286. /**@snippet [Handling events from the ble_nus_c module] */
  287. static int32_t rxcnt;
  288. static void ble_nus_c_evt_handler(ble_nus_c_t * p_ble_nus_c, ble_nus_c_evt_t const * p_ble_nus_evt)
  289. {
  290. ret_code_t err_code;
  291. switch (p_ble_nus_evt->evt_type)
  292. {
  293. case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:
  294. NRF_LOG_INFO("Discovery complete.");
  295. err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
  296. APP_ERROR_CHECK(err_code);
  297. err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
  298. APP_ERROR_CHECK(err_code);
  299. NRF_LOG_INFO("Connected to device with Nordic UART Service.");
  300. break;
  301. case BLE_NUS_C_EVT_NUS_TX_EVT:
  302. ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len,false);
  303. break;
  304. case BLE_NUS_C_EVT_NUS_TX_EVT_2:
  305. ble_nus_chars_received_uart_print(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len,true);
  306. rxcnt+=p_ble_nus_evt->data_len;
  307. // printf("data_len:%d %d\n",p_ble_nus_evt->data_len,rxcnt);
  308. break;
  309. case BLE_NUS_C_EVT_DISCONNECTED:
  310. NRF_LOG_INFO("Disconnected.");
  311. scan_start();
  312. break;
  313. }
  314. }
  315. /**@snippet [Handling events from the ble_nus_c module] */
  316. /**
  317. * @brief Function for handling shutdown events.
  318. *
  319. * @param[in] event Shutdown type.
  320. */
  321. static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
  322. {
  323. ret_code_t err_code;
  324. err_code = bsp_indication_set(BSP_INDICATE_IDLE);
  325. APP_ERROR_CHECK(err_code);
  326. switch (event)
  327. {
  328. case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
  329. // Prepare wakeup buttons.
  330. err_code = bsp_btn_ble_sleep_mode_prepare();
  331. APP_ERROR_CHECK(err_code);
  332. break;
  333. default:
  334. break;
  335. }
  336. return true;
  337. }
  338. NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
  339. /**@brief Function for handling BLE events.
  340. *
  341. * @param[in] p_ble_evt Bluetooth stack event.
  342. * @param[in] p_context Unused.
  343. */
  344. static void ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context)
  345. {
  346. ret_code_t err_code;
  347. ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
  348. switch (p_ble_evt->header.evt_id)
  349. {
  350. case BLE_GAP_EVT_CONNECTED:
  351. err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
  352. APP_ERROR_CHECK(err_code);
  353. err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
  354. APP_ERROR_CHECK(err_code);
  355. // start discovery of services. The NUS Client waits for a discovery result
  356. err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
  357. APP_ERROR_CHECK(err_code);
  358. break;
  359. case BLE_GAP_EVT_DISCONNECTED:
  360. NRF_LOG_INFO("Disconnected. conn_handle: 0x%x, reason: 0x%x",
  361. p_gap_evt->conn_handle,
  362. p_gap_evt->params.disconnected.reason);
  363. break;
  364. case BLE_GAP_EVT_TIMEOUT:
  365. if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
  366. {
  367. NRF_LOG_INFO("Connection Request timed out.");
  368. }
  369. break;
  370. case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
  371. // Pairing not supported.
  372. err_code = sd_ble_gap_sec_params_reply(p_ble_evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
  373. APP_ERROR_CHECK(err_code);
  374. break;
  375. case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
  376. // Accepting parameters requested by peer.
  377. err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
  378. &p_gap_evt->params.conn_param_update_request.conn_params);
  379. APP_ERROR_CHECK(err_code);
  380. break;
  381. case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
  382. {
  383. NRF_LOG_DEBUG("PHY update request.");
  384. ble_gap_phys_t const phys =
  385. {
  386. .rx_phys = BLE_GAP_PHY_AUTO,
  387. .tx_phys = BLE_GAP_PHY_AUTO,
  388. };
  389. err_code = sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
  390. APP_ERROR_CHECK(err_code);
  391. } break;
  392. case BLE_GATTC_EVT_TIMEOUT:
  393. // Disconnect on GATT Client timeout event.
  394. NRF_LOG_DEBUG("GATT Client Timeout.");
  395. err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
  396. BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  397. APP_ERROR_CHECK(err_code);
  398. break;
  399. case BLE_GATTS_EVT_TIMEOUT:
  400. // Disconnect on GATT Server timeout event.
  401. NRF_LOG_DEBUG("GATT Server Timeout.");
  402. err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
  403. BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  404. APP_ERROR_CHECK(err_code);
  405. break;
  406. default:
  407. break;
  408. }
  409. }
  410. /**@brief Function for initializing the BLE stack.
  411. *
  412. * @details Initializes the SoftDevice and the BLE event interrupt.
  413. */
  414. static void ble_stack_init(void)
  415. {
  416. ret_code_t err_code;
  417. err_code = nrf_sdh_enable_request();
  418. APP_ERROR_CHECK(err_code);
  419. // Configure the BLE stack using the default settings.
  420. // Fetch the start address of the application RAM.
  421. uint32_t ram_start = 0;
  422. err_code = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &ram_start);
  423. APP_ERROR_CHECK(err_code);
  424. // Enable BLE stack.
  425. err_code = nrf_sdh_ble_enable(&ram_start);
  426. APP_ERROR_CHECK(err_code);
  427. // Register a handler for BLE events.
  428. NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, ble_evt_handler, NULL);
  429. }
  430. /**@brief Function for handling events from the GATT library. */
  431. void gatt_evt_handler(nrf_ble_gatt_t * p_gatt, nrf_ble_gatt_evt_t const * p_evt)
  432. {
  433. if (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
  434. {
  435. NRF_LOG_INFO("ATT MTU exchange completed.");
  436. m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
  437. NRF_LOG_INFO("Ble NUS max data length set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
  438. }
  439. }
  440. /**@brief Function for initializing the GATT library. */
  441. void gatt_init(void)
  442. {
  443. ret_code_t err_code;
  444. err_code = nrf_ble_gatt_init(&m_gatt, gatt_evt_handler);
  445. APP_ERROR_CHECK(err_code);
  446. err_code = nrf_ble_gatt_att_mtu_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
  447. APP_ERROR_CHECK(err_code);
  448. }
  449. /**@brief Function for handling events from the BSP module.
  450. *
  451. * @param[in] event Event generated by button press.
  452. */
  453. void bsp_event_handler(bsp_event_t event)
  454. {
  455. ret_code_t err_code;
  456. switch (event)
  457. {
  458. case BSP_EVENT_SLEEP:
  459. nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
  460. break;
  461. case BSP_EVENT_DISCONNECT:
  462. err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
  463. BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  464. if (err_code != NRF_ERROR_INVALID_STATE)
  465. {
  466. APP_ERROR_CHECK(err_code);
  467. }
  468. break;
  469. default:
  470. break;
  471. }
  472. }
  473. /**@brief Function for initializing the UART. */
  474. static void uart_init(void)
  475. {
  476. ret_code_t err_code;
  477. app_uart_comm_params_t const comm_params =
  478. {
  479. .rx_pin_no = RX_PIN_NUMBER,
  480. .tx_pin_no = TX_PIN_NUMBER,
  481. .rts_pin_no = RTS_PIN_NUMBER,
  482. .cts_pin_no = CTS_PIN_NUMBER,
  483. .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
  484. .use_parity = false,
  485. .baud_rate = UART_BAUDRATE_BAUDRATE_Baud921600
  486. };
  487. APP_UART_FIFO_INIT(&comm_params,
  488. UART_RX_BUF_SIZE,
  489. UART_TX_BUF_SIZE,
  490. uart_event_handle,
  491. APP_IRQ_PRIORITY_LOWEST,
  492. err_code);
  493. APP_ERROR_CHECK(err_code);
  494. }
  495. /**@brief Function for initializing the Nordic UART Service (NUS) client. */
  496. static void nus_c_init(void)
  497. {
  498. ret_code_t err_code;
  499. ble_nus_c_init_t init;
  500. init.evt_handler = ble_nus_c_evt_handler;
  501. init.error_handler = nus_error_handler;
  502. init.p_gatt_queue = &m_ble_gatt_queue;
  503. err_code = ble_nus_c_init(&m_ble_nus_c, &init);
  504. APP_ERROR_CHECK(err_code);
  505. }
  506. /**@brief Function for initializing buttons and leds. */
  507. static void buttons_leds_init(void)
  508. {
  509. ret_code_t err_code;
  510. bsp_event_t startup_event;
  511. err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
  512. APP_ERROR_CHECK(err_code);
  513. err_code = bsp_btn_ble_init(NULL, &startup_event);
  514. APP_ERROR_CHECK(err_code);
  515. }
  516. /**@brief Function for initializing the timer. */
  517. static void timer_init(void)
  518. {
  519. ret_code_t err_code = app_timer_init();
  520. APP_ERROR_CHECK(err_code);
  521. }
  522. /**@brief Function for initializing the nrf log module. */
  523. static void log_init(void)
  524. {
  525. ret_code_t err_code = NRF_LOG_INIT(NULL);
  526. APP_ERROR_CHECK(err_code);
  527. NRF_LOG_DEFAULT_BACKENDS_INIT();
  528. }
  529. /**@brief Function for initializing power management.
  530. */
  531. static void power_management_init(void)
  532. {
  533. ret_code_t err_code;
  534. err_code = nrf_pwr_mgmt_init();
  535. APP_ERROR_CHECK(err_code);
  536. }
  537. /** @brief Function for initializing the database discovery module. */
  538. static void db_discovery_init(void)
  539. {
  540. ble_db_discovery_init_t db_init;
  541. memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
  542. db_init.evt_handler = db_disc_handler;
  543. db_init.p_gatt_queue = &m_ble_gatt_queue;
  544. ret_code_t err_code = ble_db_discovery_init(&db_init);
  545. APP_ERROR_CHECK(err_code);
  546. }
  547. /**@brief Function for handling the idle state (main loop).
  548. *
  549. * @details Handles any pending log operations, then sleeps until the next event occurs.
  550. */
  551. static void idle_state_handle(void)
  552. {
  553. if (NRF_LOG_PROCESS() == false)
  554. {
  555. nrf_pwr_mgmt_run();
  556. }
  557. }
  558. APP_TIMER_DEF(m_uart_send_tmr); // ״̬��������ʱ��
  559. static void uart_send_tmr_cb(void* p_context) { //
  560. static uint32_t last_data_array_index;
  561. ret_code_t ret_val;
  562. if (data_array_index != 0 && data_array_index == last_data_array_index) {
  563. do {
  564. ret_val = ble_nus_c_string_send(&m_ble_nus_c, data_array, data_array_index);
  565. if ((ret_val != NRF_ERROR_INVALID_STATE) && (ret_val != NRF_ERROR_RESOURCES)) {
  566. APP_ERROR_CHECK(ret_val);
  567. }
  568. } while (ret_val == NRF_ERROR_RESOURCES);
  569. data_array_index = 0;
  570. last_data_array_index = 0;
  571. }
  572. last_data_array_index = data_array_index;
  573. }
  574. int main(void)
  575. {
  576. // Initialize.
  577. log_init();
  578. timer_init();
  579. uart_init();
  580. buttons_leds_init();
  581. db_discovery_init();
  582. power_management_init();
  583. ble_stack_init();
  584. gatt_init();
  585. nus_c_init();
  586. scan_init();
  587. app_timer_create(&m_uart_send_tmr, APP_TIMER_MODE_REPEATED, uart_send_tmr_cb);
  588. app_timer_start(m_uart_send_tmr, APP_TIMER_TICKS(2), NULL);
  589. app_uart_put(1);
  590. app_uart_put(1);
  591. app_uart_put(1);
  592. app_uart_put(1);
  593. app_uart_put(1);
  594. app_uart_put(1);
  595. // Start execution.
  596. printf("BLE UART central example started.\r\n");
  597. NRF_LOG_INFO("BLE UART central example started.");
  598. scan_start();
  599. // Enter main loop.
  600. for (;;)
  601. {
  602. idle_state_handle();
  603. }
  604. }