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.

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