main.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. /*
  2. * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Unlicense OR CC0-1.0
  5. */
  6. #include "esp_log.h"
  7. #include "nvs_flash.h"
  8. /* BLE */
  9. #include "nimble/nimble_port.h"
  10. #include "nimble/nimble_port_freertos.h"
  11. #include "host/ble_hs.h"
  12. #include "host/util/util.h"
  13. #include "console/console.h"
  14. #include "services/gap/ble_svc_gap.h"
  15. #include "ble_spp_client.h"
  16. #include "driver/uart.h"
  17. static const char *tag = "NimBLE_SPP_BLE_CENT";
  18. static int ble_spp_client_gap_event(struct ble_gap_event *event, void *arg);
  19. QueueHandle_t spp_common_uart_queue = NULL;
  20. void ble_store_config_init(void);
  21. uint16_t attribute_handle[CONFIG_BT_NIMBLE_MAX_CONNECTIONS];
  22. static void ble_spp_client_scan(void);
  23. static ble_addr_t connected_addr[CONFIG_BT_NIMBLE_MAX_CONNECTIONS];
  24. /* 16 Bit Alert Notification Service UUID */
  25. #define GATT_SVR_SVC_ALERT_UUID 0x1811
  26. /* 16 Bit SPP Service UUID */
  27. #define GATT_SPP_SVC_UUID 0xABF0
  28. /* 16 Bit SPP Service Characteristic UUID */
  29. #define GATT_SPP_CHR_UUID 0xABF1
  30. static void
  31. ble_spp_client_set_handle(const struct peer *peer)
  32. {
  33. const struct peer_chr *chr;
  34. chr = peer_chr_find_uuid(peer,
  35. BLE_UUID16_DECLARE(GATT_SPP_SVC_UUID),
  36. BLE_UUID16_DECLARE(GATT_SPP_CHR_UUID));
  37. attribute_handle[peer->conn_handle - 1] = chr->chr.val_handle;
  38. }
  39. /**
  40. * Called when service discovery of the specified peer has completed.
  41. */
  42. static void
  43. ble_spp_client_on_disc_complete(const struct peer *peer, int status, void *arg)
  44. {
  45. if (status != 0) {
  46. /* Service discovery failed. Terminate the connection. */
  47. MODLOG_DFLT(ERROR, "Error: Service discovery failed; status=%d "
  48. "conn_handle=%d\n", status, peer->conn_handle);
  49. ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM);
  50. return;
  51. }
  52. /* Service discovery has completed successfully. Now we have a complete
  53. * list of services, characteristics, and descriptors that the peer
  54. * supports.
  55. */
  56. MODLOG_DFLT(INFO, "Service discovery complete; status=%d "
  57. "conn_handle=%d\n", status, peer->conn_handle);
  58. ble_spp_client_set_handle(peer);
  59. #if CONFIG_BT_NIMBLE_MAX_CONNECTIONS > 1
  60. ble_spp_client_scan();
  61. #endif
  62. }
  63. /**
  64. * Initiates the GAP general discovery procedure.
  65. */
  66. static void
  67. ble_spp_client_scan(void)
  68. {
  69. uint8_t own_addr_type;
  70. struct ble_gap_disc_params disc_params;
  71. int rc;
  72. /* Figure out address to use while advertising (no privacy for now) */
  73. rc = ble_hs_id_infer_auto(0, &own_addr_type);
  74. if (rc != 0) {
  75. MODLOG_DFLT(ERROR, "error determining address type; rc=%d\n", rc);
  76. return;
  77. }
  78. /* Tell the controller to filter duplicates; we don't want to process
  79. * repeated advertisements from the same device.
  80. */
  81. disc_params.filter_duplicates = 1;
  82. /**
  83. * Perform a passive scan. I.e., don't send follow-up scan requests to
  84. * each advertiser.
  85. */
  86. disc_params.passive = 1;
  87. /* Use defaults for the rest of the parameters. */
  88. disc_params.itvl = 0;
  89. disc_params.window = 0;
  90. disc_params.filter_policy = 0;
  91. disc_params.limited = 0;
  92. rc = ble_gap_disc(own_addr_type, BLE_HS_FOREVER, &disc_params,
  93. ble_spp_client_gap_event, NULL);
  94. if (rc != 0) {
  95. MODLOG_DFLT(ERROR, "Error initiating GAP discovery procedure; rc=%d\n",
  96. rc);
  97. }
  98. }
  99. /**
  100. * Indicates whether we should try to connect to the sender of the specified
  101. * advertisement. The function returns a positive result if the device
  102. * advertises connectability and support for the Alert Notification service.
  103. */
  104. static int
  105. ble_spp_client_should_connect(const struct ble_gap_disc_desc *disc)
  106. {
  107. struct ble_hs_adv_fields fields;
  108. int rc;
  109. int i;
  110. /* Check if device is already connected or not */
  111. for ( i = 0; i < CONFIG_BT_NIMBLE_MAX_CONNECTIONS; i++) {
  112. if (memcmp(&connected_addr[i].val,disc->addr.val, sizeof(disc->addr.val)) == 0) {
  113. MODLOG_DFLT(DEBUG, "Device already connected");
  114. return 0;
  115. }
  116. }
  117. /* The device has to be advertising connectability. */
  118. if (disc->event_type != BLE_HCI_ADV_RPT_EVTYPE_ADV_IND &&
  119. disc->event_type != BLE_HCI_ADV_RPT_EVTYPE_DIR_IND) {
  120. return 0;
  121. }
  122. rc = ble_hs_adv_parse_fields(&fields, disc->data, disc->length_data);
  123. if (rc != 0) {
  124. return rc;
  125. }
  126. /* The device has to advertise support for the Alert Notification
  127. * service (0x1811).
  128. */
  129. for (i = 0; i < fields.num_uuids16; i++) {
  130. if (ble_uuid_u16(&fields.uuids16[i].u) == GATT_SVR_SVC_ALERT_UUID) {
  131. return 1;
  132. }
  133. }
  134. return 0;
  135. }
  136. /**
  137. * Connects to the sender of the specified advertisement of it looks
  138. * interesting. A device is "interesting" if it advertises connectability and
  139. * support for the Alert Notification service.
  140. */
  141. static void
  142. ble_spp_client_connect_if_interesting(const struct ble_gap_disc_desc *disc)
  143. {
  144. uint8_t own_addr_type;
  145. int rc;
  146. /* Don't do anything if we don't care about this advertiser. */
  147. if (!ble_spp_client_should_connect(disc)) {
  148. return;
  149. }
  150. /* Scanning must be stopped before a connection can be initiated. */
  151. rc = ble_gap_disc_cancel();
  152. if (rc != 0) {
  153. MODLOG_DFLT(DEBUG, "Failed to cancel scan; rc=%d\n", rc);
  154. return;
  155. }
  156. /* Figure out address to use for connect (no privacy for now) */
  157. rc = ble_hs_id_infer_auto(0, &own_addr_type);
  158. if (rc != 0) {
  159. MODLOG_DFLT(ERROR, "error determining address type; rc=%d\n", rc);
  160. return;
  161. }
  162. /* Try to connect the the advertiser. Allow 30 seconds (30000 ms) for
  163. * timeout.
  164. */
  165. rc = ble_gap_connect(own_addr_type, &disc->addr, 30000, NULL,
  166. ble_spp_client_gap_event, NULL);
  167. if (rc != 0) {
  168. MODLOG_DFLT(ERROR, "Error: Failed to connect to device; addr_type=%d "
  169. "addr=%s; rc=%d\n",
  170. disc->addr.type, addr_str(disc->addr.val), rc);
  171. return;
  172. }
  173. }
  174. /**
  175. * The nimble host executes this callback when a GAP event occurs. The
  176. * application associates a GAP event callback with each connection that is
  177. * established. ble_spp_client uses the same callback for all connections.
  178. *
  179. * @param event The event being signalled.
  180. * @param arg Application-specified argument; unused by
  181. * ble_spp_client.
  182. *
  183. * @return 0 if the application successfully handled the
  184. * event; nonzero on failure. The semantics
  185. * of the return code is specific to the
  186. * particular GAP event being signalled.
  187. */
  188. static int
  189. ble_spp_client_gap_event(struct ble_gap_event *event, void *arg)
  190. {
  191. struct ble_gap_conn_desc desc;
  192. struct ble_hs_adv_fields fields;
  193. int rc;
  194. switch (event->type) {
  195. case BLE_GAP_EVENT_DISC:
  196. rc = ble_hs_adv_parse_fields(&fields, event->disc.data,
  197. event->disc.length_data);
  198. if (rc != 0) {
  199. return 0;
  200. }
  201. /* An advertisment report was received during GAP discovery. */
  202. print_adv_fields(&fields);
  203. /* Try to connect to the advertiser if it looks interesting. */
  204. ble_spp_client_connect_if_interesting(&event->disc);
  205. return 0;
  206. case BLE_GAP_EVENT_CONNECT:
  207. /* A new connection was established or a connection attempt failed. */
  208. if (event->connect.status == 0) {
  209. /* Connection successfully established. */
  210. MODLOG_DFLT(INFO, "Connection established ");
  211. rc = ble_gap_conn_find(event->connect.conn_handle, &desc);
  212. assert(rc == 0);
  213. memcpy(&connected_addr[event->connect.conn_handle - 1].val, desc.peer_id_addr.val,
  214. sizeof(desc.peer_id_addr.val));
  215. print_conn_desc(&desc);
  216. MODLOG_DFLT(INFO, "\n");
  217. /* Remember peer. */
  218. rc = peer_add(event->connect.conn_handle);
  219. if (rc != 0) {
  220. MODLOG_DFLT(ERROR, "Failed to add peer; rc=%d\n", rc);
  221. return 0;
  222. }
  223. /* Perform service discovery. */
  224. rc = peer_disc_all(event->connect.conn_handle,
  225. ble_spp_client_on_disc_complete, NULL);
  226. if (rc != 0) {
  227. MODLOG_DFLT(ERROR, "Failed to discover services; rc=%d\n", rc);
  228. return 0;
  229. }
  230. } else {
  231. /* Connection attempt failed; resume scanning. */
  232. MODLOG_DFLT(ERROR, "Error: Connection failed; status=%d\n",
  233. event->connect.status);
  234. ble_spp_client_scan();
  235. }
  236. return 0;
  237. case BLE_GAP_EVENT_DISCONNECT:
  238. /* Connection terminated. */
  239. MODLOG_DFLT(INFO, "disconnect; reason=%d ", event->disconnect.reason);
  240. print_conn_desc(&event->disconnect.conn);
  241. MODLOG_DFLT(INFO, "\n");
  242. /* Forget about peer. */
  243. attribute_handle[event->disconnect.conn.conn_handle] = 0;
  244. peer_delete(event->disconnect.conn.conn_handle);
  245. /* Resume scanning. */
  246. ble_spp_client_scan();
  247. return 0;
  248. case BLE_GAP_EVENT_DISC_COMPLETE:
  249. MODLOG_DFLT(INFO, "discovery complete; reason=%d\n",
  250. event->disc_complete.reason);
  251. return 0;
  252. case BLE_GAP_EVENT_NOTIFY_RX:
  253. /* Peer sent us a notification or indication. */
  254. MODLOG_DFLT(INFO, "received %s; conn_handle=%d attr_handle=%d "
  255. "attr_len=%d\n",
  256. event->notify_rx.indication ?
  257. "indication" :
  258. "notification",
  259. event->notify_rx.conn_handle,
  260. event->notify_rx.attr_handle,
  261. OS_MBUF_PKTLEN(event->notify_rx.om));
  262. /* Attribute data is contained in event->notify_rx.om. Use
  263. * `os_mbuf_copydata` to copy the data received in notification mbuf */
  264. return 0;
  265. case BLE_GAP_EVENT_MTU:
  266. MODLOG_DFLT(INFO, "mtu update event; conn_handle=%d cid=%d mtu=%d\n",
  267. event->mtu.conn_handle,
  268. event->mtu.channel_id,
  269. event->mtu.value);
  270. return 0;
  271. default:
  272. return 0;
  273. }
  274. }
  275. static void
  276. ble_spp_client_on_reset(int reason)
  277. {
  278. MODLOG_DFLT(ERROR, "Resetting state; reason=%d\n", reason);
  279. }
  280. static void
  281. ble_spp_client_on_sync(void)
  282. {
  283. int rc;
  284. /* Make sure we have proper identity address set (public preferred) */
  285. rc = ble_hs_util_ensure_addr(0);
  286. assert(rc == 0);
  287. /* Begin scanning for a peripheral to connect to. */
  288. ble_spp_client_scan();
  289. }
  290. void ble_spp_client_host_task(void *param)
  291. {
  292. ESP_LOGI(tag, "BLE Host Task Started");
  293. /* This function will return only when nimble_port_stop() is executed */
  294. nimble_port_run();
  295. nimble_port_freertos_deinit();
  296. }
  297. void ble_client_uart_task(void *pvParameters)
  298. {
  299. ESP_LOGI(tag,"BLE client UART task started\n");
  300. int rc;
  301. int i;
  302. uart_event_t event;
  303. for (;;) {
  304. //Waiting for UART event.
  305. if (xQueueReceive(spp_common_uart_queue, (void * )&event, (TickType_t)portMAX_DELAY)) {
  306. switch (event.type) {
  307. //Event of UART receving data
  308. case UART_DATA:
  309. if (event.size) {
  310. /* Writing characteristics */
  311. uint8_t * temp = NULL;
  312. temp = (uint8_t *)malloc(sizeof(uint8_t)*event.size);
  313. if(temp == NULL){
  314. ESP_LOGE(tag, "malloc failed,%s L#%d\n", __func__, __LINE__);
  315. break;
  316. }
  317. memset(temp, 0x0, event.size);
  318. uart_read_bytes(UART_NUM_0,temp,event.size,portMAX_DELAY);
  319. for ( i = 0; i < CONFIG_BT_NIMBLE_MAX_CONNECTIONS; i++) {
  320. if (attribute_handle[i] != 0) {
  321. rc = ble_gattc_write_flat(i+1, attribute_handle[i],temp, event.size,NULL,NULL);
  322. if (rc == 0) {
  323. ESP_LOGI(tag,"Write in uart task success!");
  324. }
  325. else {
  326. ESP_LOGI(tag,"Error in writing characteristic rc=%d",rc);
  327. }
  328. vTaskDelay(10);
  329. }
  330. }
  331. free(temp);
  332. }
  333. break;
  334. default:
  335. break;
  336. }
  337. }
  338. }
  339. vTaskDelete(NULL);
  340. }
  341. static void ble_spp_uart_init(void)
  342. {
  343. uart_config_t uart_config = {
  344. .baud_rate = 115200,
  345. .data_bits = UART_DATA_8_BITS,
  346. .parity = UART_PARITY_DISABLE,
  347. .stop_bits = UART_STOP_BITS_1,
  348. .flow_ctrl = UART_HW_FLOWCTRL_RTS,
  349. .rx_flow_ctrl_thresh = 122,
  350. .source_clk = UART_SCLK_DEFAULT,
  351. };
  352. //Install UART driver, and get the queue.
  353. uart_driver_install(UART_NUM_0, 4096, 8192, 10, &spp_common_uart_queue, 0);
  354. //Set UART parameters
  355. uart_param_config(UART_NUM_0, &uart_config);
  356. //Set UART pins
  357. uart_set_pin(UART_NUM_0, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
  358. xTaskCreate(ble_client_uart_task, "uTask", 4096, (void*)UART_NUM_0, 8, NULL);
  359. }
  360. void
  361. app_main(void)
  362. {
  363. int rc;
  364. /* Initialize NVS — it is used to store PHY calibration data */
  365. esp_err_t ret = nvs_flash_init();
  366. if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
  367. ESP_ERROR_CHECK(nvs_flash_erase());
  368. ret = nvs_flash_init();
  369. }
  370. ESP_ERROR_CHECK(ret);
  371. nimble_port_init();
  372. /* Initialize UART driver and start uart task */
  373. ble_spp_uart_init();
  374. /* Configure the host. */
  375. ble_hs_cfg.reset_cb = ble_spp_client_on_reset;
  376. ble_hs_cfg.sync_cb = ble_spp_client_on_sync;
  377. ble_hs_cfg.store_status_cb = ble_store_util_status_rr;
  378. /* Initialize data structures to track connected peers. */
  379. rc = peer_init(MYNEWT_VAL(BLE_MAX_CONNECTIONS), 64, 64, 64);
  380. assert(rc == 0);
  381. /* Set the default device name. */
  382. rc = ble_svc_gap_device_name_set("nimble-ble-spp-client");
  383. assert(rc == 0);
  384. /* XXX Need to have template for store */
  385. ble_store_config_init();
  386. nimble_port_freertos_init(ble_spp_client_host_task);
  387. }