bt_app_source.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <ctype.h>
  4. #include <stdlib.h>
  5. #include "esp_log.h"
  6. #include "esp_bt.h"
  7. #include "esp_bt_device.h"
  8. #include "esp_bt_main.h"
  9. #include "esp_gap_bt_api.h"
  10. #include "esp_a2dp_api.h"
  11. #include "esp_console.h"
  12. #include "esp_pthread.h"
  13. #include "esp_system.h"
  14. #include "esp_wifi.h"
  15. #include "freertos/timers.h"
  16. #include "argtable3/argtable3.h"
  17. #include "config.h"
  18. #include "bt_app_core.h"
  19. #include "trace.h"
  20. static const char * TAG = "platform";
  21. extern int32_t output_bt_data(uint8_t *data, int32_t len);
  22. extern void output_bt_tick(void);
  23. extern char* output_state_str(void);
  24. extern bool output_stopped(void);
  25. int64_t connecting_timeout = 0;
  26. static const char * art_a2dp_connected[]={"\n",
  27. " ___ _____ _____ _____ _ _ _ ",
  28. " /\\ |__ \\| __ \\| __ \\ / ____| | | | | |",
  29. " / \\ ) | | | | |__) | | | ___ _ __ _ __ ___ ___| |_ ___ __| | |",
  30. " / /\\ \\ / /| | | | ___/ | | / _ \\| '_ \\| '_ \\ / _ \\/ __| __/ _ \\/ _` | |",
  31. " / ____ \\ / /_| |__| | | | |___| (_) | | | | | | | __/ (__| || __/ (_| |_|",
  32. " /_/ \\_\\____|_____/|_| \\_____\\___/|_| |_|_| |_|\\___|\\___|\\__\\___|\\__,_(_)\n",
  33. "\0"};
  34. static const char * art_a2dp_connecting[]= {"\n",
  35. " ___ _____ _____ _____ _ _ ",
  36. " /\\ |__ \\| __ \\| __ \\ / ____| | | (_) ",
  37. " / \\ ) | | | | |__) | | | ___ _ __ _ __ ___ ___| |_ _ _ __ __ _ ",
  38. " / /\\ \\ / /| | | | ___/ | | / _ \\| '_ \\| '_ \\ / _ \\/ __| __| | '_ \\ / _` | ",
  39. " / ____ \\ / /_| |__| | | | |___| (_) | | | | | | | __/ (__| |_| | | | | (_| |_ _ _ ",
  40. " /_/ \\_\\____|_____/|_| \\_____\\___/|_| |_|_| |_|\\___|\\___|\\__|_|_| |_|\\__, (_|_|_)",
  41. " __/ | ",
  42. " |___/ \n",
  43. "\0"};
  44. static void bt_app_av_state_connecting(uint16_t event, void *param);
  45. #define A2DP_TIMER_INIT connecting_timeout = esp_timer_get_time() +(CONFIG_A2DP_CONNECT_TIMEOUT_MS * 1000)
  46. #define IS_A2DP_TIMER_OVER esp_timer_get_time() >= connecting_timeout
  47. static void filter_inquiry_scan_result(esp_bt_gap_cb_param_t *param);
  48. /* event for handler "bt_av_hdl_stack_up */
  49. enum {
  50. BT_APP_EVT_STACK_UP = 0,
  51. };
  52. /* A2DP global state */
  53. enum {
  54. APP_AV_STATE_IDLE,
  55. APP_AV_STATE_DISCOVERING,
  56. APP_AV_STATE_DISCOVERED,
  57. APP_AV_STATE_UNCONNECTED,
  58. APP_AV_STATE_CONNECTING,
  59. APP_AV_STATE_CONNECTED,
  60. APP_AV_STATE_DISCONNECTING,
  61. };
  62. char * APP_AV_STATE_DESC[] = {
  63. "APP_AV_STATE_IDLE",
  64. "APP_AV_STATE_DISCOVERING",
  65. "APP_AV_STATE_DISCOVERED",
  66. "APP_AV_STATE_UNCONNECTED",
  67. "APP_AV_STATE_CONNECTING",
  68. "APP_AV_STATE_CONNECTED",
  69. "APP_AV_STATE_DISCONNECTING"
  70. };
  71. /* sub states of APP_AV_STATE_CONNECTED */
  72. enum {
  73. APP_AV_MEDIA_STATE_IDLE,
  74. APP_AV_MEDIA_STATE_STARTING,
  75. // APP_AV_MEDIA_STATE_BUFFERING,
  76. APP_AV_MEDIA_STATE_STARTED,
  77. APP_AV_MEDIA_STATE_STOPPING,
  78. APP_AV_MEDIA_STATE_WAIT_DISCONNECT
  79. };
  80. #define BT_APP_HEART_BEAT_EVT (0xff00)
  81. /// handler for bluetooth stack enabled events
  82. static void bt_av_hdl_stack_evt(uint16_t event, void *p_param);
  83. /// callback function for A2DP source
  84. static void bt_app_a2d_cb(esp_a2d_cb_event_t event, esp_a2d_cb_param_t *param);
  85. /// callback function for A2DP source audio data stream
  86. static void a2d_app_heart_beat(void *arg);
  87. /// A2DP application state machine
  88. static void bt_app_av_sm_hdlr(uint16_t event, void *param);
  89. /* A2DP application state machine handler for each state */
  90. static void bt_app_av_state_unconnected(uint16_t event, void *param);
  91. static void bt_app_av_state_connecting(uint16_t event, void *param);
  92. static void bt_app_av_state_connected(uint16_t event, void *param);
  93. static void bt_app_av_state_disconnecting(uint16_t event, void *param);
  94. static esp_bd_addr_t s_peer_bda = {0};
  95. static uint8_t s_peer_bdname[ESP_BT_GAP_MAX_BDNAME_LEN + 1];
  96. static int s_a2d_state = APP_AV_STATE_IDLE;
  97. static int s_media_state = APP_AV_MEDIA_STATE_IDLE;
  98. static uint32_t s_pkt_cnt = 0;
  99. static TimerHandle_t s_tmr;
  100. static struct {
  101. int control_delay;
  102. int connect_timeout_delay;
  103. char * sink_name;
  104. } squeezelite_conf;
  105. void hal_bluetooth_init(const char * options)
  106. {
  107. struct {
  108. struct arg_str *sink_name;
  109. struct arg_int *control_delay;
  110. struct arg_int *connect_timeout_delay;
  111. struct arg_end *end;
  112. } squeezelite_args;
  113. ESP_LOGD(TAG,"Initializing Bluetooth HAL");
  114. squeezelite_args.sink_name = arg_str1("n", "name", "<sink name>", "the name of the bluetooth to connect to");
  115. squeezelite_args.control_delay = arg_int0("d", "delay", "<control delay>", "the delay between each pass at the A2DP control loop");
  116. squeezelite_args.connect_timeout_delay = arg_int0("t","timeout", "<timeout>", "the timeout duration for connecting to the A2DP sink");
  117. squeezelite_args.end = arg_end(2);
  118. ESP_LOGD(TAG,"Copying parameters");
  119. char * opts = strdup(options);
  120. char **argv = malloc(sizeof(char**)*15);
  121. size_t argv_size=15;
  122. // change parms so ' appear as " for parsing the options
  123. for (char* p = opts; (p = strchr(p, '\'')); ++p) *p = '"';
  124. ESP_LOGD(TAG,"Splitting arg line: %s", opts);
  125. argv_size = esp_console_split_argv(opts, argv, argv_size);
  126. ESP_LOGD(TAG,"Parsing parameters");
  127. int nerrors = arg_parse(argv_size , argv, (void **) &squeezelite_args);
  128. if (nerrors != 0) {
  129. ESP_LOGD(TAG,"Parsing Errors");
  130. arg_print_errors(stdout, squeezelite_args.end, "BT");
  131. arg_print_glossary_gnu(stdout, (void **) &squeezelite_args);
  132. free(opts);
  133. free(argv);
  134. return;
  135. }
  136. if(squeezelite_args.sink_name->count == 0)
  137. {
  138. squeezelite_conf.sink_name = config_alloc_get_default(NVS_TYPE_STR, "a2dp_sink_name", CONFIG_A2DP_SINK_NAME, 0);
  139. if(squeezelite_conf.sink_name == NULL){
  140. ESP_LOGW(TAG,"Unable to retrieve the a2dp sink name from nvs");
  141. squeezelite_conf.sink_name = strdup(CONFIG_A2DP_SINK_NAME);
  142. }
  143. } else {
  144. squeezelite_conf.sink_name=strdup(squeezelite_args.sink_name->sval[0]);
  145. }
  146. if(squeezelite_args.connect_timeout_delay->count == 0)
  147. {
  148. ESP_LOGD(TAG,"Using default connect timeout");
  149. squeezelite_conf.connect_timeout_delay=CONFIG_A2DP_CONNECT_TIMEOUT_MS;
  150. } else {
  151. squeezelite_conf.connect_timeout_delay=squeezelite_args.connect_timeout_delay->ival[0];
  152. }
  153. if(squeezelite_args.control_delay->count == 0)
  154. {
  155. ESP_LOGD(TAG,"Using default control delay");
  156. squeezelite_conf.control_delay=CONFIG_A2DP_CONTROL_DELAY_MS;
  157. } else {
  158. squeezelite_conf.control_delay=squeezelite_args.control_delay->ival[0];
  159. }
  160. ESP_LOGD(TAG,"Freeing options");
  161. free(argv);
  162. free(opts);
  163. /*
  164. * Bluetooth audio source init Start
  165. */
  166. //running_test = false;
  167. ESP_ERROR_CHECK(esp_bt_controller_mem_release(ESP_BT_MODE_BLE));
  168. esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
  169. if (esp_bt_controller_init(&bt_cfg) != ESP_OK) {
  170. ESP_LOGE(TAG,"%s initialize controller failed\n", __func__);
  171. return;
  172. }
  173. if (esp_bt_controller_enable(ESP_BT_MODE_CLASSIC_BT) != ESP_OK) {
  174. ESP_LOGE(TAG,"%s enable controller failed\n", __func__);
  175. return;
  176. }
  177. if (esp_bluedroid_init() != ESP_OK) {
  178. ESP_LOGE(TAG,"%s initialize bluedroid failed\n", __func__);
  179. return;
  180. }
  181. if (esp_bluedroid_enable() != ESP_OK) {
  182. ESP_LOGE(TAG,"%s enable bluedroid failed\n", __func__);
  183. return;
  184. }
  185. /* create application task */
  186. bt_app_task_start_up();
  187. /* Bluetooth device name, connection mode and profile set up */
  188. bt_app_work_dispatch(bt_av_hdl_stack_evt, BT_APP_EVT_STACK_UP, NULL, 0, NULL);
  189. #if (CONFIG_BT_SSP_ENABLED == true)
  190. /* Set default parameters for Secure Simple Pairing */
  191. esp_bt_sp_param_t param_type = ESP_BT_SP_IOCAP_MODE;
  192. esp_bt_io_cap_t iocap = ESP_BT_IO_CAP_IO;
  193. esp_bt_gap_set_security_param(param_type, &iocap, sizeof(uint8_t));
  194. #endif
  195. /*
  196. * Set default parameters for Legacy Pairing
  197. * Use variable pin, input pin code when pairing
  198. */
  199. esp_bt_pin_type_t pin_type = ESP_BT_PIN_TYPE_VARIABLE;
  200. esp_bt_pin_code_t pin_code;
  201. esp_bt_gap_set_pin(pin_type, 0, pin_code);
  202. }
  203. void hal_bluetooth_stop(void) {
  204. /* this still does not work, can't figure out how to stop properly this BT stack */
  205. bt_app_task_shut_down();
  206. ESP_LOGI(TAG, "bt_app_task shutdown successfully");
  207. if (esp_bluedroid_disable() != ESP_OK) return;
  208. ESP_LOGI(TAG, "esp_bluedroid_disable called successfully");
  209. if (esp_bluedroid_deinit() != ESP_OK) return;
  210. ESP_LOGI(TAG, "esp_bluedroid_deinit called successfully");
  211. if (esp_bt_controller_disable() != ESP_OK) return;
  212. ESP_LOGI(TAG, "esp_bt_controller_disable called successfully");
  213. if (esp_bt_controller_deinit() != ESP_OK) return;
  214. ESP_LOGI(TAG, "bt stopped successfully");
  215. }
  216. static void bt_app_a2d_cb(esp_a2d_cb_event_t event, esp_a2d_cb_param_t *param)
  217. {
  218. bt_app_work_dispatch(bt_app_av_sm_hdlr, event, param, sizeof(esp_a2d_cb_param_t), NULL);
  219. }
  220. static void bt_app_gap_cb(esp_bt_gap_cb_event_t event, esp_bt_gap_cb_param_t *param)
  221. {
  222. switch (event) {
  223. case ESP_BT_GAP_DISC_RES_EVT: {
  224. filter_inquiry_scan_result(param);
  225. break;
  226. }
  227. case ESP_BT_GAP_DISC_STATE_CHANGED_EVT: {
  228. if (param->disc_st_chg.state == ESP_BT_GAP_DISCOVERY_STOPPED)
  229. {
  230. if (s_a2d_state == APP_AV_STATE_DISCOVERED)
  231. {
  232. ESP_LOGI(TAG,"Discovery completed. Ready to start connecting to %s. ",s_peer_bdname);
  233. s_a2d_state = APP_AV_STATE_UNCONNECTED;
  234. }
  235. else
  236. {
  237. // not discovered, continue to discover
  238. ESP_LOGI(TAG,"Device discovery failed, continue to discover...");
  239. esp_bt_gap_start_discovery(ESP_BT_INQ_MODE_GENERAL_INQUIRY, 10, 0);
  240. }
  241. }
  242. else if (param->disc_st_chg.state == ESP_BT_GAP_DISCOVERY_STARTED) {
  243. ESP_LOGI(TAG,"Discovery started.");
  244. }
  245. else
  246. {
  247. ESP_LOGD(TAG,"This shouldn't happen. Discovery has only 2 states (for now).");
  248. }
  249. break;
  250. }
  251. case ESP_BT_GAP_RMT_SRVCS_EVT:
  252. ESP_LOG_DEBUG_EVENT(TAG,QUOTE(ESP_BT_GAP_RMT_SRVCS_EVT));
  253. break;
  254. case ESP_BT_GAP_RMT_SRVC_REC_EVT:
  255. ESP_LOG_DEBUG_EVENT(TAG,QUOTE(ESP_BT_GAP_RMT_SRVC_REC_EVT));
  256. break;
  257. case ESP_BT_GAP_AUTH_CMPL_EVT: {
  258. if (param->auth_cmpl.stat == ESP_BT_STATUS_SUCCESS) {
  259. ESP_LOGI(TAG,"authentication success: %s", param->auth_cmpl.device_name);
  260. //esp_log_buffer_hex(param->auth_cmpl.bda, ESP_BD_ADDR_LEN);
  261. } else {
  262. ESP_LOGE(TAG,"authentication failed, status:%d", param->auth_cmpl.stat);
  263. }
  264. break;
  265. }
  266. case ESP_BT_GAP_PIN_REQ_EVT: {
  267. ESP_LOGI(TAG,"ESP_BT_GAP_PIN_REQ_EVT min_16_digit:%d", param->pin_req.min_16_digit);
  268. if (param->pin_req.min_16_digit) {
  269. ESP_LOGI(TAG,"Input pin code: 0000 0000 0000 0000");
  270. esp_bt_pin_code_t pin_code = {0};
  271. esp_bt_gap_pin_reply(param->pin_req.bda, true, 16, pin_code);
  272. } else {
  273. ESP_LOGI(TAG,"Input pin code: 1234");
  274. esp_bt_pin_code_t pin_code;
  275. pin_code[0] = '1';
  276. pin_code[1] = '2';
  277. pin_code[2] = '3';
  278. pin_code[3] = '4';
  279. esp_bt_gap_pin_reply(param->pin_req.bda, true, 4, pin_code);
  280. }
  281. break;
  282. }
  283. #if (CONFIG_BT_SSP_ENABLED == true)
  284. case ESP_BT_GAP_CFM_REQ_EVT:
  285. ESP_LOGI(TAG,"ESP_BT_GAP_CFM_REQ_EVT Please compare the numeric value: %d", param->cfm_req.num_val);
  286. esp_bt_gap_ssp_confirm_reply(param->cfm_req.bda, true);
  287. break;
  288. case ESP_BT_GAP_KEY_NOTIF_EVT:
  289. ESP_LOGI(TAG,"ESP_BT_GAP_KEY_NOTIF_EVT passkey:%d", param->key_notif.passkey);
  290. break;
  291. ESP_LOGI(TAG,"ESP_BT_GAP_KEY_REQ_EVT Please enter passkey!");
  292. break;
  293. #endif
  294. default: {
  295. ESP_LOGI(TAG,"event: %d", event);
  296. break;
  297. }
  298. }
  299. return;
  300. }
  301. static void a2d_app_heart_beat(void *arg)
  302. {
  303. bt_app_work_dispatch(bt_app_av_sm_hdlr, BT_APP_HEART_BEAT_EVT, NULL, 0, NULL);
  304. }
  305. static void bt_app_av_sm_hdlr(uint16_t event, void *param)
  306. {
  307. switch (s_a2d_state) {
  308. case APP_AV_STATE_DISCOVERING:
  309. ESP_LOGV(TAG,"state %s, evt 0x%x, output state: %s", APP_AV_STATE_DESC[s_a2d_state], event, output_state_str());
  310. break;
  311. case APP_AV_STATE_DISCOVERED:
  312. ESP_LOGV(TAG,"state %s, evt 0x%x, output state: %s", APP_AV_STATE_DESC[s_a2d_state], event, output_state_str());
  313. break;
  314. case APP_AV_STATE_UNCONNECTED:
  315. bt_app_av_state_unconnected(event, param);
  316. break;
  317. case APP_AV_STATE_CONNECTING:
  318. bt_app_av_state_connecting(event, param);
  319. break;
  320. case APP_AV_STATE_CONNECTED:
  321. bt_app_av_state_connected(event, param);
  322. break;
  323. case APP_AV_STATE_DISCONNECTING:
  324. bt_app_av_state_disconnecting(event, param);
  325. break;
  326. default:
  327. ESP_LOGE(TAG,"%s invalid state %d", __func__, s_a2d_state);
  328. break;
  329. }
  330. }
  331. static char *bda2str(esp_bd_addr_t bda, char *str, size_t size)
  332. {
  333. if (bda == NULL || str == NULL || size < 18) {
  334. return NULL;
  335. }
  336. uint8_t *p = bda;
  337. sprintf(str, "%02x:%02x:%02x:%02x:%02x:%02x",
  338. p[0], p[1], p[2], p[3], p[4], p[5]);
  339. return str;
  340. }
  341. static bool get_name_from_eir(uint8_t *eir, uint8_t *bdname, uint8_t *bdname_len)
  342. {
  343. uint8_t *rmt_bdname = NULL;
  344. uint8_t rmt_bdname_len = 0;
  345. if (!eir) {
  346. return false;
  347. }
  348. rmt_bdname = esp_bt_gap_resolve_eir_data(eir, ESP_BT_EIR_TYPE_CMPL_LOCAL_NAME, &rmt_bdname_len);
  349. if (!rmt_bdname) {
  350. rmt_bdname = esp_bt_gap_resolve_eir_data(eir, ESP_BT_EIR_TYPE_SHORT_LOCAL_NAME, &rmt_bdname_len);
  351. }
  352. if (rmt_bdname) {
  353. if (rmt_bdname_len > ESP_BT_GAP_MAX_BDNAME_LEN) {
  354. rmt_bdname_len = ESP_BT_GAP_MAX_BDNAME_LEN;
  355. }
  356. if (bdname) {
  357. memcpy(bdname, rmt_bdname, rmt_bdname_len);
  358. bdname[rmt_bdname_len] = '\0';
  359. }
  360. if (bdname_len) {
  361. *bdname_len = rmt_bdname_len;
  362. }
  363. return true;
  364. }
  365. return false;
  366. }
  367. static void filter_inquiry_scan_result(esp_bt_gap_cb_param_t *param)
  368. {
  369. char bda_str[18];
  370. uint32_t cod = 0;
  371. int32_t rssi = -129; /* invalid value */
  372. uint8_t *eir = NULL;
  373. uint8_t nameLen = 0;
  374. esp_bt_gap_dev_prop_t *p;
  375. if(s_a2d_state != APP_AV_STATE_DISCOVERING)
  376. {
  377. // Ignore messages that might have been queued already
  378. // when we've discovered the target device.
  379. return;
  380. }
  381. memset(s_peer_bdname, 0x00,sizeof(s_peer_bdname));
  382. ESP_LOGI(TAG,"\n=======================\nScanned device: %s", bda2str(param->disc_res.bda, bda_str, 18));
  383. for (int i = 0; i < param->disc_res.num_prop; i++) {
  384. p = param->disc_res.prop + i;
  385. switch (p->type) {
  386. case ESP_BT_GAP_DEV_PROP_COD:
  387. cod = *(uint32_t *)(p->val);
  388. ESP_LOGI(TAG,"-- Class of Device: 0x%x", cod);
  389. break;
  390. case ESP_BT_GAP_DEV_PROP_RSSI:
  391. rssi = *(int8_t *)(p->val);
  392. ESP_LOGI(TAG,"-- RSSI: %d", rssi);
  393. break;
  394. case ESP_BT_GAP_DEV_PROP_EIR:
  395. eir = (uint8_t *)(p->val);
  396. ESP_LOGI(TAG,"-- EIR: %u", *eir);
  397. break;
  398. case ESP_BT_GAP_DEV_PROP_BDNAME:
  399. nameLen = (p->len > ESP_BT_GAP_MAX_BDNAME_LEN) ? ESP_BT_GAP_MAX_BDNAME_LEN : (uint8_t)p->len;
  400. memcpy(s_peer_bdname, (uint8_t *)(p->val), nameLen);
  401. s_peer_bdname[nameLen] = '\0';
  402. ESP_LOGI(TAG,"-- Name: %s", s_peer_bdname);
  403. break;
  404. default:
  405. break;
  406. }
  407. }
  408. if (!esp_bt_gap_is_valid_cod(cod)){
  409. /* search for device with MAJOR service class as "rendering" in COD */
  410. ESP_LOGI(TAG,"--Invalid class of device. Skipping.\n");
  411. return;
  412. }
  413. else if (!(esp_bt_gap_get_cod_srvc(cod) & ESP_BT_COD_SRVC_RENDERING))
  414. {
  415. ESP_LOGI(TAG,"--Not a rendering device. Skipping.\n");
  416. return;
  417. }
  418. /* search for device named "ESP_SPEAKER" in its extended inqury response */
  419. if (eir) {
  420. ESP_LOGI(TAG,"--Getting details from eir.\n");
  421. get_name_from_eir(eir, s_peer_bdname, NULL);
  422. ESP_LOGI(TAG,"--Device name is %s\n",s_peer_bdname);
  423. }
  424. if (strcmp((char *)s_peer_bdname, squeezelite_conf.sink_name) == 0) {
  425. ESP_LOGI(TAG,"Found a target device! address %s, name %s", bda_str, s_peer_bdname);
  426. ESP_LOGI(TAG,"=======================\n");
  427. if(esp_bt_gap_cancel_discovery()!=ESP_ERR_INVALID_STATE)
  428. {
  429. ESP_LOGI(TAG,"Cancel device discovery ...");
  430. memcpy(s_peer_bda, param->disc_res.bda, ESP_BD_ADDR_LEN);
  431. s_a2d_state = APP_AV_STATE_DISCOVERED;
  432. }
  433. else
  434. {
  435. ESP_LOGE(TAG,"Cancel device discovery failed...");
  436. }
  437. }
  438. else
  439. {
  440. ESP_LOGI(TAG,"Not the device we are looking for (%s). Continuing scan", squeezelite_conf.sink_name);
  441. }
  442. }
  443. static void bt_av_hdl_stack_evt(uint16_t event, void *p_param)
  444. {
  445. switch (event) {
  446. case BT_APP_EVT_STACK_UP: {
  447. ESP_LOGI(TAG,"BT Stack going up.");
  448. /* set up device name */
  449. char * a2dp_dev_name = config_alloc_get_default(NVS_TYPE_STR, "a2dp_dev_name", CONFIG_A2DP_DEV_NAME, 0);
  450. if(a2dp_dev_name == NULL){
  451. ESP_LOGW(TAG,"Unable to retrieve the a2dp device name from nvs");
  452. esp_bt_dev_set_device_name(CONFIG_A2DP_DEV_NAME);
  453. }
  454. else {
  455. esp_bt_dev_set_device_name(a2dp_dev_name);
  456. free(a2dp_dev_name);
  457. }
  458. ESP_LOGI(TAG,"Preparing to connect");
  459. /* register GAP callback function */
  460. esp_bt_gap_register_callback(bt_app_gap_cb);
  461. /* initialize A2DP source */
  462. esp_a2d_register_callback(&bt_app_a2d_cb);
  463. esp_a2d_source_register_data_callback(&output_bt_data);
  464. esp_a2d_source_init();
  465. /* set discoverable and connectable mode */
  466. esp_bt_gap_set_scan_mode(ESP_BT_CONNECTABLE, ESP_BT_GENERAL_DISCOVERABLE);
  467. /* start device discovery */
  468. ESP_LOGI(TAG,"Starting device discovery...");
  469. s_a2d_state = APP_AV_STATE_DISCOVERING;
  470. esp_bt_gap_start_discovery(ESP_BT_INQ_MODE_GENERAL_INQUIRY, 10, 0);
  471. /* create and start heart beat timer */
  472. do {
  473. int tmr_id = 0;
  474. s_tmr = xTimerCreate("connTmr", (CONFIG_A2DP_CONTROL_DELAY_MS / portTICK_RATE_MS),
  475. pdTRUE, (void *)tmr_id, a2d_app_heart_beat);
  476. xTimerStart(s_tmr, portMAX_DELAY);
  477. } while (0);
  478. break;
  479. }
  480. default:
  481. ESP_LOGE(TAG,"%s unhandled evt %d", __func__, event);
  482. break;
  483. }
  484. }
  485. static void bt_app_av_media_proc(uint16_t event, void *param)
  486. {
  487. esp_a2d_cb_param_t *a2d = NULL;
  488. switch (s_media_state) {
  489. case APP_AV_MEDIA_STATE_IDLE: {
  490. if (event == BT_APP_HEART_BEAT_EVT) {
  491. if(!output_stopped())
  492. {
  493. ESP_LOGI(TAG,"Output state is %s, Checking if A2DP is ready.", output_state_str());
  494. esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_CHECK_SRC_RDY);
  495. }
  496. } else if (event == ESP_A2D_MEDIA_CTRL_ACK_EVT) {
  497. a2d = (esp_a2d_cb_param_t *)(param);
  498. if (a2d->media_ctrl_stat.cmd == ESP_A2D_MEDIA_CTRL_CHECK_SRC_RDY &&
  499. a2d->media_ctrl_stat.status == ESP_A2D_MEDIA_CTRL_ACK_SUCCESS
  500. ) {
  501. ESP_LOGI(TAG,"a2dp media ready, starting playback!");
  502. s_media_state = APP_AV_MEDIA_STATE_STARTING;
  503. esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_START);
  504. }
  505. }
  506. break;
  507. }
  508. case APP_AV_MEDIA_STATE_STARTING: {
  509. if (event == ESP_A2D_MEDIA_CTRL_ACK_EVT) {
  510. a2d = (esp_a2d_cb_param_t *)(param);
  511. if (a2d->media_ctrl_stat.cmd == ESP_A2D_MEDIA_CTRL_START &&
  512. a2d->media_ctrl_stat.status == ESP_A2D_MEDIA_CTRL_ACK_SUCCESS) {
  513. ESP_LOGI(TAG,"a2dp media started successfully.");
  514. s_media_state = APP_AV_MEDIA_STATE_STARTED;
  515. } else {
  516. // not started succesfully, transfer to idle state
  517. ESP_LOGI(TAG,"a2dp media start failed.");
  518. s_media_state = APP_AV_MEDIA_STATE_IDLE;
  519. }
  520. }
  521. break;
  522. }
  523. case APP_AV_MEDIA_STATE_STARTED: {
  524. if (event == BT_APP_HEART_BEAT_EVT) {
  525. if(output_stopped()) {
  526. ESP_LOGI(TAG,"Output state is %s. Stopping a2dp media ...", output_state_str());
  527. s_media_state = APP_AV_MEDIA_STATE_STOPPING;
  528. esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_STOP);
  529. } else {
  530. output_bt_tick();
  531. }
  532. }
  533. break;
  534. }
  535. case APP_AV_MEDIA_STATE_STOPPING: {
  536. ESP_LOG_DEBUG_EVENT(TAG,QUOTE(APP_AV_MEDIA_STATE_STOPPING));
  537. if (event == ESP_A2D_MEDIA_CTRL_ACK_EVT) {
  538. a2d = (esp_a2d_cb_param_t *)(param);
  539. if (a2d->media_ctrl_stat.cmd == ESP_A2D_MEDIA_CTRL_STOP &&
  540. a2d->media_ctrl_stat.status == ESP_A2D_MEDIA_CTRL_ACK_SUCCESS) {
  541. ESP_LOGI(TAG,"a2dp media stopped successfully...");
  542. s_media_state = APP_AV_MEDIA_STATE_IDLE;
  543. } else {
  544. ESP_LOGI(TAG,"a2dp media stopping...");
  545. esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_STOP);
  546. }
  547. }
  548. break;
  549. }
  550. case APP_AV_MEDIA_STATE_WAIT_DISCONNECT:{
  551. esp_a2d_source_disconnect(s_peer_bda);
  552. s_a2d_state = APP_AV_STATE_DISCONNECTING;
  553. ESP_LOGI(TAG,"a2dp disconnecting...");
  554. }
  555. }
  556. }
  557. static void bt_app_av_state_unconnected(uint16_t event, void *param)
  558. {
  559. switch (event) {
  560. case ESP_A2D_CONNECTION_STATE_EVT:
  561. ESP_LOG_DEBUG_EVENT(TAG,QUOTE(ESP_A2D_CONNECTION_STATE_EVT));
  562. // this could happen if connection was established
  563. // right after we timed out. Pass the call down to the connecting
  564. // handler.
  565. esp_a2d_cb_param_t *a2d = (esp_a2d_cb_param_t *)(param);
  566. if (a2d->conn_stat.state == ESP_A2D_CONNECTION_STATE_CONNECTED){
  567. bt_app_av_state_connecting(event, param);
  568. }
  569. break;
  570. case ESP_A2D_AUDIO_STATE_EVT:
  571. ESP_LOG_DEBUG_EVENT(TAG,QUOTE(ESP_A2D_AUDIO_STATE_EVT));
  572. break;
  573. case ESP_A2D_AUDIO_CFG_EVT:
  574. ESP_LOG_DEBUG_EVENT(TAG,QUOTE(ESP_A2D_AUDIO_CFG_EVT));
  575. break;
  576. case ESP_A2D_MEDIA_CTRL_ACK_EVT:
  577. ESP_LOG_DEBUG_EVENT(TAG,QUOTE(ESP_A2D_MEDIA_CTRL_ACK_EVT));
  578. break;
  579. case BT_APP_HEART_BEAT_EVT: {
  580. switch (esp_bluedroid_get_status()) {
  581. case ESP_BLUEDROID_STATUS_UNINITIALIZED:
  582. ESP_LOGV(TAG,"BlueDroid Status is ESP_BLUEDROID_STATUS_UNINITIALIZED.");
  583. break;
  584. case ESP_BLUEDROID_STATUS_INITIALIZED:
  585. ESP_LOGV(TAG,"BlueDroid Status is ESP_BLUEDROID_STATUS_INITIALIZED.");
  586. break;
  587. case ESP_BLUEDROID_STATUS_ENABLED:
  588. ESP_LOGV(TAG,"BlueDroid Status is ESP_BLUEDROID_STATUS_ENABLED.");
  589. break;
  590. default:
  591. break;
  592. }
  593. for(uint8_t l=0;art_a2dp_connecting[l][0]!='\0';l++){
  594. ESP_LOGI(TAG,"%s",art_a2dp_connecting[l]);
  595. }
  596. ESP_LOGI(TAG,"Device: %s", s_peer_bdname);
  597. if(esp_a2d_source_connect(s_peer_bda)==ESP_OK) {
  598. A2DP_TIMER_INIT;
  599. s_a2d_state = APP_AV_STATE_CONNECTING;
  600. }
  601. else {
  602. // there was an issue connecting... continue to discover
  603. ESP_LOGE(TAG,"Attempt at connecting failed, restart at discover...");
  604. esp_bt_gap_start_discovery(ESP_BT_INQ_MODE_GENERAL_INQUIRY, 10, 0);
  605. }
  606. break;
  607. }
  608. default:
  609. ESP_LOGE(TAG,"%s unhandled evt %d", __func__, event);
  610. break;
  611. }
  612. }
  613. static void bt_app_av_state_connecting(uint16_t event, void *param)
  614. {
  615. esp_a2d_cb_param_t *a2d = NULL;
  616. switch (event) {
  617. case ESP_A2D_CONNECTION_STATE_EVT: {
  618. a2d = (esp_a2d_cb_param_t *)(param);
  619. if (a2d->conn_stat.state == ESP_A2D_CONNECTION_STATE_CONNECTED) {
  620. s_a2d_state = APP_AV_STATE_CONNECTED;
  621. s_media_state = APP_AV_MEDIA_STATE_IDLE;
  622. ESP_LOGD(TAG,"Setting scan mode to ESP_BT_NON_CONNECTABLE, ESP_BT_NON_DISCOVERABLE");
  623. esp_bt_gap_set_scan_mode(ESP_BT_NON_CONNECTABLE, ESP_BT_NON_DISCOVERABLE);
  624. ESP_LOGD(TAG,"Done setting scan mode. App state is now CONNECTED and media state IDLE.");
  625. for(uint8_t l=0;art_a2dp_connected[l][0]!='\0';l++){
  626. ESP_LOGI(TAG,"%s",art_a2dp_connected[l]);
  627. }
  628. } else if (a2d->conn_stat.state == ESP_A2D_CONNECTION_STATE_DISCONNECTED) {
  629. s_a2d_state = APP_AV_STATE_UNCONNECTED;
  630. }
  631. break;
  632. }
  633. case ESP_A2D_AUDIO_STATE_EVT:
  634. ESP_LOG_DEBUG_EVENT(TAG,QUOTE(ESP_A2D_AUDIO_STATE_EVT));
  635. break;
  636. case ESP_A2D_AUDIO_CFG_EVT:
  637. ESP_LOG_DEBUG_EVENT(TAG,QUOTE(ESP_A2D_AUDIO_CFG_EVT));
  638. break;
  639. case ESP_A2D_MEDIA_CTRL_ACK_EVT:
  640. ESP_LOG_DEBUG_EVENT(TAG,QUOTE(ESP_A2D_MEDIA_CTRL_ACK_EVT));
  641. break;
  642. case BT_APP_HEART_BEAT_EVT:
  643. if (IS_A2DP_TIMER_OVER)
  644. {
  645. s_a2d_state = APP_AV_STATE_UNCONNECTED;
  646. ESP_LOGW(TAG,"A2DP Connect time out! Setting state to Unconnected. ");
  647. }
  648. ESP_LOGV(TAG,"BT_APP_HEART_BEAT_EVT");
  649. break;
  650. default:
  651. ESP_LOGE(TAG,"%s unhandled evt %d", __func__, event);
  652. break;
  653. }
  654. }
  655. static void bt_app_av_state_connected(uint16_t event, void *param)
  656. {
  657. esp_a2d_cb_param_t *a2d = NULL;
  658. switch (event) {
  659. case ESP_A2D_CONNECTION_STATE_EVT: {
  660. a2d = (esp_a2d_cb_param_t *)(param);
  661. if (a2d->conn_stat.state == ESP_A2D_CONNECTION_STATE_DISCONNECTED) {
  662. ESP_LOGI(TAG,"a2dp disconnected");
  663. s_a2d_state = APP_AV_STATE_UNCONNECTED;
  664. esp_bt_gap_set_scan_mode(ESP_BT_CONNECTABLE, ESP_BT_GENERAL_DISCOVERABLE);
  665. }
  666. break;
  667. }
  668. case ESP_A2D_AUDIO_STATE_EVT: {
  669. ESP_LOG_DEBUG_EVENT(TAG,QUOTE(ESP_A2D_AUDIO_STATE_EVT));
  670. a2d = (esp_a2d_cb_param_t *)(param);
  671. if (ESP_A2D_AUDIO_STATE_STARTED == a2d->audio_stat.state) {
  672. s_pkt_cnt = 0;
  673. }
  674. break;
  675. }
  676. case ESP_A2D_AUDIO_CFG_EVT:
  677. // not suppposed to occur for A2DP source
  678. ESP_LOG_DEBUG_EVENT(TAG,QUOTE(ESP_A2D_AUDIO_CFG_EVT));
  679. break;
  680. case ESP_A2D_MEDIA_CTRL_ACK_EVT:{
  681. ESP_LOG_DEBUG_EVENT(TAG,QUOTE(ESP_A2D_MEDIA_CTRL_ACK_EVT));
  682. bt_app_av_media_proc(event, param);
  683. break;
  684. }
  685. case BT_APP_HEART_BEAT_EVT: {
  686. ESP_LOGV(TAG,QUOTE(BT_APP_HEART_BEAT_EVT));
  687. bt_app_av_media_proc(event, param);
  688. break;
  689. }
  690. default:
  691. ESP_LOGE(TAG,"%s unhandled evt %d", __func__, event);
  692. break;
  693. }
  694. }
  695. static void bt_app_av_state_disconnecting(uint16_t event, void *param)
  696. {
  697. esp_a2d_cb_param_t *a2d = NULL;
  698. switch (event) {
  699. case ESP_A2D_CONNECTION_STATE_EVT: {
  700. ESP_LOG_DEBUG_EVENT(TAG,QUOTE(ESP_A2D_CONNECTION_STATE_EVT));
  701. a2d = (esp_a2d_cb_param_t *)(param);
  702. if (a2d->conn_stat.state == ESP_A2D_CONNECTION_STATE_DISCONNECTED) {
  703. ESP_LOGI(TAG,"a2dp disconnected");
  704. s_a2d_state = APP_AV_STATE_UNCONNECTED;
  705. esp_bt_gap_set_scan_mode(ESP_BT_CONNECTABLE, ESP_BT_GENERAL_DISCOVERABLE);
  706. }
  707. break;
  708. }
  709. case ESP_A2D_AUDIO_STATE_EVT:
  710. ESP_LOG_DEBUG_EVENT(TAG,QUOTE(ESP_A2D_AUDIO_STATE_EVT));
  711. break;
  712. case ESP_A2D_AUDIO_CFG_EVT:
  713. ESP_LOG_DEBUG_EVENT(TAG,QUOTE(ESP_A2D_AUDIO_CFG_EVT));
  714. break;
  715. case ESP_A2D_MEDIA_CTRL_ACK_EVT:
  716. ESP_LOG_DEBUG_EVENT(TAG,QUOTE(ESP_A2D_MEDIA_CTRL_ACK_EVT));
  717. break;
  718. case BT_APP_HEART_BEAT_EVT:
  719. ESP_LOG_DEBUG_EVENT(TAG,QUOTE(BT_APP_HEART_BEAT_EVT));
  720. break;
  721. default:
  722. ESP_LOGE(TAG,"%s unhandled evt %d", __func__, event);
  723. break;
  724. }
  725. }