ble_nus_app.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. #include "nordic_common.h"
  2. #include "nrf.h"
  3. #include "ble_hci.h"
  4. #include "ble_advdata.h"
  5. #include "ble_advertising.h"
  6. #include "ble_conn_params.h"
  7. #include "softdevice_handler.h"
  8. #include "nrf_ble_gatt.h"
  9. #include "app_timer.h"
  10. #include "ble_nus.h"
  11. #include "app_util_platform.h"
  12. #include <rtthread.h>
  13. typedef rt_size_t (*BLE_NOTIFY_T)(rt_uint8_t *buf, rt_uint16_t size);
  14. #define STACK_EVT_MQ_NUM 10
  15. #define FAST_ADV() \
  16. do { \
  17. uint32_t err_code; \
  18. err_code = ble_advertising_start(BLE_ADV_MODE_FAST); \
  19. APP_ERROR_CHECK(err_code); \
  20. } while(0)
  21. typedef enum
  22. {
  23. STACK_EV_DISCON = 1,
  24. STACK_EV_DISPATCH = 2,
  25. STACK_EV_KEY = 4,
  26. } STACK_EV_E;
  27. typedef struct
  28. {
  29. rt_list_t node;
  30. void* evt;
  31. } evt_list_t;
  32. typedef enum
  33. {
  34. STACK_STATE_IDLE = 0,
  35. STACK_STATE_ADV = 1,
  36. STACK_STATE_CON = 2,
  37. STACK_STATE_DISC = 3
  38. } STACK_STATE_E;
  39. STACK_STATE_E stack_state = STACK_STATE_IDLE;
  40. rt_event_t stack_event;
  41. rt_sem_t sd_evt_sem;
  42. rt_mq_t stack_evt_mq;
  43. rt_uint8_t *evt_sample;
  44. BLE_NOTIFY_T rx_notify = RT_NULL;
  45. // Low frequency clock source to be used by the SoftDevice
  46. #define NRF_CLOCK_LFCLKSRC {.source = NRF_CLOCK_LF_SRC_XTAL, \
  47. .rc_ctiv = 0, \
  48. .rc_temp_ctiv = 0, \
  49. .xtal_accuracy = NRF_CLOCK_LF_XTAL_ACCURACY_20_PPM}
  50. #define CONN_CFG_TAG 1 /**< A tag that refers to the BLE stack configuration we set with @ref sd_ble_cfg_set. Default tag is @ref BLE_CONN_CFG_TAG_DEFAULT. */
  51. #define APP_FEATURE_NOT_SUPPORTED BLE_GATT_STATUS_ATTERR_APP_BEGIN + 2 /**< Reply when unsupported features are requested. */
  52. #define DEVICE_NAME "Nordic_UART" /**< Name of device. Will be included in the advertising data. */
  53. #define NUS_SERVICE_UUID_TYPE BLE_UUID_TYPE_VENDOR_BEGIN /**< UUID type for the Nordic UART Service (vendor specific). */
  54. #define APP_ADV_INTERVAL 64 /**< The advertising interval (in units of 0.625 ms. This value corresponds to 40 ms). */
  55. #define APP_ADV_TIMEOUT_IN_SECONDS 30 /**< The advertising timeout (in units of seconds). */
  56. #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. */
  57. #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. */
  58. #define SLAVE_LATENCY 0 /**< Slave latency. */
  59. #define CONN_SUP_TIMEOUT MSEC_TO_UNITS(4000, UNIT_10_MS) /**< Connection supervisory timeout (4 seconds), Supervision Timeout uses 10 ms units. */
  60. #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). */
  61. #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). */
  62. #define MAX_CONN_PARAMS_UPDATE_COUNT 3 /**< Number of attempts before giving up the connection parameter negotiation. */
  63. #define DEAD_BEEF 0xDEADBEEF /**< Value used as error code on stack dump, can be used to identify stack location on stack unwind. */
  64. #define UART_TX_BUF_SIZE 256 /**< UART TX buffer size. */
  65. #define UART_RX_BUF_SIZE 256 /**< UART RX buffer size. */
  66. static ble_nus_t m_nus; /**< Structure to identify the Nordic UART Service. */
  67. static uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID; /**< Handle of the current connection. */
  68. static nrf_ble_gatt_t m_gatt; /**< GATT module instance. */
  69. static ble_uuid_t m_adv_uuids[] = {{BLE_UUID_NUS_SERVICE, NUS_SERVICE_UUID_TYPE}}; /**< Universally unique service identifier. */
  70. static uint16_t m_ble_nus_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. */
  71. /**@brief Function for assert macro callback.
  72. *
  73. * @details This function will be called in case of an assert in the SoftDevice.
  74. *
  75. * @warning This handler is an example only and does not fit a final product. You need to analyse
  76. * how your product is supposed to react in case of Assert.
  77. * @warning On assert from the SoftDevice, the system can only recover on reset.
  78. *
  79. * @param[in] line_num Line number of the failing ASSERT call.
  80. * @param[in] p_file_name File name of the failing ASSERT call.
  81. */
  82. void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name)
  83. {
  84. app_error_handler(DEAD_BEEF, line_num, p_file_name);
  85. }
  86. /**@brief Function for the GAP initialization.
  87. *
  88. * @details This function will set up all the necessary GAP (Generic Access Profile) parameters of
  89. * the device. It also sets the permissions and appearance.
  90. */
  91. static void gap_params_init(void)
  92. {
  93. uint32_t err_code;
  94. ble_gap_conn_params_t gap_conn_params;
  95. ble_gap_conn_sec_mode_t sec_mode;
  96. BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode);
  97. err_code = sd_ble_gap_device_name_set(&sec_mode,
  98. (const uint8_t *) DEVICE_NAME,
  99. strlen(DEVICE_NAME));
  100. APP_ERROR_CHECK(err_code);
  101. memset(&gap_conn_params, 0, sizeof(gap_conn_params));
  102. gap_conn_params.min_conn_interval = MIN_CONN_INTERVAL;
  103. gap_conn_params.max_conn_interval = MAX_CONN_INTERVAL;
  104. gap_conn_params.slave_latency = SLAVE_LATENCY;
  105. gap_conn_params.conn_sup_timeout = CONN_SUP_TIMEOUT;
  106. err_code = sd_ble_gap_ppcp_set(&gap_conn_params);
  107. APP_ERROR_CHECK(err_code);
  108. }
  109. /**@brief Function for handling the data from the Nordic UART Service.
  110. *
  111. * @details This function will process the data received from the Nordic UART BLE Service and send
  112. * it to the UART module.
  113. *
  114. * @param[in] p_nus Nordic UART Service structure.
  115. * @param[in] p_data Data to be send to UART module.
  116. * @param[in] length Length of the data.
  117. */
  118. /**@snippet [Handling the data received over BLE] */
  119. static void nus_data_handler(ble_nus_t * p_nus, uint8_t * p_data, uint16_t length)
  120. {
  121. rt_kprintf("Received data from BLE NUS. Writing data on UART.\r\n");
  122. for (uint32_t i = 0; i < length; i++)
  123. {
  124. rt_kprintf("%02x ", p_data[i]);
  125. }
  126. // ble_send(p_data, length);
  127. if (rx_notify != RT_NULL)
  128. {
  129. rx_notify(p_data, length);
  130. }
  131. }
  132. /**@snippet [Handling the data received over BLE] */
  133. /**@brief Function for initializing services that will be used by the application.
  134. */
  135. static void services_init(void)
  136. {
  137. uint32_t err_code;
  138. ble_nus_init_t nus_init;
  139. memset(&nus_init, 0, sizeof(nus_init));
  140. nus_init.data_handler = nus_data_handler;
  141. err_code = ble_nus_init(&m_nus, &nus_init);
  142. APP_ERROR_CHECK(err_code);
  143. }
  144. /**@brief Function for handling an event from the Connection Parameters Module.
  145. *
  146. * @details This function will be called for all events in the Connection Parameters Module
  147. * which are passed to the application.
  148. *
  149. * @note All this function does is to disconnect. This could have been done by simply setting
  150. * the disconnect_on_fail config parameter, but instead we use the event handler
  151. * mechanism to demonstrate its use.
  152. *
  153. * @param[in] p_evt Event received from the Connection Parameters Module.
  154. */
  155. static void on_conn_params_evt(ble_conn_params_evt_t * p_evt)
  156. {
  157. uint32_t err_code;
  158. if (p_evt->evt_type == BLE_CONN_PARAMS_EVT_FAILED)
  159. {
  160. err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_CONN_INTERVAL_UNACCEPTABLE);
  161. APP_ERROR_CHECK(err_code);
  162. }
  163. }
  164. /**@brief Function for handling errors from the Connection Parameters module.
  165. *
  166. * @param[in] nrf_error Error code containing information about what went wrong.
  167. */
  168. static void conn_params_error_handler(uint32_t nrf_error)
  169. {
  170. APP_ERROR_HANDLER(nrf_error);
  171. }
  172. /**@brief Function for initializing the Connection Parameters module.
  173. */
  174. static void conn_params_init(void)
  175. {
  176. uint32_t err_code;
  177. ble_conn_params_init_t cp_init;
  178. memset(&cp_init, 0, sizeof(cp_init));
  179. cp_init.p_conn_params = NULL;
  180. cp_init.first_conn_params_update_delay = FIRST_CONN_PARAMS_UPDATE_DELAY;
  181. cp_init.next_conn_params_update_delay = NEXT_CONN_PARAMS_UPDATE_DELAY;
  182. cp_init.max_conn_params_update_count = MAX_CONN_PARAMS_UPDATE_COUNT;
  183. cp_init.start_on_notify_cccd_handle = BLE_GATT_HANDLE_INVALID;
  184. cp_init.disconnect_on_fail = false;
  185. cp_init.evt_handler = on_conn_params_evt;
  186. cp_init.error_handler = conn_params_error_handler;
  187. err_code = ble_conn_params_init(&cp_init);
  188. APP_ERROR_CHECK(err_code);
  189. }
  190. /**@brief Function for handling advertising events.
  191. *
  192. * @details This function will be called for advertising events which are passed to the application.
  193. *
  194. * @param[in] ble_adv_evt Advertising event.
  195. */
  196. static void on_adv_evt(ble_adv_evt_t ble_adv_evt)
  197. {
  198. // uint32_t err_code;
  199. switch (ble_adv_evt)
  200. {
  201. case BLE_ADV_EVT_FAST:
  202. // err_code = bsp_indication_set(BSP_INDICATE_ADVERTISING);
  203. // APP_ERROR_CHECK(err_code);
  204. stack_state = STACK_STATE_ADV;
  205. rt_kprintf("fast advert\n");
  206. break;
  207. case BLE_ADV_EVT_IDLE:
  208. // sleep_mode_enter();
  209. stack_state = STACK_STATE_IDLE;
  210. rt_kprintf("advert idle\n");
  211. break;
  212. default:
  213. break;
  214. }
  215. }
  216. /**@brief Function for the application's SoftDevice event handler.
  217. *
  218. * @param[in] p_ble_evt SoftDevice event.
  219. */
  220. static void on_ble_evt(ble_evt_t * p_ble_evt)
  221. {
  222. uint32_t err_code;
  223. switch (p_ble_evt->header.evt_id)
  224. {
  225. case BLE_GAP_EVT_CONNECTED:
  226. // err_code = bsp_indication_set(BSP_INDICATE_CONNECTED);
  227. // APP_ERROR_CHECK(err_code);
  228. m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
  229. stack_state = STACK_STATE_CON;
  230. rt_kprintf("Connected\r\n");
  231. break; // BLE_GAP_EVT_CONNECTED
  232. case BLE_GAP_EVT_DISCONNECTED:
  233. // err_code = bsp_indication_set(BSP_INDICATE_IDLE);
  234. // APP_ERROR_CHECK(err_code);
  235. m_conn_handle = BLE_CONN_HANDLE_INVALID;
  236. stack_state = STACK_STATE_DISC;
  237. rt_kprintf("Disconnected\r\n");
  238. break; // BLE_GAP_EVT_DISCONNECTED
  239. case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
  240. // Pairing not supported
  241. err_code = sd_ble_gap_sec_params_reply(m_conn_handle, BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP, NULL, NULL);
  242. APP_ERROR_CHECK(err_code);
  243. break; // BLE_GAP_EVT_SEC_PARAMS_REQUEST
  244. case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
  245. {
  246. ble_gap_data_length_params_t dl_params;
  247. // Clearing the struct will effectivly set members to @ref BLE_GAP_DATA_LENGTH_AUTO
  248. memset(&dl_params, 0, sizeof(ble_gap_data_length_params_t));
  249. err_code = sd_ble_gap_data_length_update(p_ble_evt->evt.gap_evt.conn_handle, &dl_params, NULL);
  250. APP_ERROR_CHECK(err_code);
  251. } break;
  252. case BLE_GATTS_EVT_SYS_ATTR_MISSING:
  253. // No system attributes have been stored.
  254. err_code = sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0, 0);
  255. APP_ERROR_CHECK(err_code);
  256. break; // BLE_GATTS_EVT_SYS_ATTR_MISSING
  257. case BLE_GATTC_EVT_TIMEOUT:
  258. // Disconnect on GATT Client timeout event.
  259. err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
  260. BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  261. APP_ERROR_CHECK(err_code);
  262. break; // BLE_GATTC_EVT_TIMEOUT
  263. case BLE_GATTS_EVT_TIMEOUT:
  264. // Disconnect on GATT Server timeout event.
  265. err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
  266. BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  267. APP_ERROR_CHECK(err_code);
  268. break; // BLE_GATTS_EVT_TIMEOUT
  269. case BLE_EVT_USER_MEM_REQUEST:
  270. err_code = sd_ble_user_mem_reply(p_ble_evt->evt.gattc_evt.conn_handle, NULL);
  271. APP_ERROR_CHECK(err_code);
  272. break; // BLE_EVT_USER_MEM_REQUEST
  273. case BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST:
  274. {
  275. ble_gatts_evt_rw_authorize_request_t req;
  276. ble_gatts_rw_authorize_reply_params_t auth_reply;
  277. req = p_ble_evt->evt.gatts_evt.params.authorize_request;
  278. if (req.type != BLE_GATTS_AUTHORIZE_TYPE_INVALID)
  279. {
  280. if ((req.request.write.op == BLE_GATTS_OP_PREP_WRITE_REQ) ||
  281. (req.request.write.op == BLE_GATTS_OP_EXEC_WRITE_REQ_NOW) ||
  282. (req.request.write.op == BLE_GATTS_OP_EXEC_WRITE_REQ_CANCEL))
  283. {
  284. if (req.type == BLE_GATTS_AUTHORIZE_TYPE_WRITE)
  285. {
  286. auth_reply.type = BLE_GATTS_AUTHORIZE_TYPE_WRITE;
  287. }
  288. else
  289. {
  290. auth_reply.type = BLE_GATTS_AUTHORIZE_TYPE_READ;
  291. }
  292. auth_reply.params.write.gatt_status = APP_FEATURE_NOT_SUPPORTED;
  293. err_code = sd_ble_gatts_rw_authorize_reply(p_ble_evt->evt.gatts_evt.conn_handle,
  294. &auth_reply);
  295. APP_ERROR_CHECK(err_code);
  296. }
  297. }
  298. } break; // BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST
  299. default:
  300. // No implementation needed.
  301. break;
  302. }
  303. }
  304. /**@brief Function for dispatching a SoftDevice event to all modules with a SoftDevice
  305. * event handler.
  306. *
  307. * @details This function is called from the SoftDevice event interrupt handler after a
  308. * SoftDevice event has been received.
  309. *
  310. * @param[in] p_ble_evt SoftDevice event.
  311. */
  312. static void ble_evt_dispatch(ble_evt_t * p_ble_evt)
  313. {
  314. if (rt_mq_send(stack_evt_mq, p_ble_evt, p_ble_evt->header.evt_len) != RT_EOK)
  315. {
  316. rt_kprintf("dispatch malloc failure\n");
  317. }
  318. else
  319. {
  320. rt_event_send(stack_event, STACK_EV_DISPATCH);
  321. }
  322. }
  323. static rt_err_t evt_dispatch_worker(void)
  324. {
  325. ble_evt_t * p_ble_evt = (ble_evt_t *)evt_sample;
  326. rt_err_t err;
  327. err = rt_mq_recv(stack_evt_mq, (void*)evt_sample, BLE_STACK_EVT_MSG_BUF_SIZE, RT_WAITING_NO);
  328. if (RT_EOK == err)
  329. {
  330. ble_conn_params_on_ble_evt(p_ble_evt);
  331. nrf_ble_gatt_on_ble_evt(&m_gatt, p_ble_evt);
  332. ble_nus_on_ble_evt(&m_nus, p_ble_evt);
  333. on_ble_evt(p_ble_evt);
  334. ble_advertising_on_ble_evt(p_ble_evt);
  335. // bsp_btn_ble_on_ble_evt(p_ble_evt);
  336. rt_kprintf("ble evt dispatch\n");
  337. }
  338. return err;
  339. }
  340. static uint32_t _softdevice_evt_schedule(void)
  341. {
  342. rt_sem_release(sd_evt_sem);
  343. return NRF_SUCCESS;
  344. }
  345. /**@brief Function for the SoftDevice initialization.
  346. *
  347. * @details This function initializes the SoftDevice and the BLE event interrupt.
  348. */
  349. static void ble_stack_init(void)
  350. {
  351. uint32_t err_code;
  352. nrf_clock_lf_cfg_t clock_lf_cfg = NRF_CLOCK_LFCLKSRC;
  353. // Initialize SoftDevice.
  354. SOFTDEVICE_HANDLER_INIT(&clock_lf_cfg, _softdevice_evt_schedule);
  355. // Fetch the start address of the application RAM.
  356. uint32_t ram_start = 0;
  357. err_code = softdevice_app_ram_start_get(&ram_start);
  358. APP_ERROR_CHECK(err_code);
  359. // Overwrite some of the default configurations for the BLE stack.
  360. ble_cfg_t ble_cfg;
  361. // Configure the maximum number of connections.
  362. memset(&ble_cfg, 0, sizeof(ble_cfg));
  363. ble_cfg.gap_cfg.role_count_cfg.periph_role_count = BLE_GAP_ROLE_COUNT_PERIPH_DEFAULT;
  364. ble_cfg.gap_cfg.role_count_cfg.central_role_count = 0;
  365. ble_cfg.gap_cfg.role_count_cfg.central_sec_count = 0;
  366. err_code = sd_ble_cfg_set(BLE_GAP_CFG_ROLE_COUNT, &ble_cfg, ram_start);
  367. APP_ERROR_CHECK(err_code);
  368. // Configure the maximum ATT MTU.
  369. memset(&ble_cfg, 0x00, sizeof(ble_cfg));
  370. ble_cfg.conn_cfg.conn_cfg_tag = CONN_CFG_TAG;
  371. ble_cfg.conn_cfg.params.gatt_conn_cfg.att_mtu = NRF_BLE_GATT_MAX_MTU_SIZE;
  372. err_code = sd_ble_cfg_set(BLE_CONN_CFG_GATT, &ble_cfg, ram_start);
  373. APP_ERROR_CHECK(err_code);
  374. // Configure the maximum event length.
  375. memset(&ble_cfg, 0x00, sizeof(ble_cfg));
  376. ble_cfg.conn_cfg.conn_cfg_tag = CONN_CFG_TAG;
  377. ble_cfg.conn_cfg.params.gap_conn_cfg.event_length = 320;
  378. ble_cfg.conn_cfg.params.gap_conn_cfg.conn_count = BLE_GAP_CONN_COUNT_DEFAULT;
  379. err_code = sd_ble_cfg_set(BLE_CONN_CFG_GAP, &ble_cfg, ram_start);
  380. APP_ERROR_CHECK(err_code);
  381. // Enable BLE stack.
  382. err_code = softdevice_enable(&ram_start);
  383. APP_ERROR_CHECK(err_code);
  384. // Subscribe for BLE events.
  385. err_code = softdevice_ble_evt_handler_set(ble_evt_dispatch);
  386. APP_ERROR_CHECK(err_code);
  387. }
  388. /**@brief Function for handling events from the GATT library. */
  389. static void gatt_evt_handler(nrf_ble_gatt_t * p_gatt, const nrf_ble_gatt_evt_t * p_evt)
  390. {
  391. if ((m_conn_handle == p_evt->conn_handle) && (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED))
  392. {
  393. m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;
  394. rt_kprintf("Data len is set to 0x%X(%d)\r\n", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
  395. }
  396. rt_kprintf("ATT MTU exchange completed. central 0x%x peripheral 0x%x\r\n", p_gatt->att_mtu_desired_central, p_gatt->att_mtu_desired_periph);
  397. }
  398. /**@brief Function for initializing the GATT library. */
  399. static void gatt_init(void)
  400. {
  401. ret_code_t err_code;
  402. err_code = nrf_ble_gatt_init(&m_gatt, gatt_evt_handler);
  403. APP_ERROR_CHECK(err_code);
  404. err_code = nrf_ble_gatt_att_mtu_periph_set(&m_gatt, 64);
  405. APP_ERROR_CHECK(err_code);
  406. }
  407. /**@brief Function for initializing the Advertising functionality.
  408. */
  409. static void advertising_init(void)
  410. {
  411. uint32_t err_code;
  412. ble_advdata_t advdata;
  413. ble_advdata_t scanrsp;
  414. ble_adv_modes_config_t options;
  415. // Build advertising data struct to pass into @ref ble_advertising_init.
  416. memset(&advdata, 0, sizeof(advdata));
  417. advdata.name_type = BLE_ADVDATA_FULL_NAME;
  418. advdata.include_appearance = false;
  419. advdata.flags = BLE_GAP_ADV_FLAGS_LE_ONLY_LIMITED_DISC_MODE;
  420. memset(&scanrsp, 0, sizeof(scanrsp));
  421. scanrsp.uuids_complete.uuid_cnt = sizeof(m_adv_uuids) / sizeof(m_adv_uuids[0]);
  422. scanrsp.uuids_complete.p_uuids = m_adv_uuids;
  423. memset(&options, 0, sizeof(options));
  424. options.ble_adv_fast_enabled = true;
  425. options.ble_adv_fast_interval = APP_ADV_INTERVAL;
  426. options.ble_adv_fast_timeout = APP_ADV_TIMEOUT_IN_SECONDS;
  427. err_code = ble_advertising_init(&advdata, &scanrsp, &options, on_adv_evt, NULL);
  428. APP_ERROR_CHECK(err_code);
  429. ble_advertising_conn_cfg_tag_set(CONN_CFG_TAG);
  430. }
  431. /**@brief Function for handling app_uart events.
  432. *
  433. * @details This function will receive a single character from the app_uart module and append it to
  434. * a string. The string will be be sent over BLE when the last character received was a
  435. * 'new line' '\n' (hex 0x0A) or if the string has reached the maximum data length.
  436. */
  437. /**@snippet [Handling the data received over UART] */
  438. void uart_event_handle(rt_device_t uart)
  439. {
  440. uint8_t data_array[BLE_NUS_MAX_DATA_LEN];
  441. rt_size_t size = 0;
  442. uint32_t err_code;
  443. size = rt_device_read(uart, 0, data_array, BLE_NUS_MAX_DATA_LEN);
  444. if (size <= 0)
  445. {
  446. return;
  447. }
  448. do
  449. {
  450. err_code = ble_nus_string_send(&m_nus, data_array, size);
  451. if ( (err_code != NRF_ERROR_INVALID_STATE) && (err_code != NRF_ERROR_BUSY) )
  452. {
  453. APP_ERROR_CHECK(err_code);
  454. }
  455. } while (err_code == NRF_ERROR_BUSY);
  456. }
  457. /**@snippet [Handling the data received over UART] */
  458. /**@brief Function for initializing the UART module.
  459. */
  460. /**@snippet [UART Initialization] */
  461. static rt_bool_t _stack_init(void)
  462. {
  463. uint32_t err_code;
  464. stack_event = rt_event_create("stackev", RT_IPC_FLAG_FIFO);
  465. sd_evt_sem = rt_sem_create("sdsem", 0, RT_IPC_FLAG_FIFO);
  466. stack_evt_mq = rt_mq_create("stackmq", BLE_STACK_EVT_MSG_BUF_SIZE, STACK_EVT_MQ_NUM, RT_IPC_FLAG_FIFO);
  467. evt_sample = rt_malloc(BLE_STACK_EVT_MSG_BUF_SIZE);
  468. if (!stack_event || !sd_evt_sem || !stack_evt_mq || !evt_sample)
  469. {
  470. rt_kprintf("uart rx sem create failure\n");
  471. return RT_FALSE;
  472. }
  473. // Initialize.
  474. err_code = app_timer_init();
  475. APP_ERROR_CHECK(err_code);
  476. ble_stack_init();
  477. gap_params_init();
  478. gatt_init();
  479. services_init();
  480. advertising_init();
  481. conn_params_init();
  482. return RT_TRUE;
  483. }
  484. /**@brief Application main function.
  485. */
  486. static void _stack_thread(void *parameter)
  487. {
  488. rt_tick_t next_timeout = (rt_tick_t)RT_WAITING_FOREVER;
  489. FAST_ADV();
  490. // Enter main loop.
  491. for (;;)
  492. {
  493. rt_uint32_t event = 0;
  494. rt_tick_t dispatch_timeout = RT_WAITING_NO;
  495. rt_event_recv(stack_event, STACK_EV_DISCON | STACK_EV_DISPATCH | STACK_EV_KEY,
  496. RT_EVENT_FLAG_OR | RT_EVENT_FLAG_CLEAR, next_timeout, &event);
  497. if (evt_dispatch_worker() != RT_EOK)
  498. {
  499. dispatch_timeout = (rt_tick_t)RT_WAITING_FOREVER;
  500. }
  501. if (event & STACK_EV_DISCON)
  502. {
  503. if (BLE_CONN_HANDLE_INVALID != m_conn_handle)
  504. {
  505. sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
  506. }
  507. }
  508. if (event & STACK_EV_KEY)
  509. {
  510. if (stack_state != STACK_STATE_CON && stack_state != STACK_STATE_ADV)
  511. {
  512. FAST_ADV();
  513. }
  514. }
  515. next_timeout = (rt_tick_t)RT_WAITING_FOREVER;
  516. if (dispatch_timeout < next_timeout)
  517. {
  518. next_timeout = dispatch_timeout;
  519. }
  520. }
  521. }
  522. static void _softdevice_thread(void* parameter)
  523. {
  524. for (;;)
  525. {
  526. rt_sem_take(sd_evt_sem, RT_WAITING_FOREVER);
  527. intern_softdevice_events_execute();
  528. }
  529. }
  530. rt_err_t ble_init(void)
  531. {
  532. rt_thread_t thread;
  533. _stack_init();
  534. thread = rt_thread_create("sdth", _softdevice_thread, RT_NULL, 512, 0, 10);
  535. if (thread != RT_NULL)
  536. {
  537. rt_thread_startup(thread);
  538. }
  539. else
  540. {
  541. return RT_ERROR;
  542. }
  543. thread = rt_thread_create("bleth", _stack_thread, RT_NULL, 2048, 1, 10);
  544. if (thread != RT_NULL)
  545. {
  546. return rt_thread_startup(thread);
  547. }
  548. return RT_ERROR;
  549. }