main-20210414.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  1. #include "main.h"
  2. #include "bsp_time.h"
  3. #include "hal_ble_client.h"
  4. #include "hal_ble_host.h"
  5. static uint8_t isHostConnet = 0; //本机主机
  6. static uint8_t isClientConnet = 0; //本机从机
  7. //#if IS_HOST
  8. // char my_name[] = "long_S0";
  9. //#else
  10. // char my_name[] = "long_SS0";
  11. //#endif
  12. #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. */
  13. #define APP_BLE_OBSERVER_PRIO 3 /**< BLE observer priority of the application. There is no need to modify this value. */
  14. #define NUS_SERVICE_UUID_TYPE BLE_UUID_TYPE_VENDOR_BEGIN /**< UUID type for the Nordic UART Service (vendor specific). */
  15. #define ECHOBACK_BLE_UART_DATA 1 /**< Echo the UART data that is received over the Nordic UART Service (NUS) back to the sender. */
  16. BLE_NUS_C_DEF(m_ble_nus_c); /**< BLE Nordic UART Service (NUS) client instance. */
  17. NRF_BLE_GATT_DEF(m_gatt); /**< GATT module instance. */
  18. BLE_DB_DISCOVERY_DEF(m_db_disc); /**< Database discovery module instance. */
  19. NRF_BLE_SCAN_DEF(m_scan); /**< Scanning Module instance. */
  20. NRF_BLE_GQ_DEF(m_ble_gatt_queue, /**< BLE GATT Queue instance. */
  21. NRF_SDH_BLE_CENTRAL_LINK_COUNT,
  22. NRF_BLE_GQ_QUEUE_SIZE);
  23. 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. */
  24. /**@brief Function for handling asserts in the SoftDevice.
  25. *
  26. * @details This function is called in case of an assert in the SoftDevice.
  27. *
  28. * @warning This handler is only an example and is not meant for the final product. You need to analyze
  29. * how your product is supposed to react in case of assert.
  30. * @warning On assert from the SoftDevice, the system can only recover on reset.
  31. *
  32. * @param[in] line_num Line number of the failing assert call.
  33. * @param[in] p_file_name File name of the failing assert call.
  34. */
  35. void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name)
  36. {
  37. app_error_handler(0xDEADBEEF, line_num, p_file_name);
  38. }
  39. /**@brief Function for handling the Nordic UART Service Client errors.
  40. *
  41. * @param[in] nrf_error Error code containing information about what went wrong.
  42. */
  43. static void nus_error_handler(uint32_t nrf_error)
  44. {
  45. //APP_ERROR_HANDLER(nrf_error);
  46. }
  47. /**@brief Function to start scanning. */
  48. static void scan_start(void)
  49. {
  50. ret_code_t ret;
  51. ret = nrf_ble_scan_start(&m_scan);
  52. APP_ERROR_CHECK(ret);
  53. ret = bsp_indication_set(BSP_INDICATE_SCANNING);
  54. APP_ERROR_CHECK(ret);
  55. // SEGGER_RTT_printf(0,"scan_start -> scan_name <%s> \n",HOST_NAME);
  56. }
  57. /**@brief Function to stop scanning. */
  58. //static void scan_stop(void)
  59. //{
  60. // nrf_ble_scan_stop();
  61. //}
  62. #define PRINT_MAC 0
  63. /**@brief Function for handling Scanning Module events.
  64. */
  65. static void scan_evt_handler(scan_evt_t const * p_scan_evt)
  66. {
  67. ret_code_t err_code;
  68. switch(p_scan_evt->scan_evt_id)
  69. {
  70. case NRF_BLE_SCAN_EVT_CONNECTING_ERROR:
  71. {
  72. err_code = p_scan_evt->params.connecting_err.err_code;
  73. APP_ERROR_CHECK(err_code);
  74. SEGGER_RTT_printf(0,"scan_evt_handler -> NRF_BLE_SCAN_EVT_CONNECTING_ERROR \n");
  75. } break;
  76. case NRF_BLE_SCAN_EVT_CONNECTED:
  77. {
  78. SEGGER_RTT_printf(0,"scan_evt_handler -> NRF_BLE_SCAN_EVT_CONNECTED\n");
  79. ble_gap_evt_connected_t const * p_connected = p_scan_evt->params.connected.p_connected;
  80. // Scan is automatically stopped by the connection.
  81. SEGGER_RTT_printf(0,"mac:%02x %02x %02x %02x %02x %02x\r\n",
  82. p_connected->peer_addr.addr[5],
  83. p_connected->peer_addr.addr[4],
  84. p_connected->peer_addr.addr[3],
  85. p_connected->peer_addr.addr[2],
  86. p_connected->peer_addr.addr[1],
  87. p_connected->peer_addr.addr[0]
  88. );
  89. } break;
  90. case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT:
  91. {
  92. SEGGER_RTT_printf(0,"scan_evt_handler -> NRF_BLE_SCAN_EVT_SCAN_TIMEOUT -> Scan timed out.\n");
  93. scan_start();
  94. } break;
  95. case NRF_BLE_SCAN_EVT_FILTER_MATCH:
  96. {
  97. SEGGER_RTT_printf(0,"scan_evt_handler -> NRF_BLE_SCAN_EVT_FILTER_MATCH\n");
  98. } break;
  99. case NRF_BLE_SCAN_EVT_WHITELIST_REQUEST:
  100. {
  101. SEGGER_RTT_printf(0,"scan_evt_handler -> NRF_BLE_SCAN_EVT_WHITELIST_REQUEST\n");
  102. } break;
  103. case NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT:
  104. {
  105. SEGGER_RTT_printf(0,"scan_evt_handler -> NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT\n");
  106. } break;
  107. case NRF_BLE_SCAN_EVT_NOT_FOUND:
  108. {
  109. // SEGGER_RTT_printf(0,"scan_evt_handler -> NRF_BLE_SCAN_EVT_NOT_FOUND");
  110. } break;
  111. default:SEGGER_RTT_printf(0,"scan_evt_handler -> default:%d \n",p_scan_evt->scan_evt_id);
  112. break;
  113. }
  114. }
  115. /**@brief Function for initializing the scanning and setting the filters.
  116. */
  117. static void scan_init(void)
  118. {
  119. ret_code_t err_code;
  120. nrf_ble_scan_init_t init_scan;
  121. memset(&init_scan, 0, sizeof(init_scan));
  122. init_scan.connect_if_match = true;
  123. init_scan.conn_cfg_tag = APP_BLE_CONN_CFG_TAG;
  124. err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler);
  125. APP_ERROR_CHECK(err_code);
  126. err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_NAME_FILTER, HOST_NAME);
  127. APP_ERROR_CHECK(err_code);
  128. err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_NAME_FILTER, false);
  129. APP_ERROR_CHECK(err_code);
  130. }
  131. /**@brief Function for handling database discovery events.
  132. *
  133. * @details This function is a callback function to handle events from the database discovery module.
  134. * Depending on the UUIDs that are discovered, this function forwards the events
  135. * to their respective services.
  136. *
  137. * @param[in] p_event Pointer to the database discovery event.
  138. */
  139. static void db_disc_handler(ble_db_discovery_evt_t * p_evt)
  140. {
  141. ble_nus_c_on_db_disc_evt(&m_ble_nus_c, p_evt);
  142. }
  143. /**@brief Function for handling app_uart events.
  144. *
  145. * @details This function receives a single character from the app_uart module and appends it to
  146. * a string. The string is sent over BLE when the last character received is a
  147. * 'new line' '\n' (hex 0x0A) or if the string reaches the maximum data length.
  148. */
  149. //void uart_event_handle(app_uart_evt_t * p_event)
  150. //{
  151. // unsigned char byte;
  152. // switch (p_event->evt_type)
  153. // {
  154. // /**@snippet [Handling data from UART] */
  155. // case APP_UART_DATA_READY:
  156. // app_uart_get(&byte);
  157. // break;
  158. // /**@snippet [Handling data from UART] */
  159. // case APP_UART_COMMUNICATION_ERROR:
  160. // //APP_ERROR_HANDLER(p_event->data.error_communication);
  161. // break;
  162. // case APP_UART_FIFO_ERROR:
  163. // //APP_ERROR_HANDLER(p_event->data.error_code);
  164. // break;
  165. // default:
  166. // break;
  167. // }
  168. //}
  169. /**@brief Callback handling Nordic UART Service (NUS) client events.
  170. *
  171. * @details This function is called to notify the application of NUS client events.
  172. *
  173. * @param[in] p_ble_nus_c NUS client handle. This identifies the NUS client.
  174. * @param[in] p_ble_nus_evt Pointer to the NUS client event.
  175. */
  176. /**@snippet [Handling events from the ble_nus_c module] */
  177. 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)
  178. {
  179. ret_code_t err_code;
  180. switch (p_ble_nus_evt->evt_type)
  181. {
  182. case BLE_NUS_C_EVT_DISCOVERY_COMPLETE:
  183. printf("Discovery complete.\n");
  184. err_code = ble_nus_c_handles_assign(p_ble_nus_c, p_ble_nus_evt->conn_handle, &p_ble_nus_evt->handles);
  185. APP_ERROR_CHECK(err_code);
  186. err_code = ble_nus_c_tx_notif_enable(p_ble_nus_c);
  187. APP_ERROR_CHECK(err_code);
  188. printf("Connected to device with Nordic UART Service.\n");
  189. break;
  190. case BLE_NUS_C_EVT_NUS_TX_EVT://作为主机接收从机的数据
  191. BLE_Host_Push(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
  192. //ble_receive_from_server(p_ble_nus_evt->p_data, p_ble_nus_evt->data_len);
  193. break;
  194. case BLE_NUS_C_EVT_DISCONNECTED:
  195. printf("Disconnected.\n");
  196. scan_start();
  197. break;
  198. }
  199. }
  200. /**@snippet [Handling events from the ble_nus_c module] */
  201. int send_bytes_server(uint8_t * bytes, uint16_t len)
  202. {
  203. if(isHostConnet==0) return -1;
  204. if(NRF_SUCCESS != ble_nus_c_string_send(&m_ble_nus_c,bytes,len)) {
  205. SEGGER_RTT_printf(0,"send_bytes_server -> fail\r\n");
  206. return -1;
  207. }
  208. return 0;
  209. }
  210. /**
  211. * @brief Function for handling shutdown events.
  212. *
  213. * @param[in] event Shutdown type.
  214. */
  215. static bool shutdown_handler(nrf_pwr_mgmt_evt_t event)
  216. {
  217. ret_code_t err_code;
  218. err_code = bsp_indication_set(BSP_INDICATE_IDLE);
  219. APP_ERROR_CHECK(err_code);
  220. switch (event)
  221. {
  222. case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP:
  223. // Prepare wakeup buttons.
  224. err_code = bsp_btn_ble_sleep_mode_prepare();
  225. APP_ERROR_CHECK(err_code);
  226. break;
  227. default:
  228. break;
  229. }
  230. return true;
  231. }
  232. NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY);
  233. /**@brief Function for handling BLE events.
  234. *
  235. * @param[in] p_ble_evt Bluetooth stack event.
  236. * @param[in] p_context Unused.
  237. */
  238. static void on_ble_central_evt(ble_evt_t const * p_ble_evt, void * p_context)//作为主设备时的处理
  239. {
  240. ret_code_t err_code;
  241. ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
  242. switch (p_ble_evt->header.evt_id)
  243. {
  244. case BLE_GAP_EVT_CONNECTED:
  245. err_code = ble_nus_c_handles_assign(&m_ble_nus_c, p_ble_evt->evt.gap_evt.conn_handle, NULL);
  246. APP_ERROR_CHECK(err_code);
  247. err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
  248. APP_ERROR_CHECK(err_code);
  249. SEGGER_RTT_printf(0,"start discovery services\n");//添加开始发现服务提示
  250. APP_ERROR_CHECK(err_code);
  251. // start discovery of services. The NUS Client waits for a discovery result
  252. err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle);
  253. APP_ERROR_CHECK(err_code);
  254. isHostConnet = 1;
  255. break;
  256. case BLE_GAP_EVT_DISCONNECTED:
  257. isHostConnet = 0;
  258. SEGGER_RTT_printf(0,"Disconnected. conn_handle: 0x%x, reason: 0x%x",
  259. p_gap_evt->conn_handle,
  260. p_gap_evt->params.disconnected.reason);
  261. printf("Disconnected to Server.\n");
  262. break;
  263. case BLE_GAP_EVT_TIMEOUT:
  264. if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN)
  265. {
  266. SEGGER_RTT_printf(0,"Connection Request timed out.\n");
  267. }
  268. break;
  269. case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
  270. // Pairing not supported.
  271. 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);
  272. APP_ERROR_CHECK(err_code);
  273. SEGGER_RTT_printf(0,"on_ble_central_evt -> BLE_GAP_EVT_SEC_PARAMS_REQUEST\n");
  274. break;
  275. case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST:
  276. // Accepting parameters requested by peer.
  277. err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle,
  278. &p_gap_evt->params.conn_param_update_request.conn_params);//主机接受从机连接参数更新连接参数
  279. APP_ERROR_CHECK(err_code);
  280. SEGGER_RTT_printf(0,"on_ble_central_evt -> BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST\n");
  281. break;
  282. case BLE_GAP_EVT_CONN_PARAM_UPDATE:
  283. SEGGER_RTT_printf(0,"on_ble_central_evt -> BLE_GAP_EVT_CONN_PARAM_UPDATE\n");
  284. SEGGER_RTT_printf(0,"min_conn_interval : %d\n",p_gap_evt->params.conn_param_update_request.conn_params.min_conn_interval);
  285. SEGGER_RTT_printf(0,"max_conn_interval : %d\n",p_gap_evt->params.conn_param_update_request.conn_params.max_conn_interval);
  286. SEGGER_RTT_printf(0,"slave_latency : %d\n",p_gap_evt->params.conn_param_update_request.conn_params.slave_latency);
  287. SEGGER_RTT_printf(0,"conn_sup_timeout : %d\n",p_gap_evt->params.conn_param_update_request.conn_params.conn_sup_timeout);
  288. break;
  289. case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
  290. {
  291. NRF_LOG_DEBUG("PHY update request.\n");
  292. ble_gap_phys_t const phys =
  293. {
  294. .rx_phys = BLE_GAP_PHY_AUTO,
  295. .tx_phys = BLE_GAP_PHY_AUTO,
  296. };
  297. err_code = sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
  298. APP_ERROR_CHECK(err_code);
  299. } break;
  300. case BLE_GATTC_EVT_TIMEOUT:
  301. // Disconnect on GATT Client timeout event.
  302. NRF_LOG_DEBUG("GATT Client Timeout.\n");
  303. err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
  304. BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  305. APP_ERROR_CHECK(err_code);
  306. break;
  307. case BLE_GATTS_EVT_TIMEOUT:
  308. // Disconnect on GATT Server timeout event.
  309. NRF_LOG_DEBUG("GATT Server Timeout.\n");
  310. err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
  311. BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  312. APP_ERROR_CHECK(err_code);
  313. break;
  314. default:
  315. break;
  316. }
  317. }
  318. /**@brief Function for handling events from the GATT library. */
  319. void gatt_evt_handler(nrf_ble_gatt_t * p_gatt, nrf_ble_gatt_evt_t const * p_evt)
  320. {
  321. if (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)
  322. {
  323. printf("ATT MTU exchange completed.\r\n");
  324. m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
  325. printf("Ble NUS max data length set to 0x%X(%d)\r\n", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
  326. }
  327. }
  328. /**@brief Function for initializing the GATT library. */
  329. void gatt_init(void)
  330. {
  331. ret_code_t err_code;
  332. err_code = nrf_ble_gatt_init(&m_gatt, gatt_evt_handler);
  333. APP_ERROR_CHECK(err_code);
  334. err_code = nrf_ble_gatt_att_mtu_central_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
  335. APP_ERROR_CHECK(err_code);
  336. }
  337. /**@brief Function for handling events from the BSP module.
  338. *
  339. * @param[in] event Event generated by button press.
  340. */
  341. void bsp_event_handler(bsp_event_t event)
  342. {
  343. ret_code_t err_code;
  344. switch (event)
  345. {
  346. case BSP_EVENT_SLEEP:
  347. nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF);
  348. break;
  349. case BSP_EVENT_DISCONNECT:
  350. err_code = sd_ble_gap_disconnect(m_ble_nus_c.conn_handle,
  351. BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  352. if (err_code != NRF_ERROR_INVALID_STATE)
  353. {
  354. APP_ERROR_CHECK(err_code);
  355. }
  356. break;
  357. default:
  358. break;
  359. }
  360. }
  361. /**@brief Function for initializing the UART. */
  362. //static void uart_init(void)
  363. //{
  364. // #ifdef USE_REGISTER_UART
  365. // bsp_uart_init(ble_receive_from_uart);
  366. // #else
  367. // ret_code_t err_code;
  368. // app_uart_comm_params_t const comm_params =
  369. // {
  370. // .rx_pin_no = PIN_RXD_BLE,
  371. // .tx_pin_no = PIN_TXD_BLE,
  372. // .rts_pin_no = RTS_PIN_NUMBER,
  373. // .cts_pin_no = CTS_PIN_NUMBER,
  374. // .flow_control = APP_UART_FLOW_CONTROL_DISABLED,
  375. // .use_parity = false,
  376. // .baud_rate = UART_BAUDRATE_BAUDRATE_Baud115200
  377. // };
  378. // APP_UART_FIFO_INIT(&comm_params,
  379. // UART_RX_BUF_SIZE,
  380. // UART_TX_BUF_SIZE,
  381. // uart_event_handle,
  382. // APP_IRQ_PRIORITY_LOWEST,
  383. // err_code);
  384. // APP_ERROR_CHECK(err_code);
  385. // #endif
  386. //}
  387. /**@brief Function for initializing the Nordic UART Service (NUS) client. */
  388. static void nus_c_init(void)
  389. {
  390. ret_code_t err_code;
  391. ble_nus_c_init_t init;
  392. init.evt_handler = ble_nus_c_evt_handler;
  393. init.error_handler = nus_error_handler;
  394. init.p_gatt_queue = &m_ble_gatt_queue;
  395. err_code = ble_nus_c_init(&m_ble_nus_c, &init);
  396. APP_ERROR_CHECK(err_code);
  397. }
  398. /**@brief Function for initializing buttons and leds. */
  399. //static void buttons_leds_init(void)
  400. //{
  401. // ret_code_t err_code;
  402. // bsp_event_t startup_event;
  403. // err_code = bsp_init(BSP_INIT_LEDS, bsp_event_handler);
  404. // APP_ERROR_CHECK(err_code);
  405. // err_code = bsp_btn_ble_init(NULL, &startup_event);
  406. // APP_ERROR_CHECK(err_code);
  407. //}
  408. /**@brief Function for initializing the timer. */
  409. static void timer_init(void)
  410. { ret_code_t err_code = app_timer_init();
  411. APP_ERROR_CHECK(err_code);
  412. }
  413. /**@brief Function for initializing the nrf log module. */
  414. //static void log_init(void)
  415. //{
  416. // ret_code_t err_code = NRF_LOG_INIT(NULL);
  417. // APP_ERROR_CHECK(err_code);
  418. // NRF_LOG_DEFAULT_BACKENDS_INIT();
  419. //}
  420. /**@brief Function for initializing power management.
  421. */
  422. static void power_management_init(void)
  423. {
  424. ret_code_t err_code;
  425. err_code = nrf_pwr_mgmt_init();
  426. APP_ERROR_CHECK(err_code);
  427. }
  428. /** @brief Function for initializing the database discovery module. */
  429. static void db_discovery_init(void)
  430. {
  431. ble_db_discovery_init_t db_init;
  432. memset(&db_init, 0, sizeof(ble_db_discovery_init_t));
  433. db_init.evt_handler = db_disc_handler;
  434. db_init.p_gatt_queue = &m_ble_gatt_queue;
  435. ret_code_t err_code = ble_db_discovery_init(&db_init);
  436. APP_ERROR_CHECK(err_code);
  437. }
  438. /**@brief Function for handling the idle state (main loop).
  439. *
  440. * @details Handles any pending log operations, then sleeps until the next event occurs.
  441. */
  442. //static void idle_state_handle(void)
  443. //{
  444. // if (NRF_LOG_PROCESS() == false)
  445. // {
  446. // nrf_pwr_mgmt_run();
  447. // }
  448. //}
  449. //********************************* 从机初始化 *********************************//
  450. #include "ble_advertising.h"
  451. #include "ble_conn_params.h"
  452. #include "nrf_ble_qwr.h"
  453. #include "nrf_fstorage.h"
  454. #include "nrf_soc.h"
  455. #include "ble_nus.h"
  456. #define APP_ADV_INTERVAL 300 /**< The advertising interval (in units of 0.625 ms). This value corresponds to 187.5 ms. */
  457. #define APP_ADV_DURATION 18000 /**< The advertising duration (180 seconds) in units of 10 milliseconds. */
  458. #define FIRST_CONN_PARAMS_UPDATE_DELAY APP_TIMER_TICKS(1000) /**< Time from initiating event (connect or start of notification) to first time sd_ble_gap_conn_param_update is called (5 seconds). */
  459. #define NEXT_CONN_PARAMS_UPDATE_DELAY APP_TIMER_TICKS(5000) /**< Time between each call to sd_ble_gap_conn_param_update after the first call (30 seconds). */
  460. #define MAX_CONN_PARAMS_UPDATE_COUNT 1
  461. //#if IS_HOST
  462. // #define DEVICE_NAME "00_test"
  463. //#else
  464. // #define DEVICE_NAME "long_S0"
  465. //#endif
  466. //#define DEVICE_NAME "00_test"
  467. #define MIN_CONN_INTERVAL MSEC_TO_UNITS(20, UNIT_1_25_MS) /**< Minimum acceptable connection interval (20 ms), Connection interval uses 1.25 ms units. */
  468. #define MAX_CONN_INTERVAL MSEC_TO_UNITS(75, UNIT_1_25_MS) /**< Maximum acceptable connection interval (75 ms), Connection interval uses 1.25 ms units. */
  469. #define SLAVE_LATENCY 0 /**< Slave latency. */
  470. #define CONN_SUP_TIMEOUT MSEC_TO_UNITS(4000, UNIT_10_MS)
  471. static ble_uuid_t m_adv_uuids[] = /**< Universally unique service identifier. */
  472. {
  473. {BLE_UUID_NUS_SERVICE, NUS_SERVICE_UUID_TYPE}
  474. };
  475. BLE_NUS_DEF(m_nus, NRF_SDH_BLE_TOTAL_LINK_COUNT);
  476. BLE_ADVERTISING_DEF(m_advertising);
  477. NRF_BLE_QWRS_DEF(m_qwr, NRF_SDH_BLE_TOTAL_LINK_COUNT);
  478. uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID;
  479. static void on_adv_evt(ble_adv_evt_t ble_adv_evt)//广播事件
  480. {
  481. switch (ble_adv_evt)
  482. {
  483. case BLE_ADV_EVT_FAST:
  484. {
  485. SEGGER_RTT_printf(0,"Fast advertising.\n");
  486. } break;
  487. case BLE_ADV_EVT_IDLE:
  488. {
  489. SEGGER_RTT_printf(0,"on_adv_evt->BLE_ADV_EVT_IDLE\n");
  490. ret_code_t err_code = ble_advertising_start(&m_advertising, BLE_ADV_MODE_FAST);//开始广播
  491. APP_ERROR_CHECK(err_code);
  492. } break;
  493. default:
  494. // No implementation needed.
  495. break;
  496. }
  497. }
  498. static void multi_qwr_conn_handle_assign(uint16_t conn_handle)
  499. {
  500. for (uint32_t i = 0; i < NRF_SDH_BLE_TOTAL_LINK_COUNT; i++)
  501. {
  502. if (m_qwr[i].conn_handle == BLE_CONN_HANDLE_INVALID)
  503. {
  504. ret_code_t err_code = nrf_ble_qwr_conn_handle_assign(&m_qwr[i], conn_handle);
  505. APP_ERROR_CHECK(err_code);
  506. break;
  507. }
  508. }
  509. }
  510. static void on_ble_peripheral_evt(ble_evt_t const * p_ble_evt)//作为从设备的处理
  511. {
  512. ret_code_t err_code;
  513. ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt;
  514. switch (p_ble_evt->header.evt_id)
  515. {
  516. case BLE_GAP_EVT_CONNECTED:
  517. SEGGER_RTT_printf(0,"on_ble_peripheral_evt -> BLE_GAP_EVT_CONNECTED\n");
  518. m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
  519. multi_qwr_conn_handle_assign(p_ble_evt->evt.gap_evt.conn_handle);//QWR句柄分配
  520. isClientConnet = 1;
  521. break;
  522. case BLE_GAP_EVT_DISCONNECTED:
  523. isClientConnet = 0;
  524. SEGGER_RTT_printf(0,"on_ble_peripheral_evt -> BLE_GAP_EVT_DISCONNECTED\n");
  525. break;
  526. case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
  527. {
  528. SEGGER_RTT_printf(0,"on_ble_peripheral_evt -> BLE_GAP_EVT_PHY_UPDATE_REQUEST\n");
  529. ble_gap_phys_t const phys =
  530. {
  531. .rx_phys = BLE_GAP_PHY_AUTO,
  532. .tx_phys = BLE_GAP_PHY_AUTO,
  533. };
  534. err_code = sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
  535. APP_ERROR_CHECK(err_code);
  536. } break;
  537. case BLE_GATTC_EVT_TIMEOUT:
  538. // Disconnect on GATT Client timeout event.
  539. SEGGER_RTT_printf(0,"on_ble_peripheral_evt -> BLE_GATTC_EVT_TIMEOUT\n");
  540. err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
  541. BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  542. APP_ERROR_CHECK(err_code);
  543. break;
  544. case BLE_GATTS_EVT_TIMEOUT:
  545. // Disconnect on GATT Server timeout event.
  546. SEGGER_RTT_printf(0,"on_ble_peripheral_evt -> BLE_GATTS_EVT_TIMEOUT\n");
  547. err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
  548. BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  549. APP_ERROR_CHECK(err_code);
  550. break;
  551. case BLE_GAP_EVT_CONN_PARAM_UPDATE:
  552. SEGGER_RTT_printf(0,"on_ble_peripheral_evt -> BLE_GAP_EVT_CONN_PARAM_UPDATE\n");
  553. SEGGER_RTT_printf(0,"min_conn_interval : %d\n",p_gap_evt->params.conn_param_update_request.conn_params.min_conn_interval);
  554. SEGGER_RTT_printf(0,"max_conn_interval : %d\n",p_gap_evt->params.conn_param_update_request.conn_params.max_conn_interval);
  555. SEGGER_RTT_printf(0,"slave_latency : %d\n",p_gap_evt->params.conn_param_update_request.conn_params.slave_latency);
  556. SEGGER_RTT_printf(0,"conn_sup_timeout : %d\n",p_gap_evt->params.conn_param_update_request.conn_params.conn_sup_timeout);
  557. break;
  558. case BLE_GATTC_EVT_EXCHANGE_MTU_RSP:
  559. SEGGER_RTT_printf(0,"on_ble_peripheral_evt -> BLE_GATTC_EVT_EXCHANGE_MTU_RSP\n");
  560. break;
  561. case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
  562. SEGGER_RTT_printf(0,"on_ble_peripheral_evt -> BLE_GAP_EVT_DATA_LENGTH_UPDATE\n");
  563. break;
  564. case BLE_GAP_EVT_ADV_SET_TERMINATED:
  565. SEGGER_RTT_printf(0,"on_ble_peripheral_evt -> BLE_GAP_EVT_ADV_SET_TERMINATED\n");
  566. break;
  567. case BLE_GATTS_EVT_HVN_TX_COMPLETE:
  568. NRF_LOG_DEBUG("on_ble_peripheral_evt -> BLE_GATTS_EVT_HVN_TX_COMPLETE\n");
  569. break;
  570. case BLE_GATTS_EVT_WRITE:
  571. NRF_LOG_DEBUG("on_ble_peripheral_evt -> BLE_GATTS_EVT_WRITE\n");
  572. break;
  573. default:SEGGER_RTT_printf(0,"on_ble_peripheral_evt -> default : 0x%2x\n",p_ble_evt->header.evt_id);
  574. // No implementation needed.
  575. break;
  576. }
  577. }
  578. static void conn_params_error_handler(uint32_t nrf_error)
  579. {
  580. APP_ERROR_HANDLER(nrf_error);
  581. }
  582. static void conn_params_init(void)
  583. {
  584. ret_code_t err_code;
  585. ble_conn_params_init_t cp_init;
  586. memset(&cp_init, 0, sizeof(cp_init));
  587. cp_init.p_conn_params = NULL;
  588. cp_init.first_conn_params_update_delay = FIRST_CONN_PARAMS_UPDATE_DELAY;
  589. cp_init.next_conn_params_update_delay = NEXT_CONN_PARAMS_UPDATE_DELAY;
  590. cp_init.max_conn_params_update_count = MAX_CONN_PARAMS_UPDATE_COUNT;
  591. cp_init.start_on_notify_cccd_handle = BLE_CONN_HANDLE_INVALID; // Start upon connection.
  592. cp_init.disconnect_on_fail = true;
  593. cp_init.evt_handler = NULL; // Ignore events.
  594. cp_init.error_handler = conn_params_error_handler;
  595. err_code = ble_conn_params_init(&cp_init);
  596. APP_ERROR_CHECK(err_code);
  597. }
  598. static void nrf_qwr_error_handler(uint32_t nrf_error)//队列写错误操作
  599. {
  600. APP_ERROR_HANDLER(nrf_error);
  601. }
  602. //从 BLE 接受数据
  603. static void nus_data_handler(ble_nus_evt_t * p_evt)
  604. {
  605. if (p_evt->type == BLE_NUS_EVT_RX_DATA)
  606. {
  607. BLE_Client_Push((unsigned char*)(p_evt->params.rx_data.p_data), p_evt->params.rx_data.length);
  608. }
  609. }
  610. void ble_nus_send_buff(uint8_t *p,uint16_t len)
  611. {
  612. if(isClientConnet==0) return;
  613. ble_nus_data_send(&m_nus, p, &len, m_conn_handle);
  614. }
  615. static void services_init(void)//服务初始化
  616. {
  617. uint32_t err_code;
  618. ble_nus_init_t nus_init;
  619. nrf_ble_qwr_init_t qwr_init = {0};
  620. // Initialize Queued Write Module.
  621. qwr_init.error_handler = nrf_qwr_error_handler;
  622. for (uint32_t i = 0; i < NRF_SDH_BLE_TOTAL_LINK_COUNT; i++)
  623. {
  624. err_code = nrf_ble_qwr_init(&m_qwr[i], &qwr_init);
  625. APP_ERROR_CHECK(err_code);
  626. }
  627. // Initialize NUS.
  628. memset(&nus_init, 0, sizeof(nus_init));
  629. nus_init.data_handler = nus_data_handler;
  630. err_code = ble_nus_init(&m_nus, &nus_init);
  631. APP_ERROR_CHECK(err_code);
  632. }
  633. static void gap_params_init(void)//GAP初始化
  634. {
  635. uint32_t err_code;
  636. ble_gap_conn_params_t gap_conn_params;
  637. ble_gap_conn_sec_mode_t sec_mode;
  638. #if USE_LADDR == 1
  639. ble_gap_addr_t m_my_addr;
  640. char BleReallyName[30]={0};
  641. #endif
  642. BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode);
  643. #if USE_LADDR == 1
  644. err_code = sd_ble_gap_addr_get(&m_my_addr);
  645. APP_ERROR_CHECK(err_code);
  646. #if PROJECT_SLECT == 8
  647. sprintf(BleReallyName,"%s_L%02X%02X",DEVICE_NAME,m_my_addr.addr[1],m_my_addr.addr[0]);
  648. #endif
  649. #if PROJECT_SLECT == 9
  650. sprintf(BleReallyName,"%s_R%02X%02X",DEVICE_NAME,m_my_addr.addr[1],m_my_addr.addr[0]);
  651. #endif
  652. err_code = sd_ble_gap_device_name_set(&sec_mode,
  653. (const uint8_t *) BleReallyName,
  654. strlen(DEVICE_NAME)+7);
  655. #else
  656. err_code = sd_ble_gap_device_name_set(&sec_mode,
  657. (const uint8_t *) DEVICE_NAME,
  658. strlen(DEVICE_NAME));
  659. #endif
  660. APP_ERROR_CHECK(err_code);
  661. memset(&gap_conn_params, 0, sizeof(gap_conn_params));
  662. gap_conn_params.min_conn_interval = MIN_CONN_INTERVAL;
  663. gap_conn_params.max_conn_interval = MAX_CONN_INTERVAL;
  664. gap_conn_params.slave_latency = SLAVE_LATENCY;
  665. gap_conn_params.conn_sup_timeout = CONN_SUP_TIMEOUT;
  666. err_code = sd_ble_gap_ppcp_set(&gap_conn_params);
  667. APP_ERROR_CHECK(err_code);
  668. }
  669. static void advertising_init(void)
  670. {
  671. uint32_t err_code;
  672. ble_advertising_init_t init;
  673. memset(&init, 0, sizeof(init));
  674. init.advdata.name_type = BLE_ADVDATA_FULL_NAME;
  675. init.advdata.include_appearance = false;
  676. init.advdata.flags = BLE_GAP_ADV_FLAGS_LE_ONLY_LIMITED_DISC_MODE;
  677. init.srdata.uuids_complete.uuid_cnt = sizeof(m_adv_uuids) / sizeof(m_adv_uuids[0]);
  678. init.srdata.uuids_complete.p_uuids = m_adv_uuids;
  679. init.config.ble_adv_fast_enabled = true;
  680. init.config.ble_adv_fast_interval = APP_ADV_INTERVAL;
  681. init.config.ble_adv_fast_timeout = APP_ADV_DURATION;
  682. init.evt_handler = on_adv_evt;
  683. err_code = ble_advertising_init(&m_advertising, &init);
  684. APP_ERROR_CHECK(err_code);
  685. ble_advertising_conn_cfg_tag_set(&m_advertising, APP_BLE_CONN_CFG_TAG);
  686. }
  687. //static void adv_scan_start(void)
  688. //{
  689. //#if BLESLAVE
  690. // ret_code_t err_code;
  691. //#endif
  692. // //check if there are no flash operations in progress
  693. // if (!nrf_fstorage_is_busy(NULL))
  694. // {
  695. // // Start scanning for peripherals and initiate connection to devices which
  696. // // advertise Heart Rate or Running speed and cadence UUIDs.
  697. //#if BLEHOST
  698. // scan_start();//开始扫描
  699. //#endif
  700. // // Start advertising.
  701. //#if BLESLAVE
  702. // err_code = ble_advertising_start(&m_advertising, BLE_ADV_MODE_FAST);//同时开始广播
  703. // APP_ERROR_CHECK(err_code);
  704. //#endif
  705. // }
  706. //}
  707. void advertising_start(void)
  708. {
  709. #if BLESLAVE
  710. ret_code_t err_code;
  711. err_code = ble_advertising_start(&m_advertising, BLE_ADV_MODE_FAST);//同时开始广播
  712. APP_ERROR_CHECK(err_code);
  713. #endif
  714. }
  715. void senduart(unsigned char* bytes,int len)
  716. {
  717. for(int i=0;i<len;i++) app_uart_put(bytes[i]); //串口输出数据
  718. }
  719. void Advertising_Config(void)
  720. {
  721. gap_params_init();//添加的GAP初始化
  722. conn_params_init();//添加的连接参数初始化
  723. services_init();//添加从机服务初始化
  724. advertising_init();//添加广播初始化
  725. }
  726. static bool ble_evt_is_advertising_timeout(ble_evt_t const * p_ble_evt)
  727. {
  728. return (p_ble_evt->header.evt_id == BLE_GAP_EVT_ADV_SET_TERMINATED);
  729. }
  730. /**@brief Function for handling BLE events.
  731. *
  732. * @param[in] p_ble_evt Bluetooth stack event.
  733. * @param[in] p_context Unused.
  734. */
  735. static void ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context)
  736. {
  737. uint16_t conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
  738. uint16_t role = ble_conn_state_role(conn_handle);
  739. // Based on the role this device plays in the connection, dispatch to the right handler.不同角色下所做的处理
  740. if (role == BLE_GAP_ROLE_PERIPH || ble_evt_is_advertising_timeout(p_ble_evt))
  741. {
  742. // ble_nus_on_ble_evt(p_ble_evt, &m_nus);
  743. on_ble_peripheral_evt(p_ble_evt);
  744. }
  745. else if ((role == BLE_GAP_ROLE_CENTRAL) || (p_ble_evt->header.evt_id == BLE_GAP_EVT_ADV_REPORT))
  746. {
  747. // ble_nus_c_on_ble_evt(p_ble_evt, &m_ble_nus_c);
  748. on_ble_central_evt(p_ble_evt,NULL);
  749. }
  750. else
  751. {
  752. SEGGER_RTT_printf(0,"ble_evt_handler -> other\n");
  753. }
  754. }
  755. /**@brief Function for initializing the BLE stack.
  756. *
  757. * @details Initializes the SoftDevice and the BLE event interrupt.
  758. */
  759. static void ble_stack_init(void)
  760. {
  761. ret_code_t err_code;
  762. err_code = nrf_sdh_enable_request();
  763. APP_ERROR_CHECK(err_code);
  764. // Configure the BLE stack using the default settings.
  765. // Fetch the start address of the application RAM.
  766. uint32_t ram_start = 0;
  767. err_code = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &ram_start);
  768. APP_ERROR_CHECK(err_code);
  769. // Enable BLE stack.
  770. err_code = nrf_sdh_ble_enable(&ram_start);
  771. APP_ERROR_CHECK(err_code);
  772. // Register a handler for BLE events.
  773. NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, ble_evt_handler, NULL);
  774. }
  775. uint8_t BLE_Client_Isconneted(void)
  776. {
  777. return isClientConnet;
  778. }
  779. uint8_t BLE_Host_Isconneted(void)
  780. {
  781. return isHostConnet;
  782. }
  783. int8_t sd_ble_gap_rssi_get_user(void)
  784. {
  785. int8_t rssi =0;
  786. unsigned char pch_chan=0;
  787. sd_ble_gap_rssi_get(m_ble_nus_c.conn_handle, &rssi,&pch_chan);
  788. return rssi;
  789. }
  790. extern void PRE_Init(void);
  791. extern void USR_Init(void);
  792. extern void USR_Process(void);
  793. int main(void)
  794. {
  795. // log_init();
  796. PRE_Init(); //用户初始化
  797. timer_init();
  798. TIME_Init();
  799. // uart_init();
  800. db_discovery_init();
  801. power_management_init();
  802. ble_stack_init();
  803. gatt_init();
  804. nus_c_init();
  805. scan_init();
  806. scan_start();//开始扫描
  807. SEGGER_RTT_printf(0,"Uart BLE_Host started.\r\n");
  808. Advertising_Config();
  809. ble_advertising_start(&m_advertising, BLE_ADV_MODE_FAST);
  810. SEGGER_RTT_printf(0,"Uart BLE_Slave started.\r\n");
  811. USR_Init(); //用户初始化
  812. while (1)
  813. {
  814. USR_Process();
  815. }
  816. }