main.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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_server.h"
  16. #include "driver/uart.h"
  17. static const char *tag = "NimBLE_SPP_BLE_PRPH";
  18. static int ble_spp_server_gap_event(struct ble_gap_event *event, void *arg);
  19. static uint8_t own_addr_type;
  20. int gatt_svr_register(void);
  21. QueueHandle_t spp_common_uart_queue = NULL;
  22. uint16_t connection_handle[CONFIG_BT_NIMBLE_MAX_CONNECTIONS];
  23. static uint16_t ble_svc_gatt_read_val_handle,ble_spp_svc_gatt_read_val_handle;
  24. /* 16 Bit Alert Notification Service UUID */
  25. #define BLE_SVC_ANS_UUID16 0x1811
  26. /* 16 Bit Alert Notification Service Characteristic UUIDs */
  27. #define BLE_SVC_ANS_CHR_UUID16_SUP_NEW_ALERT_CAT 0x2a47
  28. /* 16 Bit SPP Service UUID */
  29. #define BLE_SVC_SPP_UUID16 0xABF0
  30. /* 16 Bit SPP Service Characteristic UUID */
  31. #define BLE_SVC_SPP_CHR_UUID16 0xABF1
  32. void ble_store_config_init(void);
  33. /**
  34. * Logs information about a connection to the console.
  35. */
  36. static void
  37. ble_spp_server_print_conn_desc(struct ble_gap_conn_desc *desc)
  38. {
  39. MODLOG_DFLT(INFO, "handle=%d our_ota_addr_type=%d our_ota_addr=",
  40. desc->conn_handle, desc->our_ota_addr.type);
  41. print_addr(desc->our_ota_addr.val);
  42. MODLOG_DFLT(INFO, " our_id_addr_type=%d our_id_addr=",
  43. desc->our_id_addr.type);
  44. print_addr(desc->our_id_addr.val);
  45. MODLOG_DFLT(INFO, " peer_ota_addr_type=%d peer_ota_addr=",
  46. desc->peer_ota_addr.type);
  47. print_addr(desc->peer_ota_addr.val);
  48. MODLOG_DFLT(INFO, " peer_id_addr_type=%d peer_id_addr=",
  49. desc->peer_id_addr.type);
  50. print_addr(desc->peer_id_addr.val);
  51. MODLOG_DFLT(INFO, " conn_itvl=%d conn_latency=%d supervision_timeout=%d "
  52. "encrypted=%d authenticated=%d bonded=%d\n",
  53. desc->conn_itvl, desc->conn_latency,
  54. desc->supervision_timeout,
  55. desc->sec_state.encrypted,
  56. desc->sec_state.authenticated,
  57. desc->sec_state.bonded);
  58. }
  59. /**
  60. * Enables advertising with the following parameters:
  61. * o General discoverable mode.
  62. * o Undirected connectable mode.
  63. */
  64. static void
  65. ble_spp_server_advertise(void)
  66. {
  67. struct ble_gap_adv_params adv_params;
  68. struct ble_hs_adv_fields fields;
  69. const char *name;
  70. int rc;
  71. /**
  72. * Set the advertisement data included in our advertisements:
  73. * o Flags (indicates advertisement type and other general info).
  74. * o Advertising tx power.
  75. * o Device name.
  76. * o 16-bit service UUIDs (alert notifications).
  77. */
  78. memset(&fields, 0, sizeof fields);
  79. /* Advertise two flags:
  80. * o Discoverability in forthcoming advertisement (general)
  81. * o BLE-only (BR/EDR unsupported).
  82. */
  83. fields.flags = BLE_HS_ADV_F_DISC_GEN |
  84. BLE_HS_ADV_F_BREDR_UNSUP;
  85. /* Indicate that the TX power level field should be included; have the
  86. * stack fill this value automatically. This is done by assigning the
  87. * special value BLE_HS_ADV_TX_PWR_LVL_AUTO.
  88. */
  89. fields.tx_pwr_lvl_is_present = 1;
  90. fields.tx_pwr_lvl = BLE_HS_ADV_TX_PWR_LVL_AUTO;
  91. name = ble_svc_gap_device_name();
  92. fields.name = (uint8_t *)name;
  93. fields.name_len = strlen(name);
  94. fields.name_is_complete = 1;
  95. fields.uuids16 = (ble_uuid16_t[]) {
  96. BLE_UUID16_INIT(GATT_SVR_SVC_ALERT_UUID)
  97. };
  98. fields.num_uuids16 = 1;
  99. fields.uuids16_is_complete = 1;
  100. rc = ble_gap_adv_set_fields(&fields);
  101. if (rc != 0) {
  102. MODLOG_DFLT(ERROR, "error setting advertisement data; rc=%d\n", rc);
  103. return;
  104. }
  105. /* Begin advertising. */
  106. memset(&adv_params, 0, sizeof adv_params);
  107. adv_params.conn_mode = BLE_GAP_CONN_MODE_UND;
  108. adv_params.disc_mode = BLE_GAP_DISC_MODE_GEN;
  109. rc = ble_gap_adv_start(own_addr_type, NULL, BLE_HS_FOREVER,
  110. &adv_params, ble_spp_server_gap_event, NULL);
  111. if (rc != 0) {
  112. MODLOG_DFLT(ERROR, "error enabling advertisement; rc=%d\n", rc);
  113. return;
  114. }
  115. }
  116. /**
  117. * The nimble host executes this callback when a GAP event occurs. The
  118. * application associates a GAP event callback with each connection that forms.
  119. * ble_spp_server uses the same callback for all connections.
  120. *
  121. * @param event The type of event being signalled.
  122. * @param ctxt Various information pertaining to the event.
  123. * @param arg Application-specified argument; unused by
  124. * ble_spp_server.
  125. *
  126. * @return 0 if the application successfully handled the
  127. * event; nonzero on failure. The semantics
  128. * of the return code is specific to the
  129. * particular GAP event being signalled.
  130. */
  131. static int
  132. ble_spp_server_gap_event(struct ble_gap_event *event, void *arg)
  133. {
  134. struct ble_gap_conn_desc desc;
  135. int rc;
  136. switch (event->type) {
  137. case BLE_GAP_EVENT_CONNECT:
  138. /* A new connection was established or a connection attempt failed. */
  139. MODLOG_DFLT(INFO, "connection %s; status=%d ",
  140. event->connect.status == 0 ? "established" : "failed",
  141. event->connect.status);
  142. if (event->connect.status == 0) {
  143. rc = ble_gap_conn_find(event->connect.conn_handle, &desc);
  144. assert(rc == 0);
  145. ble_spp_server_print_conn_desc(&desc);
  146. connection_handle[event->connect.conn_handle - 1] = event->connect.conn_handle;
  147. }
  148. MODLOG_DFLT(INFO, "\n");
  149. if (event->connect.status != 0 || CONFIG_BT_NIMBLE_MAX_CONNECTIONS > 1) {
  150. /* Connection failed or if multiple connection allowed; resume advertising. */
  151. ble_spp_server_advertise();
  152. }
  153. return 0;
  154. case BLE_GAP_EVENT_DISCONNECT:
  155. MODLOG_DFLT(INFO, "disconnect; reason=%d ", event->disconnect.reason);
  156. ble_spp_server_print_conn_desc(&event->disconnect.conn);
  157. MODLOG_DFLT(INFO, "\n");
  158. /* Connection terminated; resume advertising. */
  159. ble_spp_server_advertise();
  160. return 0;
  161. case BLE_GAP_EVENT_CONN_UPDATE:
  162. /* The central has updated the connection parameters. */
  163. MODLOG_DFLT(INFO, "connection updated; status=%d ",
  164. event->conn_update.status);
  165. rc = ble_gap_conn_find(event->conn_update.conn_handle, &desc);
  166. assert(rc == 0);
  167. ble_spp_server_print_conn_desc(&desc);
  168. MODLOG_DFLT(INFO, "\n");
  169. return 0;
  170. case BLE_GAP_EVENT_ADV_COMPLETE:
  171. MODLOG_DFLT(INFO, "advertise complete; reason=%d",
  172. event->adv_complete.reason);
  173. ble_spp_server_advertise();
  174. return 0;
  175. case BLE_GAP_EVENT_MTU:
  176. MODLOG_DFLT(INFO, "mtu update event; conn_handle=%d cid=%d mtu=%d\n",
  177. event->mtu.conn_handle,
  178. event->mtu.channel_id,
  179. event->mtu.value);
  180. return 0;
  181. default:
  182. return 0;
  183. }
  184. }
  185. static void
  186. ble_spp_server_on_reset(int reason)
  187. {
  188. MODLOG_DFLT(ERROR, "Resetting state; reason=%d\n", reason);
  189. }
  190. static void
  191. ble_spp_server_on_sync(void)
  192. {
  193. int rc;
  194. rc = ble_hs_util_ensure_addr(0);
  195. assert(rc == 0);
  196. /* Figure out address to use while advertising (no privacy for now) */
  197. rc = ble_hs_id_infer_auto(0, &own_addr_type);
  198. if (rc != 0) {
  199. MODLOG_DFLT(ERROR, "error determining address type; rc=%d\n", rc);
  200. return;
  201. }
  202. /* Printing ADDR */
  203. uint8_t addr_val[6] = {0};
  204. rc = ble_hs_id_copy_addr(own_addr_type, addr_val, NULL);
  205. MODLOG_DFLT(INFO, "Device Address: ");
  206. print_addr(addr_val);
  207. MODLOG_DFLT(INFO, "\n");
  208. /* Begin advertising. */
  209. ble_spp_server_advertise();
  210. }
  211. void ble_spp_server_host_task(void *param)
  212. {
  213. ESP_LOGI(tag, "BLE Host Task Started");
  214. /* This function will return only when nimble_port_stop() is executed */
  215. nimble_port_run();
  216. nimble_port_freertos_deinit();
  217. }
  218. /* Callback function for custom service */
  219. static int ble_svc_gatt_handler(uint16_t conn_handle, uint16_t attr_handle,struct ble_gatt_access_ctxt *ctxt, void *arg)
  220. {
  221. switch(ctxt->op){
  222. case BLE_GATT_ACCESS_OP_READ_CHR:
  223. ESP_LOGI(tag, "Callback for read");
  224. break;
  225. case BLE_GATT_ACCESS_OP_WRITE_CHR:
  226. ESP_LOGI(tag,"Data received in write event,conn_handle = %x,attr_handle = %x",conn_handle,attr_handle);
  227. break;
  228. default:
  229. ESP_LOGI(tag, "\nDefault Callback");
  230. break;
  231. }
  232. return 0;
  233. }
  234. /* Define new custom service */
  235. static const struct ble_gatt_svc_def new_ble_svc_gatt_defs[] = {
  236. {
  237. /*** Service: GATT */
  238. .type = BLE_GATT_SVC_TYPE_PRIMARY,
  239. .uuid = BLE_UUID16_DECLARE(BLE_SVC_ANS_UUID16),
  240. .characteristics = (struct ble_gatt_chr_def[]) { {
  241. /* Support new alert category */
  242. .uuid = BLE_UUID16_DECLARE(BLE_SVC_ANS_CHR_UUID16_SUP_NEW_ALERT_CAT),
  243. .access_cb = ble_svc_gatt_handler,
  244. .val_handle = &ble_svc_gatt_read_val_handle,
  245. .flags = BLE_GATT_CHR_F_READ | BLE_GATT_CHR_F_WRITE | BLE_GATT_CHR_F_NOTIFY | BLE_GATT_CHR_F_INDICATE,
  246. },
  247. {
  248. 0, /* No more characteristics */
  249. }
  250. },
  251. },
  252. {
  253. /*** Service: SPP */
  254. .type = BLE_GATT_SVC_TYPE_PRIMARY,
  255. .uuid = BLE_UUID16_DECLARE(BLE_SVC_SPP_UUID16),
  256. .characteristics = (struct ble_gatt_chr_def[]) { {
  257. /* Support SPP service */
  258. .uuid = BLE_UUID16_DECLARE(BLE_SVC_SPP_CHR_UUID16),
  259. .access_cb = ble_svc_gatt_handler,
  260. .val_handle = &ble_spp_svc_gatt_read_val_handle,
  261. .flags = BLE_GATT_CHR_F_READ | BLE_GATT_CHR_F_WRITE | BLE_GATT_CHR_F_NOTIFY | BLE_GATT_CHR_F_INDICATE,
  262. },
  263. {
  264. 0, /* No more characteristics */
  265. }
  266. },
  267. },
  268. {
  269. 0, /* No more services. */
  270. },
  271. };
  272. int gatt_svr_register(void)
  273. {
  274. int rc=0;
  275. rc = ble_gatts_count_cfg(new_ble_svc_gatt_defs);
  276. if (rc != 0) {
  277. return rc;
  278. }
  279. rc = ble_gatts_add_svcs(new_ble_svc_gatt_defs);
  280. if (rc != 0) {
  281. return rc;
  282. }
  283. return 0;
  284. }
  285. void ble_server_uart_task(void *pvParameters){
  286. ESP_LOGI(tag,"BLE server UART_task started\n");
  287. uart_event_t event;
  288. int rc=0;
  289. for (;;) {
  290. //Waiting for UART event.
  291. if (xQueueReceive(spp_common_uart_queue, (void * )&event, (TickType_t)portMAX_DELAY)) {
  292. switch (event.type) {
  293. //Event of UART receving data
  294. case UART_DATA:
  295. if (event.size) {
  296. static uint8_t ntf[1];
  297. ntf[0] = 90;
  298. for ( int i = 0; i < CONFIG_BT_NIMBLE_MAX_CONNECTIONS; i++) {
  299. if (connection_handle[i] != 0) {
  300. struct os_mbuf *txom;
  301. txom = ble_hs_mbuf_from_flat(ntf, sizeof(ntf));
  302. rc = ble_gattc_notify_custom(connection_handle[i],
  303. ble_spp_svc_gatt_read_val_handle,
  304. txom);
  305. if ( rc == 0 ) {
  306. ESP_LOGI(tag,"Notification sent successfully");
  307. }
  308. else {
  309. ESP_LOGI(tag,"Error in sending notification rc = %d", rc);
  310. }
  311. }
  312. }
  313. }
  314. break;
  315. default:
  316. break;
  317. }
  318. }
  319. }
  320. vTaskDelete(NULL);
  321. }
  322. static void ble_spp_uart_init(void)
  323. {
  324. uart_config_t uart_config = {
  325. .baud_rate = 115200,
  326. .data_bits = UART_DATA_8_BITS,
  327. .parity = UART_PARITY_DISABLE,
  328. .stop_bits = UART_STOP_BITS_1,
  329. .flow_ctrl = UART_HW_FLOWCTRL_RTS,
  330. .rx_flow_ctrl_thresh = 122,
  331. .source_clk = UART_SCLK_DEFAULT,
  332. };
  333. //Install UART driver, and get the queue.
  334. uart_driver_install(UART_NUM_0, 4096, 8192, 10,&spp_common_uart_queue,0);
  335. //Set UART parameters
  336. uart_param_config(UART_NUM_0, &uart_config);
  337. //Set UART pins
  338. uart_set_pin(UART_NUM_0, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
  339. xTaskCreate(ble_server_uart_task, "uTask", 4096, (void*)UART_NUM_0, 8, NULL);
  340. }
  341. void
  342. app_main(void)
  343. {
  344. int rc;
  345. /* Initialize NVS — it is used to store PHY calibration data */
  346. esp_err_t ret = nvs_flash_init();
  347. if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
  348. ESP_ERROR_CHECK(nvs_flash_erase());
  349. ret = nvs_flash_init();
  350. }
  351. ESP_ERROR_CHECK(ret);
  352. nimble_port_init();
  353. /* Initialize uart driver and start uart task */
  354. ble_spp_uart_init();
  355. /* Initialize the NimBLE host configuration. */
  356. ble_hs_cfg.reset_cb = ble_spp_server_on_reset;
  357. ble_hs_cfg.sync_cb = ble_spp_server_on_sync;
  358. ble_hs_cfg.gatts_register_cb = gatt_svr_register_cb;
  359. ble_hs_cfg.store_status_cb = ble_store_util_status_rr;
  360. ble_hs_cfg.sm_io_cap = CONFIG_EXAMPLE_IO_TYPE;
  361. #ifdef CONFIG_EXAMPLE_BONDING
  362. ble_hs_cfg.sm_bonding = 1;
  363. #endif
  364. #ifdef CONFIG_EXAMPLE_MITM
  365. ble_hs_cfg.sm_mitm = 1;
  366. #endif
  367. #ifdef CONFIG_EXAMPLE_USE_SC
  368. ble_hs_cfg.sm_sc = 1;
  369. #else
  370. ble_hs_cfg.sm_sc = 0;
  371. #endif
  372. #ifdef CONFIG_EXAMPLE_BONDING
  373. ble_hs_cfg.sm_our_key_dist = 1;
  374. ble_hs_cfg.sm_their_key_dist = 1;
  375. #endif
  376. rc = new_gatt_svr_init();
  377. assert(rc == 0);
  378. /* Register custom service */
  379. rc = gatt_svr_register();
  380. assert(rc == 0);
  381. /* Set the default device name. */
  382. rc = ble_svc_gap_device_name_set("nimble-ble-spp-svr");
  383. assert(rc == 0);
  384. /* XXX Need to have template for store */
  385. ble_store_config_init();
  386. nimble_port_freertos_init(ble_spp_server_host_task);
  387. }