Files
soundshot/main/bt_app.c
Brent Perteet b8a3a09e9f Fix Bluetooth pairing, menu crashes, and improve UX
Major fixes and improvements to Bluetooth device management and menu navigation:

**Bluetooth Device Pairing**
- Fixed discovered devices not being saved as paired after connection
- Only save devices to NVS when successfully connected (not just discovered)
- Auto-pair discovered devices on successful A2DP connection
- Update device list to show paired status immediately after connection

**Critical Bug Fixes**
- Fixed dangling pointer crash in NVS request/response mechanism
  - Was sending pointer to stack variable, now sends result value directly
  - Prevents crash when connecting to Bluetooth devices
- Fixed use-after-free crash when clicking menu items after dynamic updates
  - Menu context now properly synchronized after adding/removing items
  - Prevents InstructionFetchError crashes in menu navigation
- Fixed memory exhaustion by reducing MAX_BT_DEVICES from 20 to 8
  - Prevents heap allocation failures when populating device list

**Menu & UX Improvements**
- "Clear Paired" button now properly disconnects active connections
- "Clear Paired" button always visible when paired devices exist
- GUI updates immediately after clearing paired devices
- Paired devices marked with asterisk prefix (* Device Name)
- Removed redundant "(paired)" suffix text
- Long device names scroll smoothly when selected (3-second animation)
- Refresh button preserved during menu updates to prevent crashes
- Menu focus state properly maintained across all dynamic updates

**Technical Details**
- bt_add_discovered_device() no longer saves to NVS
- Added currentFocusIndex() calls after all menu modifications
- Improved clear_bt_device_list() to avoid deleting active buttons
- Added bt_disconnect_current_device() for clean disconnections
- Fixed NVS notification mechanism to avoid stack variable pointers

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-14 11:39:58 -06:00

1885 lines
63 KiB
C

/*
* SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Unlicense OR CC0-1.0
*/
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
#include "freertos/FreeRTOSConfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "freertos/task.h"
#include "freertos/stream_buffer.h"
#include "esp_log.h"
#include "bt_app.h"
#include "system.h"
#include "esp_bt.h"
#include "esp_bt_main.h"
#include "esp_bt_device.h"
#include "esp_gap_bt_api.h"
#include "esp_a2dp_api.h"
#include "esp_avrc_api.h"
#include "nvs_flash.h"
#include "nvs.h"
#include "esp_timer.h"
/* log tags */
#define BT_AV_TAG "BT_AV"
#define BT_RC_CT_TAG "RC_CT"
/* device name */
#define TARGET_DEVICE_NAME "ESP_SPEAKER"
#define LOCAL_DEVICE_NAME "ESP_A2DP_SRC"
/* AVRCP used transaction label */
#define APP_RC_CT_TL_GET_CAPS (0)
#define APP_RC_CT_TL_RN_VOLUME_CHANGE (1)
/* NVS storage constants */
#define NVS_NAMESPACE "bt_devices"
#define NVS_KEY_PREFIX "device_"
#define NVS_KEY_COUNT "dev_count"
#define MAX_PAIRED_DEVICES 10
enum {
BT_APP_STACK_UP_EVT = 0x0000, /* event for stack up */
BT_APP_HEART_BEAT_EVT = 0xff00, /* event for heart beat */
};
/* A2DP global states */
enum {
APP_AV_STATE_IDLE,
APP_AV_STATE_DISCOVERING,
APP_AV_STATE_DISCOVERED,
APP_AV_STATE_UNCONNECTED,
APP_AV_STATE_CONNECTING,
APP_AV_STATE_CONNECTED,
APP_AV_STATE_DISCONNECTING,
};
/* sub states of APP_AV_STATE_CONNECTED */
enum {
APP_AV_MEDIA_STATE_IDLE,
APP_AV_MEDIA_STATE_STARTING,
APP_AV_MEDIA_STATE_STARTED,
APP_AV_MEDIA_STATE_STOPPING,
};
/*********************************
* STATIC FUNCTION DECLARATIONS
********************************/
/* application task handler */
static void bt_app_task_handler(void *arg);
/* message sender for Work queue */
static bool bt_app_send_msg(bt_app_msg_t *msg);
/* handler for dispatched message */
static void bt_app_work_dispatched(bt_app_msg_t *msg);
/* handler for bluetooth stack enabled events */
static void bt_av_hdl_stack_evt(uint16_t event, void *p_param);
/* avrc controller event handler */
static void bt_av_hdl_avrc_ct_evt(uint16_t event, void *p_param);
/* GAP callback function */
static void bt_app_gap_cb(esp_bt_gap_cb_event_t event, esp_bt_gap_cb_param_t *param);
/* callback function for A2DP source */
static void bt_app_a2d_cb(esp_a2d_cb_event_t event, esp_a2d_cb_param_t *param);
/* callback function for A2DP source audio data stream */
static int32_t bt_app_a2d_data_cb(uint8_t *data, int32_t len);
/* callback function for AVRCP controller */
static void bt_app_rc_ct_cb(esp_avrc_ct_cb_event_t event, esp_avrc_ct_cb_param_t *param);
/* handler for heart beat timer */
static void bt_app_a2d_heart_beat(TimerHandle_t arg);
/* A2DP application state machine */
static void bt_app_av_sm_hdlr(uint16_t event, void *param);
/* utils for transfer BLuetooth Deveice Address into string form */
static char *bda2str(const uint8_t *bda, char *str, size_t size);
static esp_err_t bt_try_connect_known_devices(void);
static void bt_debug_print_known_devices(void);
static esp_err_t bt_add_discovered_device(esp_bd_addr_t bda, const char *name);
static esp_err_t bt_try_connect_all_known_devices(void);
static esp_err_t bt_try_next_known_device(void);
/* A2DP application state machine handler for each state */
static void bt_app_av_state_unconnected_hdlr(uint16_t event, void *param);
static void bt_app_av_state_connecting_hdlr(uint16_t event, void *param);
static void bt_app_av_state_connected_hdlr(uint16_t event, void *param);
static void bt_app_av_state_disconnecting_hdlr(uint16_t event, void *param);
static void add_device_to_list(esp_bd_addr_t bda, const char *name, bool is_paired, int rssi);
/*********************************
* STATIC VARIABLE DEFINITIONS
********************************/
static QueueHandle_t s_bt_app_task_queue = NULL;
static TaskHandle_t s_bt_app_task_handle = NULL;
static esp_bd_addr_t s_peer_bda = {0}; /* Bluetooth Device Address of peer device*/
static uint8_t s_peer_bdname[ESP_BT_GAP_MAX_BDNAME_LEN + 1]; /* Bluetooth Device Name of peer device*/
static int s_a2d_state = APP_AV_STATE_IDLE; /* A2DP global state */
static int s_media_state = APP_AV_MEDIA_STATE_IDLE; /* sub states of APP_AV_STATE_CONNECTED */
static int s_intv_cnt = 0; /* count of heart beat intervals */
static int s_connecting_intv = 0; /* count of heart beat intervals for connecting */
static uint32_t s_pkt_cnt = 0; /* count of packets */
/* Device list for GUI */
static bt_device_list_t s_device_list = {0};
static esp_avrc_rn_evt_cap_mask_t s_avrc_peer_rn_cap; /* AVRC target notification event capability bit mask */
static TimerHandle_t s_tmr;
static int s_current_device_index = -1; /* index of device currently being attempted */
static paired_device_t s_known_devices[MAX_PAIRED_DEVICES]; /* cached list of known devices */
static size_t s_known_device_count = 0; /* count of cached known devices */
/* Volume control */
static uint8_t s_volume_level = 64; /* Current volume (0-127, default ~50%) */
static bool s_volume_control_available = false; /* Whether AVRC volume control is available */
/*********************************
* NVS STORAGE FUNCTION DEFINITIONS
********************************/
// This function is no longer used - replaced by system_savePairedDevice
// This function is no longer used - replaced by system_loadPairedDevices
// This function is no longer used - replaced by system_isDeviceKnown
static esp_err_t bt_try_connect_known_devices(void)
{
paired_device_t devices[MAX_PAIRED_DEVICES];
size_t count = MAX_PAIRED_DEVICES;
esp_err_t ret = system_loadPairedDevices(devices, &count);
if (ret != ESP_OK || count == 0) {
ESP_LOGI(BT_AV_TAG, "No known devices to connect to");
return ESP_ERR_NOT_FOUND;
}
// Filter out devices that have never been connected (last_connected == 0)
// and sort by last_connected timestamp (most recent first)
paired_device_t connected_devices[MAX_PAIRED_DEVICES];
size_t connected_count = 0;
for (int i = 0; i < count; i++) {
if (devices[i].last_connected > 0) {
connected_devices[connected_count++] = devices[i];
}
}
if (connected_count == 0) {
ESP_LOGI(BT_AV_TAG, "No previously connected devices to reconnect to");
return ESP_ERR_NOT_FOUND;
}
// Sort connected devices by last_connected timestamp (most recent first)
for (int i = 0; i < connected_count - 1; i++) {
for (int j = i + 1; j < connected_count; j++) {
if (connected_devices[i].last_connected < connected_devices[j].last_connected) {
paired_device_t temp = connected_devices[i];
connected_devices[i] = connected_devices[j];
connected_devices[j] = temp;
}
}
}
// Try to connect to the most recently connected device
char bda_str[18];
ESP_LOGI(BT_AV_TAG, "Attempting to connect to previously connected device: %s (%s)",
connected_devices[0].name, bda2str(connected_devices[0].bda, bda_str, sizeof(bda_str)));
memcpy(s_peer_bda, connected_devices[0].bda, ESP_BD_ADDR_LEN);
strcpy((char*)s_peer_bdname, connected_devices[0].name);
ret = esp_a2d_source_connect(s_peer_bda);
if (ret == ESP_OK) {
s_a2d_state = APP_AV_STATE_CONNECTING;
s_connecting_intv = 0;
}
return ret;
}
static void bt_debug_print_known_devices(void)
{
const paired_device_t* devices;
size_t count = 0;
devices = system_getPairedDevices(&count);
if (!devices) {
ESP_LOGE(BT_AV_TAG, "Failed to load devices for debug");
return;
}
ESP_LOGI(BT_AV_TAG, "=== Known Paired Devices (%d) ===", count);
for (int i = 0; i < count; i++) {
char bda_str[18];
ESP_LOGI(BT_AV_TAG, "%d: %s (%s) last_connected: %lu",
i + 1, devices[i].name,
bda2str(devices[i].bda, bda_str, sizeof(bda_str)),
devices[i].last_connected);
}
ESP_LOGI(BT_AV_TAG, "=== End Device List ===");
}
static esp_err_t __attribute__((unused)) nvs_remove_paired_device(esp_bd_addr_t bda)
{
paired_device_t devices[MAX_PAIRED_DEVICES];
size_t count = MAX_PAIRED_DEVICES;
esp_err_t ret = system_loadPairedDevices(devices, &count);
if (ret != ESP_OK || count == 0) {
return ESP_ERR_NOT_FOUND;
}
// Find device to remove
int found_index = -1;
for (int i = 0; i < count; i++) {
if (memcmp(devices[i].bda, bda, ESP_BD_ADDR_LEN) == 0) {
found_index = i;
break;
}
}
if (found_index == -1) {
return ESP_ERR_NOT_FOUND;
}
// Open NVS for writing
nvs_handle_t nvs_handle;
ret = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &nvs_handle);
if (ret != ESP_OK) {
return ret;
}
// Shift remaining devices
for (int i = found_index; i < count - 1; i++) {
devices[i] = devices[i + 1];
}
count--;
// Save updated devices
char key[32];
for (int i = 0; i < count; i++) {
snprintf(key, sizeof(key), "%s%d", NVS_KEY_PREFIX, i);
ret = nvs_set_blob(nvs_handle, key, &devices[i], sizeof(paired_device_t));
if (ret != ESP_OK) {
nvs_close(nvs_handle);
return ret;
}
}
// Remove the last device slot
snprintf(key, sizeof(key), "%s%d", NVS_KEY_PREFIX, (int)count);
nvs_erase_key(nvs_handle, key);
// Update count
ret = nvs_set_blob(nvs_handle, NVS_KEY_COUNT, &count, sizeof(size_t));
if (ret == ESP_OK) {
ret = nvs_commit(nvs_handle);
}
nvs_close(nvs_handle);
return ret;
}
static esp_err_t __attribute__((unused)) nvs_get_known_device_count(size_t *count)
{
if (!count) {
return ESP_ERR_INVALID_ARG;
}
nvs_handle_t nvs_handle;
esp_err_t ret = nvs_open(NVS_NAMESPACE, NVS_READONLY, &nvs_handle);
if (ret != ESP_OK) {
*count = 0;
return ESP_OK; // No devices is not an error
}
size_t required_size = sizeof(size_t);
ret = nvs_get_blob(nvs_handle, NVS_KEY_COUNT, count, &required_size);
if (ret != ESP_OK) {
*count = 0;
ret = ESP_OK; // No devices is not an error
}
nvs_close(nvs_handle);
return ret;
}
static esp_err_t bt_add_discovered_device(esp_bd_addr_t bda, const char *name)
{
if (!bda || !name) {
return ESP_ERR_INVALID_ARG;
}
// Don't save discovered devices to NVS - they're not paired yet!
// They will only be saved to NVS when successfully connected.
// Just log that we discovered this device.
char bda_str[18];
ESP_LOGI(BT_AV_TAG, "Discovered device: %s (%s)",
name, bda2str(bda, bda_str, sizeof(bda_str)));
return ESP_OK;
}
static esp_err_t __attribute__((unused)) nvs_update_connection_timestamp(esp_bd_addr_t bda)
{
if (!bda) {
return ESP_ERR_INVALID_ARG;
}
paired_device_t devices[MAX_PAIRED_DEVICES];
size_t count = MAX_PAIRED_DEVICES;
esp_err_t ret = system_loadPairedDevices(devices, &count);
if (ret != ESP_OK || count == 0) {
ESP_LOGW(BT_AV_TAG, "No devices found to update timestamp");
return ESP_ERR_NOT_FOUND;
}
// Find the device and update its timestamp
int device_index = -1;
for (int i = 0; i < count; i++) {
if (memcmp(devices[i].bda, bda, ESP_BD_ADDR_LEN) == 0) {
device_index = i;
break;
}
}
if (device_index == -1) {
ESP_LOGW(BT_AV_TAG, "Device not found in NVS to update timestamp");
return ESP_ERR_NOT_FOUND;
}
// Update timestamp to current time (using ESP timer)
devices[device_index].last_connected = (uint32_t)(esp_timer_get_time() / 1000000); // Convert to seconds
// Save updated device
ret = system_savePairedDevice(&devices[device_index]);
if (ret == ESP_OK) {
char bda_str[18];
ESP_LOGI(BT_AV_TAG, "Updated connection timestamp for device: %s (%s)",
devices[device_index].name, bda2str(devices[device_index].bda, bda_str, sizeof(bda_str)));
} else {
ESP_LOGE(BT_AV_TAG, "Failed to update connection timestamp: %s", esp_err_to_name(ret));
}
return ret;
}
static esp_err_t bt_try_connect_all_known_devices(void)
{
// Load all known devices into cache
s_known_device_count = MAX_PAIRED_DEVICES;
esp_err_t ret = system_loadPairedDevices(s_known_devices, &s_known_device_count);
if (ret != ESP_OK || s_known_device_count == 0) {
ESP_LOGI(BT_AV_TAG, "No known devices to connect to");
s_current_device_index = -1;
return ESP_ERR_NOT_FOUND;
}
// Sort devices by last_connected timestamp (most recent first)
// This prioritizes recently connected devices
for (int i = 0; i < s_known_device_count - 1; i++) {
for (int j = i + 1; j < s_known_device_count; j++) {
if (s_known_devices[i].last_connected < s_known_devices[j].last_connected) {
paired_device_t temp = s_known_devices[i];
s_known_devices[i] = s_known_devices[j];
s_known_devices[j] = temp;
}
}
}
// Start with the first (most recently connected) device
s_current_device_index = 0;
char bda_str[18];
ESP_LOGI(BT_AV_TAG, "Attempting to connect to device %d/%d: %s (%s)",
s_current_device_index + 1, (int)s_known_device_count,
s_known_devices[s_current_device_index].name,
bda2str(s_known_devices[s_current_device_index].bda, bda_str, sizeof(bda_str)));
memcpy(s_peer_bda, s_known_devices[s_current_device_index].bda, ESP_BD_ADDR_LEN);
strcpy((char*)s_peer_bdname, s_known_devices[s_current_device_index].name);
ret = esp_a2d_source_connect(s_peer_bda);
if (ret == ESP_OK) {
s_a2d_state = APP_AV_STATE_CONNECTING;
s_connecting_intv = 0;
} else {
ESP_LOGE(BT_AV_TAG, "Failed to initiate connection: %s", esp_err_to_name(ret));
}
return ret;
}
static esp_err_t bt_try_next_known_device(void)
{
if (s_current_device_index < 0 || s_known_device_count == 0) {
ESP_LOGI(BT_AV_TAG, "No more devices to try");
return ESP_ERR_NOT_FOUND;
}
// Move to next device
s_current_device_index++;
if (s_current_device_index >= s_known_device_count) {
ESP_LOGI(BT_AV_TAG, "Exhausted all known devices, starting discovery...");
s_current_device_index = -1;
return ESP_ERR_NOT_FOUND;
}
char bda_str[18];
ESP_LOGI(BT_AV_TAG, "Attempting to connect to next device %d/%d: %s (%s)",
s_current_device_index + 1, (int)s_known_device_count,
s_known_devices[s_current_device_index].name,
bda2str(s_known_devices[s_current_device_index].bda, bda_str, sizeof(bda_str)));
memcpy(s_peer_bda, s_known_devices[s_current_device_index].bda, ESP_BD_ADDR_LEN);
strcpy((char*)s_peer_bdname, s_known_devices[s_current_device_index].name);
esp_err_t ret = esp_a2d_source_connect(s_peer_bda);
if (ret == ESP_OK) {
s_a2d_state = APP_AV_STATE_CONNECTING;
s_connecting_intv = 0;
} else {
ESP_LOGE(BT_AV_TAG, "Failed to initiate connection: %s", esp_err_to_name(ret));
}
return ret;
}
/*********************************
* STATIC FUNCTION DEFINITIONS
********************************/
static char *bda2str(const uint8_t *bda, char *str, size_t size)
{
if (bda == NULL || str == NULL || size < 18) {
return NULL;
}
sprintf(str, "%02x:%02x:%02x:%02x:%02x:%02x",
bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
return str;
}
static bool get_name_from_eir(uint8_t *eir, uint8_t *bdname, uint8_t *bdname_len)
{
uint8_t *rmt_bdname = NULL;
uint8_t rmt_bdname_len = 0;
if (!eir) {
return false;
}
/* get complete or short local name from eir data */
rmt_bdname = esp_bt_gap_resolve_eir_data(eir, ESP_BT_EIR_TYPE_CMPL_LOCAL_NAME, &rmt_bdname_len);
if (!rmt_bdname) {
rmt_bdname = esp_bt_gap_resolve_eir_data(eir, ESP_BT_EIR_TYPE_SHORT_LOCAL_NAME, &rmt_bdname_len);
}
if (rmt_bdname) {
if (rmt_bdname_len > ESP_BT_GAP_MAX_BDNAME_LEN) {
rmt_bdname_len = ESP_BT_GAP_MAX_BDNAME_LEN;
}
if (bdname) {
memcpy(bdname, rmt_bdname, rmt_bdname_len);
bdname[rmt_bdname_len] = '\0';
}
if (bdname_len) {
*bdname_len = rmt_bdname_len;
}
return true;
}
return false;
}
static void filter_inquiry_scan_result(esp_bt_gap_cb_param_t *param)
{
char bda_str[18];
uint32_t cod = 0; /* class of device */
int32_t rssi = -129; /* invalid value */
uint8_t *eir = NULL;
esp_bt_gap_dev_prop_t *p;
/* handle the discovery results */
for (int i = 0; i < param->disc_res.num_prop; i++) {
p = param->disc_res.prop + i;
switch (p->type) {
case ESP_BT_GAP_DEV_PROP_COD:
cod = *(uint32_t *)(p->val);
break;
case ESP_BT_GAP_DEV_PROP_RSSI:
rssi = *(int8_t *)(p->val);
break;
case ESP_BT_GAP_DEV_PROP_EIR:
eir = (uint8_t *)(p->val);
break;
case ESP_BT_GAP_DEV_PROP_BDNAME:
default:
break;
}
}
// Log device details for debugging
ESP_LOGI(BT_AV_TAG, " CoD: 0x%"PRIx32", Valid: %d, RSSI: %"PRId32", EIR: %p",
cod, esp_bt_gap_is_valid_cod(cod), rssi, eir);
/* search for device with MAJOR service class as "rendering" in COD */
if (!esp_bt_gap_is_valid_cod(cod) ||
!(esp_bt_gap_get_cod_srvc(cod) & ESP_BT_COD_SRVC_RENDERING)) {
ESP_LOGI(BT_AV_TAG, " Device filtered out - not an audio rendering device");
return;
}
ESP_LOGI(BT_AV_TAG, "Scanned device: %s", bda2str(param->disc_res.bda, bda_str, 18));
ESP_LOGI(BT_AV_TAG, "--Class of Device: 0x%"PRIx32, cod);
ESP_LOGI(BT_AV_TAG, "--RSSI: %"PRId32, rssi);
/* search for target device in its Extended Inqury Response */
if (eir) {
get_name_from_eir(eir, s_peer_bdname, NULL);
// Save discovered audio device to NVS (but don't connect to it)
bt_add_discovered_device(param->disc_res.bda, (char *)s_peer_bdname);
// Add to device list for GUI
add_device_to_list(param->disc_res.bda, (char *)s_peer_bdname, false, rssi);
ESP_LOGI(BT_AV_TAG, "Found audio device, address %s, name %s (added to list)",
bda_str, s_peer_bdname);
// Don't automatically connect - just continue discovering more devices
// User will manually select a device from the menu to connect
}
}
static void bt_app_gap_cb(esp_bt_gap_cb_event_t event, esp_bt_gap_cb_param_t *param)
{
switch (event) {
/* when device discovered a result, this event comes */
case ESP_BT_GAP_DISC_RES_EVT: {
// Log ALL discovered devices for debugging
char bda_str[18];
ESP_LOGI(BT_AV_TAG, "*** Device discovered: %s (A2DP state: %d)",
bda2str(param->disc_res.bda, bda_str, 18), s_a2d_state);
// Process the result regardless of A2DP state
filter_inquiry_scan_result(param);
break;
}
/* when discovery state changed, this event comes */
case ESP_BT_GAP_DISC_STATE_CHANGED_EVT: {
if (param->disc_st_chg.state == ESP_BT_GAP_DISCOVERY_STOPPED) {
ESP_LOGI(BT_AV_TAG, "Device discovery stopped.");
s_device_list.discovery_active = false;
// Notify GUI that discovery is complete so it can refresh the display
system_notifyAll(EM_EVENT_BT_DISCOVERY_COMPLETE);
// Don't automatically connect - wait for user selection
// Only connect if we're in DISCOVERED state (manually triggered by bt_connect_device)
if (s_a2d_state == APP_AV_STATE_DISCOVERED) {
s_a2d_state = APP_AV_STATE_CONNECTING;
ESP_LOGI(BT_AV_TAG, "a2dp connecting to peer: %s", s_peer_bdname);
esp_a2d_source_connect(s_peer_bda);
}
} else if (param->disc_st_chg.state == ESP_BT_GAP_DISCOVERY_STARTED) {
ESP_LOGI(BT_AV_TAG, "Discovery started.");
s_device_list.discovery_active = true;
}
break;
}
/* when authentication completed, this event comes */
case ESP_BT_GAP_AUTH_CMPL_EVT: {
if (param->auth_cmpl.stat == ESP_BT_STATUS_SUCCESS) {
ESP_LOGI(BT_AV_TAG, "authentication success: %s", param->auth_cmpl.device_name);
esp_log_buffer_hex(BT_AV_TAG, param->auth_cmpl.bda, ESP_BD_ADDR_LEN);
} else {
ESP_LOGE(BT_AV_TAG, "authentication failed, status: %d", param->auth_cmpl.stat);
}
break;
}
/* when Legacy Pairing pin code requested, this event comes */
case ESP_BT_GAP_PIN_REQ_EVT: {
ESP_LOGI(BT_AV_TAG, "ESP_BT_GAP_PIN_REQ_EVT min_16_digit: %d", param->pin_req.min_16_digit);
if (param->pin_req.min_16_digit) {
ESP_LOGI(BT_AV_TAG, "Input pin code: 0000 0000 0000 0000");
esp_bt_pin_code_t pin_code = {0};
esp_bt_gap_pin_reply(param->pin_req.bda, true, 16, pin_code);
} else {
ESP_LOGI(BT_AV_TAG, "Input pin code: 1234");
esp_bt_pin_code_t pin_code;
pin_code[0] = '1';
pin_code[1] = '2';
pin_code[2] = '3';
pin_code[3] = '4';
esp_bt_gap_pin_reply(param->pin_req.bda, true, 4, pin_code);
}
break;
}
#if (CONFIG_EXAMPLE_SSP_ENABLED == true)
/* when Security Simple Pairing user confirmation requested, this event comes */
case ESP_BT_GAP_CFM_REQ_EVT:
ESP_LOGI(BT_AV_TAG, "ESP_BT_GAP_CFM_REQ_EVT Please compare the numeric value: %"PRIu32, param->cfm_req.num_val);
esp_bt_gap_ssp_confirm_reply(param->cfm_req.bda, true);
break;
/* when Security Simple Pairing passkey notified, this event comes */
case ESP_BT_GAP_KEY_NOTIF_EVT:
ESP_LOGI(BT_AV_TAG, "ESP_BT_GAP_KEY_NOTIF_EVT passkey: %"PRIu32, param->key_notif.passkey);
break;
/* when Security Simple Pairing passkey requested, this event comes */
case ESP_BT_GAP_KEY_REQ_EVT:
ESP_LOGI(BT_AV_TAG, "ESP_BT_GAP_KEY_REQ_EVT Please enter passkey!");
break;
#endif
/* when GAP mode changed, this event comes */
case ESP_BT_GAP_MODE_CHG_EVT:
ESP_LOGI(BT_AV_TAG, "ESP_BT_GAP_MODE_CHG_EVT mode: %d", param->mode_chg.mode);
break;
case ESP_BT_GAP_GET_DEV_NAME_CMPL_EVT:
if (param->get_dev_name_cmpl.status == ESP_BT_STATUS_SUCCESS) {
ESP_LOGI(BT_AV_TAG, "ESP_BT_GAP_GET_DEV_NAME_CMPL_EVT device name: %s", param->get_dev_name_cmpl.name);
} else {
ESP_LOGI(BT_AV_TAG, "ESP_BT_GAP_GET_DEV_NAME_CMPL_EVT failed, state: %d", param->get_dev_name_cmpl.status);
}
break;
/* other */
default: {
ESP_LOGI(BT_AV_TAG, "event: %d", event);
break;
}
}
return;
}
static void bt_av_hdl_stack_evt(uint16_t event, void *p_param)
{
ESP_LOGD(BT_AV_TAG, "%s event: %d", __func__, event);
switch (event) {
/* when stack up worked, this event comes */
case BT_APP_STACK_UP_EVT: {
char *dev_name = LOCAL_DEVICE_NAME;
esp_bt_gap_set_device_name(dev_name);
esp_bt_gap_register_callback(bt_app_gap_cb);
esp_avrc_ct_init();
esp_avrc_ct_register_callback(bt_app_rc_ct_cb);
esp_avrc_rn_evt_cap_mask_t evt_set = {0};
esp_avrc_rn_evt_bit_mask_operation(ESP_AVRC_BIT_MASK_OP_SET, &evt_set, ESP_AVRC_RN_VOLUME_CHANGE);
ESP_ERROR_CHECK(esp_avrc_tg_set_rn_evt_cap(&evt_set));
esp_a2d_source_init();
esp_a2d_register_callback(&bt_app_a2d_cb);
esp_a2d_source_register_data_callback(bt_app_a2d_data_cb);
/* Avoid the state error of s_a2d_state caused by the connection initiated by the peer device. */
esp_bt_gap_set_scan_mode(ESP_BT_NON_CONNECTABLE, ESP_BT_NON_DISCOVERABLE);
esp_bt_gap_get_device_name();
// Print list of saved devices from NVS
bt_debug_print_known_devices();
// Try to connect to known devices automatically (those we've connected to before)
esp_err_t connect_ret = bt_try_connect_known_devices();
if (connect_ret != ESP_OK) {
// No known devices found - stay in unconnected state
// Don't start discovery automatically - user must do it from menu
ESP_LOGI(BT_AV_TAG, "No previously connected devices found. User can discover devices from menu.");
s_a2d_state = APP_AV_STATE_UNCONNECTED;
} else {
ESP_LOGI(BT_AV_TAG, "Attempting to connect to previously connected device...");
}
/* create and start heart beat timer */
do {
int tmr_id = 0;
s_tmr = xTimerCreate("connTmr", (10000 / portTICK_PERIOD_MS),
pdTRUE, (void *) &tmr_id, bt_app_a2d_heart_beat);
xTimerStart(s_tmr, portMAX_DELAY);
} while (0);
break;
}
/* other */
default: {
ESP_LOGE(BT_AV_TAG, "%s unhandled event: %d", __func__, event);
break;
}
}
}
static void bt_app_a2d_cb(esp_a2d_cb_event_t event, esp_a2d_cb_param_t *param)
{
bt_app_work_dispatch(bt_app_av_sm_hdlr, event, param, sizeof(esp_a2d_cb_param_t), NULL);
}
#define SAMPLE_RATE 44100
#define TONE_FREQ 440.0f // A4
#define FADE_FREQ 1.0f // 1 Hz fade L->R
#define STREAM_BUF_SIZE (8192)
#define CHUNK_SIZE (512)
StreamBufferHandle_t audio_stream_buf;
void generate_synth_pcm(uint8_t *buf, int len) {
static float phase = 0.0f;
static float fade_phase = 0.0f;
int16_t *samples = (int16_t *)buf;
int samples_needed = len / 4; // 4 bytes per stereo frame (2 bytes L, 2 bytes R)
for (int i = 0; i < samples_needed; i++) {
// Fade L/R amplitude: 0..1 for L, inverted for R
float fade = (sinf(2 * M_PI * fade_phase) + 1.0f) * 0.5f;
// Sine wave sample
float sample = sinf(2 * M_PI * phase);
int16_t left = (int16_t)(sample * fade * 32767);
int16_t right = (int16_t)(sample * (1.0f - fade) * 32767);
samples[i * 2 + 0] = left;
samples[i * 2 + 1] = right;
// Advance phases
phase += TONE_FREQ / SAMPLE_RATE;
if (phase >= 1.0f) phase -= 1.0f;
fade_phase += FADE_FREQ / SAMPLE_RATE;
if (fade_phase >= 1.0f) fade_phase -= 1.0f;
}
}
#define MIN_RATE_HZ 1.0f
#define MAX_RATE_HZ 440.0f
#define CLICK_AMPLITUDE 32000 // 16-bit
#define EXP_K 3.0f
#define DEADBAND_ANGLE 0.5f
static float click_timer = 0.0f;
void generate_exp(uint8_t *buf, int len, float balance)
{
const float k = 3.0f;
int16_t *samples = (int16_t *)buf;
int samples_needed = len / 4;
float abs_balance = fabsf(balance);
float rate_hz = MAX_RATE_HZ*expf(k*(abs_balance - 1.0f));
//float rate_hz = MIN_RATE_HZ * powf(MAX_RATE_HZ / MIN_RATE_HZ, abs_balance);
float samples_per_click = SAMPLE_RATE / rate_hz;
for (int i = 0; i < samples_needed; i++) {
int16_t left = 0;
int16_t right = 0;
if (click_timer <= 0.0f) {
// Insert a short pulse: single sample spike
if (balance < 0) {
left = CLICK_AMPLITUDE;
} else if (balance > 0) {
right = CLICK_AMPLITUDE;
}
click_timer += samples_per_click;
}
click_timer -= 1.0f;
samples[i * 2 + 0] = left;
samples[i * 2 + 1] = right;
}
}
void generate_synth_clicks(uint8_t *buf, int len, float balance)
{
generate_exp(buf, len, balance);
return;
int16_t *samples = (int16_t *)buf;
int samples_needed = len / 4;
float abs_balance = fabsf(balance);
float rate_hz = MIN_RATE_HZ * powf(MAX_RATE_HZ / MIN_RATE_HZ, abs_balance);
float samples_per_click = SAMPLE_RATE / rate_hz;
for (int i = 0; i < samples_needed; i++) {
int16_t left = 0;
int16_t right = 0;
if (click_timer <= 0.0f) {
// Insert a short pulse: single sample spike
if (balance < 0) {
left = CLICK_AMPLITUDE;
} else if (balance > 0) {
right = CLICK_AMPLITUDE;
}
click_timer += samples_per_click;
}
click_timer -= 1.0f;
samples[i * 2 + 0] = left;
samples[i * 2 + 1] = right;
}
}
void audio_producer_task(void *pvParameters) {
uint8_t chunk[CHUNK_SIZE];
int core_id = xPortGetCoreID();
ESP_LOGI("Producer", "Running on core %d", core_id);
system_subscribe(xTaskGetCurrentTaskHandle());
#if 0
while (1) {
generate_synth_pcm(chunk, sizeof(chunk));
size_t sent = xStreamBufferSend(audio_stream_buf, chunk, sizeof(chunk), portMAX_DELAY);
if (sent < sizeof(chunk)) {
ESP_LOGW(BT_APP_CORE_TAG, "Dropped %d bytes", sizeof(chunk) - sent);
}
}
#endif
static float phase = 0.0f;
float balance = 0.0f; // -1.0 = left, +1.0 = right
uint32_t raw_value;
uint32_t notifiedBits = 0;
while (1) {
// Non-blocking check for new notification:
// clear on entry (first param), wait for any bit, block forever
xTaskNotifyWait(
0, // clear any old bits on entry
0, // clear bits on exit
&notifiedBits,
0);
if (notifiedBits & EM_EVENT_NEW_DATA)
{
ImuData_t d = system_getImuData();
if (fabs(d.raw[ANGLE_XY]) > 45.0f)
{
balance = 0.0f;
}
else
{
if (fabs(d.angle) <= DEADBAND_ANGLE)
{
balance = 0.0f;
}
else
{
balance = -d.angle / MAX_INDICATION_ANGLE;
}
}
}
if (balance > 1.0f)
{
balance = 1.0f;
}
else
if (balance < -1.0f)
{
balance = -1.0f;
}
generate_synth_clicks(chunk, sizeof(chunk), balance);
#if 0
// Synthesize audio using latest balance
int16_t *samples = (int16_t *)chunk;
int samples_needed = CHUNK_SIZE / 4;
for (int i = 0; i < samples_needed; i++) {
float sample = sinf(2 * M_PI * phase);
float left_gain = 0.5f * (1.0f - balance);
float right_gain = 0.5f * (1.0f + balance);
int16_t left = (int16_t)(sample * left_gain * 32767);
int16_t right = (int16_t)(sample * right_gain * 32767);
samples[i * 2 + 0] = left;
samples[i * 2 + 1] = right;
phase += TONE_FREQ / SAMPLE_RATE;
if (phase >= 1.0f) phase -= 1.0f;
}
#endif
// Push chunk to FIFO
xStreamBufferSend(audio_stream_buf, chunk, sizeof(chunk), portMAX_DELAY);
}
}
/* generate some random noise to simulate source audio */
static int32_t bt_app_a2d_data_cb(uint8_t *data, int32_t len)
{
if (data == NULL || len <= 0 || audio_stream_buf == NULL) {
return 0;
}
size_t bytes_read = xStreamBufferReceive(audio_stream_buf, data, len, 0);
if (bytes_read < len) {
memset(data + bytes_read, 0, len - bytes_read); // fill silence
}
return len;
#if 0
if (data == NULL || len < 0) {
return 0;
}
int16_t *p_buf = (int16_t *)data;
for (int i = 0; i < (len >> 1); i++) {
p_buf[i] = rand() % (1 << 16);
}
return len;
#endif
}
#if 0
/* Generate a continuous 440Hz sine wave */
static int32_t bt_app_a2d_data_cb(uint8_t *data, int32_t len)
{
if (data == NULL || len < 0) {
return 0;
}
int16_t *p_buf = (int16_t *)data;
for (int i = 0; i < (len >> 1); i++) {
p_buf[i] = rand() % (1 << 16);
}
return len;
#if 0
static double phase = 0.0;
const double frequency = 440.0; // A4 tone (440 Hz)
const double sample_rate = 44100.0; // 44.1 kHz sample rate
const double phase_increment = 2.0 * M_PI * frequency / sample_rate;
const int16_t amplitude = 32767; // Maximum amplitude for 16-bit audio
//ESP_LOGI(BT_AV_TAG, "len: %d", (int)len);
// Process stereo samples (each sample is 16-bit)
for (int i = 0; i < len / 4; i++) {
// Generate the sample value
int16_t sample = (int16_t)(amplitude * sin(phase));
// Write the same sample to both left and right channels
// Left channel
data[4*i] = sample & 0xFF; // Low byte
data[4*i + 1] = (sample >> 8); // High byte
// Right channel
data[4*i + 2] = sample & 0xFF; // Low byte
data[4*i + 3] = (sample >> 8); // High byte
// Update phase for next sample
phase += phase_increment;
if (phase >= 2.0 * M_PI) {
phase -= 2.0 * M_PI; // Keep phase in [0, 2π)
}
}
return len;
#endif
}
#endif
static void bt_app_a2d_heart_beat(TimerHandle_t arg)
{
bt_app_work_dispatch(bt_app_av_sm_hdlr, BT_APP_HEART_BEAT_EVT, NULL, 0, NULL);
}
static void bt_app_av_sm_hdlr(uint16_t event, void *param)
{
ESP_LOGI(BT_AV_TAG, "%s state: %d, event: 0x%x", __func__, s_a2d_state, event);
/* select handler according to different states */
switch (s_a2d_state) {
case APP_AV_STATE_DISCOVERING:
case APP_AV_STATE_DISCOVERED:
break;
case APP_AV_STATE_UNCONNECTED:
bt_app_av_state_unconnected_hdlr(event, param);
break;
case APP_AV_STATE_CONNECTING:
bt_app_av_state_connecting_hdlr(event, param);
break;
case APP_AV_STATE_CONNECTED:
bt_app_av_state_connected_hdlr(event, param);
break;
case APP_AV_STATE_DISCONNECTING:
bt_app_av_state_disconnecting_hdlr(event, param);
break;
default:
ESP_LOGE(BT_AV_TAG, "%s invalid state: %d", __func__, s_a2d_state);
break;
}
}
static void bt_app_av_state_unconnected_hdlr(uint16_t event, void *param)
{
esp_a2d_cb_param_t *a2d = NULL;
/* handle the events of interest in unconnected state */
switch (event) {
case ESP_A2D_CONNECTION_STATE_EVT:
case ESP_A2D_AUDIO_STATE_EVT:
case ESP_A2D_AUDIO_CFG_EVT:
case ESP_A2D_MEDIA_CTRL_ACK_EVT:
break;
case BT_APP_HEART_BEAT_EVT: {
// Don't automatically try to reconnect - wait for user to select device
// from the menu
break;
}
case ESP_A2D_REPORT_SNK_DELAY_VALUE_EVT: {
a2d = (esp_a2d_cb_param_t *)(param);
ESP_LOGI(BT_AV_TAG, "%s, delay value: %u * 1/10 ms", __func__, a2d->a2d_report_delay_value_stat.delay_value);
break;
}
default: {
ESP_LOGE(BT_AV_TAG, "%s unhandled event: %d", __func__, event);
break;
}
}
}
static void bt_app_av_state_connecting_hdlr(uint16_t event, void *param)
{
esp_a2d_cb_param_t *a2d = NULL;
/* handle the events of interest in connecting state */
switch (event) {
case ESP_A2D_CONNECTION_STATE_EVT: {
a2d = (esp_a2d_cb_param_t *)(param);
if (a2d->conn_stat.state == ESP_A2D_CONNECTION_STATE_CONNECTED) {
ESP_LOGI(BT_AV_TAG, "a2dp connected");
s_a2d_state = APP_AV_STATE_CONNECTED;
s_media_state = APP_AV_MEDIA_STATE_IDLE;
// Check if device is already paired, if not, add it as paired
if (!system_isDeviceKnown(s_peer_bda)) {
ESP_LOGI(BT_AV_TAG, "Device not in paired list, adding: %s", s_peer_bdname);
paired_device_t new_device;
memcpy(new_device.bda, s_peer_bda, ESP_BD_ADDR_LEN);
strncpy(new_device.name, (char*)s_peer_bdname, DEVICE_NAME_MAX_LEN - 1);
new_device.name[DEVICE_NAME_MAX_LEN - 1] = '\0';
new_device.last_connected = (uint32_t)(esp_timer_get_time() / 1000000);
system_savePairedDevice(&new_device);
// Update the device in the GUI list to show it as paired
for (int i = 0; i < s_device_list.count; i++) {
if (memcmp(s_device_list.devices[i].bda, s_peer_bda, ESP_BD_ADDR_LEN) == 0) {
s_device_list.devices[i].is_paired = true;
ESP_LOGI(BT_AV_TAG, "Marked device as paired in GUI list: %s", s_peer_bdname);
break;
}
}
} else {
// Update connection timestamp for this device
system_updateConnectionTimestamp(s_peer_bda);
}
} else if (a2d->conn_stat.state == ESP_A2D_CONNECTION_STATE_DISCONNECTED) {
ESP_LOGI(BT_AV_TAG, "Connection failed.");
// If device was previously connected (known device), don't retry automatically
// User can manually reconnect from menu
s_a2d_state = APP_AV_STATE_UNCONNECTED;
}
break;
}
case ESP_A2D_AUDIO_STATE_EVT:
case ESP_A2D_AUDIO_CFG_EVT:
case ESP_A2D_MEDIA_CTRL_ACK_EVT:
break;
case BT_APP_HEART_BEAT_EVT:
/**
* Switch state to APP_AV_STATE_UNCONNECTED
* when connecting lasts more than 2 heart beat intervals.
*/
if (++s_connecting_intv >= 2) {
ESP_LOGI(BT_AV_TAG, "Connection timeout.");
// Return to unconnected state - don't retry automatically
// User can manually reconnect from menu
s_a2d_state = APP_AV_STATE_UNCONNECTED;
s_connecting_intv = 0;
}
break;
case ESP_A2D_REPORT_SNK_DELAY_VALUE_EVT: {
a2d = (esp_a2d_cb_param_t *)(param);
ESP_LOGI(BT_AV_TAG, "%s, delay value: %u * 1/10 ms", __func__, a2d->a2d_report_delay_value_stat.delay_value);
break;
}
default:
ESP_LOGE(BT_AV_TAG, "%s unhandled event: %d", __func__, event);
break;
}
}
static void bt_app_av_media_proc(uint16_t event, void *param)
{
esp_a2d_cb_param_t *a2d = NULL;
switch (s_media_state) {
case APP_AV_MEDIA_STATE_IDLE: {
if (event == BT_APP_HEART_BEAT_EVT) {
ESP_LOGI(BT_AV_TAG, "a2dp media ready checking ...");
esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_CHECK_SRC_RDY);
} else if (event == ESP_A2D_MEDIA_CTRL_ACK_EVT) {
a2d = (esp_a2d_cb_param_t *)(param);
if (a2d->media_ctrl_stat.cmd == ESP_A2D_MEDIA_CTRL_CHECK_SRC_RDY &&
a2d->media_ctrl_stat.status == ESP_A2D_MEDIA_CTRL_ACK_SUCCESS) {
ESP_LOGI(BT_AV_TAG, "a2dp media ready, starting ...");
esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_START);
s_media_state = APP_AV_MEDIA_STATE_STARTING;
}
}
break;
}
case APP_AV_MEDIA_STATE_STARTING: {
if (event == ESP_A2D_MEDIA_CTRL_ACK_EVT) {
a2d = (esp_a2d_cb_param_t *)(param);
if (a2d->media_ctrl_stat.cmd == ESP_A2D_MEDIA_CTRL_START &&
a2d->media_ctrl_stat.status == ESP_A2D_MEDIA_CTRL_ACK_SUCCESS) {
ESP_LOGI(BT_AV_TAG, "a2dp media start successfully.");
s_intv_cnt = 0;
s_media_state = APP_AV_MEDIA_STATE_STARTED;
} else {
/* not started successfully, transfer to idle state */
ESP_LOGI(BT_AV_TAG, "a2dp media start failed.");
s_media_state = APP_AV_MEDIA_STATE_IDLE;
}
}
break;
}
case APP_AV_MEDIA_STATE_STARTED: {
if (event == BT_APP_HEART_BEAT_EVT) {
#if 0
/* stop media after 10 heart beat intervals */
if (++s_intv_cnt >= 10) {
ESP_LOGI(BT_AV_TAG, "a2dp media suspending...");
esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_SUSPEND);
s_media_state = APP_AV_MEDIA_STATE_STOPPING;
s_intv_cnt = 0;
}
#endif
}
break;
}
case APP_AV_MEDIA_STATE_STOPPING: {
if (event == ESP_A2D_MEDIA_CTRL_ACK_EVT) {
a2d = (esp_a2d_cb_param_t *)(param);
if (a2d->media_ctrl_stat.cmd == ESP_A2D_MEDIA_CTRL_SUSPEND &&
a2d->media_ctrl_stat.status == ESP_A2D_MEDIA_CTRL_ACK_SUCCESS) {
ESP_LOGI(BT_AV_TAG, "a2dp media suspend successfully, disconnecting...");
s_media_state = APP_AV_MEDIA_STATE_IDLE;
esp_a2d_source_disconnect(s_peer_bda);
s_a2d_state = APP_AV_STATE_DISCONNECTING;
} else {
ESP_LOGI(BT_AV_TAG, "a2dp media suspending...");
esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_SUSPEND);
}
}
break;
}
default: {
break;
}
}
}
static void bt_app_av_state_connected_hdlr(uint16_t event, void *param)
{
esp_a2d_cb_param_t *a2d = NULL;
/* handle the events of interest in connected state */
switch (event) {
case ESP_A2D_CONNECTION_STATE_EVT: {
a2d = (esp_a2d_cb_param_t *)(param);
if (a2d->conn_stat.state == ESP_A2D_CONNECTION_STATE_DISCONNECTED) {
ESP_LOGI(BT_AV_TAG, "a2dp disconnected");
s_a2d_state = APP_AV_STATE_UNCONNECTED;
}
break;
}
case ESP_A2D_AUDIO_STATE_EVT: {
a2d = (esp_a2d_cb_param_t *)(param);
if (ESP_A2D_AUDIO_STATE_STARTED == a2d->audio_stat.state) {
s_pkt_cnt = 0;
}
break;
}
case ESP_A2D_AUDIO_CFG_EVT:
// not supposed to occur for A2DP source
break;
case ESP_A2D_MEDIA_CTRL_ACK_EVT:
case BT_APP_HEART_BEAT_EVT: {
bt_app_av_media_proc(event, param);
break;
}
case ESP_A2D_REPORT_SNK_DELAY_VALUE_EVT: {
a2d = (esp_a2d_cb_param_t *)(param);
ESP_LOGI(BT_AV_TAG, "%s, delay value: %u * 1/10 ms", __func__, a2d->a2d_report_delay_value_stat.delay_value);
break;
}
default: {
ESP_LOGE(BT_AV_TAG, "%s unhandled event: %d", __func__, event);
break;
}
}
}
static void bt_app_av_state_disconnecting_hdlr(uint16_t event, void *param)
{
esp_a2d_cb_param_t *a2d = NULL;
/* handle the events of interest in disconnecing state */
switch (event) {
case ESP_A2D_CONNECTION_STATE_EVT: {
a2d = (esp_a2d_cb_param_t *)(param);
if (a2d->conn_stat.state == ESP_A2D_CONNECTION_STATE_DISCONNECTED) {
ESP_LOGI(BT_AV_TAG, "a2dp disconnected");
s_a2d_state = APP_AV_STATE_UNCONNECTED;
}
break;
}
case ESP_A2D_AUDIO_STATE_EVT:
case ESP_A2D_AUDIO_CFG_EVT:
case ESP_A2D_MEDIA_CTRL_ACK_EVT:
case BT_APP_HEART_BEAT_EVT:
break;
case ESP_A2D_REPORT_SNK_DELAY_VALUE_EVT: {
a2d = (esp_a2d_cb_param_t *)(param);
ESP_LOGI(BT_AV_TAG, "%s, delay value: 0x%u * 1/10 ms", __func__, a2d->a2d_report_delay_value_stat.delay_value);
break;
}
default: {
ESP_LOGE(BT_AV_TAG, "%s unhandled event: %d", __func__, event);
break;
}
}
}
/* callback function for AVRCP controller */
static void bt_app_rc_ct_cb(esp_avrc_ct_cb_event_t event, esp_avrc_ct_cb_param_t *param)
{
switch (event) {
case ESP_AVRC_CT_CONNECTION_STATE_EVT:
case ESP_AVRC_CT_PASSTHROUGH_RSP_EVT:
case ESP_AVRC_CT_METADATA_RSP_EVT:
case ESP_AVRC_CT_CHANGE_NOTIFY_EVT:
case ESP_AVRC_CT_REMOTE_FEATURES_EVT:
case ESP_AVRC_CT_GET_RN_CAPABILITIES_RSP_EVT:
case ESP_AVRC_CT_SET_ABSOLUTE_VOLUME_RSP_EVT: {
bt_app_work_dispatch(bt_av_hdl_avrc_ct_evt, event, param, sizeof(esp_avrc_ct_cb_param_t), NULL);
break;
}
default: {
ESP_LOGE(BT_RC_CT_TAG, "Invalid AVRC event: %d", event);
break;
}
}
}
static void bt_av_volume_changed(void)
{
if (esp_avrc_rn_evt_bit_mask_operation(ESP_AVRC_BIT_MASK_OP_TEST, &s_avrc_peer_rn_cap,
ESP_AVRC_RN_VOLUME_CHANGE)) {
esp_avrc_ct_send_register_notification_cmd(APP_RC_CT_TL_RN_VOLUME_CHANGE, ESP_AVRC_RN_VOLUME_CHANGE, 0);
}
}
void bt_av_notify_evt_handler(uint8_t event_id, esp_avrc_rn_param_t *event_parameter)
{
switch (event_id) {
/* when volume changed locally on target, this event comes */
case ESP_AVRC_RN_VOLUME_CHANGE: {
ESP_LOGI(BT_RC_CT_TAG, "Volume changed: %d", event_parameter->volume);
// Update our stored volume level
s_volume_level = event_parameter->volume;
bt_av_volume_changed();
break;
}
/* other */
default:
break;
}
}
/* AVRC controller event handler */
static void bt_av_hdl_avrc_ct_evt(uint16_t event, void *p_param)
{
ESP_LOGD(BT_RC_CT_TAG, "%s evt %d", __func__, event);
esp_avrc_ct_cb_param_t *rc = (esp_avrc_ct_cb_param_t *)(p_param);
switch (event) {
/* when connection state changed, this event comes */
case ESP_AVRC_CT_CONNECTION_STATE_EVT: {
uint8_t *bda = rc->conn_stat.remote_bda;
ESP_LOGI(BT_RC_CT_TAG, "AVRC conn_state event: state %d, [%02x:%02x:%02x:%02x:%02x:%02x]",
rc->conn_stat.connected, bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]);
if (rc->conn_stat.connected) {
esp_avrc_ct_send_get_rn_capabilities_cmd(APP_RC_CT_TL_GET_CAPS);
} else {
s_avrc_peer_rn_cap.bits = 0;
s_volume_control_available = false;
}
break;
}
/* when passthrough responded, this event comes */
case ESP_AVRC_CT_PASSTHROUGH_RSP_EVT: {
ESP_LOGI(BT_RC_CT_TAG, "AVRC passthrough response: key_code 0x%x, key_state %d, rsp_code %d", rc->psth_rsp.key_code,
rc->psth_rsp.key_state, rc->psth_rsp.rsp_code);
break;
}
/* when metadata responded, this event comes */
case ESP_AVRC_CT_METADATA_RSP_EVT: {
ESP_LOGI(BT_RC_CT_TAG, "AVRC metadata response: attribute id 0x%x, %s", rc->meta_rsp.attr_id, rc->meta_rsp.attr_text);
free(rc->meta_rsp.attr_text);
break;
}
/* when notification changed, this event comes */
case ESP_AVRC_CT_CHANGE_NOTIFY_EVT: {
ESP_LOGI(BT_RC_CT_TAG, "AVRC event notification: %d", rc->change_ntf.event_id);
bt_av_notify_evt_handler(rc->change_ntf.event_id, &rc->change_ntf.event_parameter);
break;
}
/* when indicate feature of remote device, this event comes */
case ESP_AVRC_CT_REMOTE_FEATURES_EVT: {
ESP_LOGI(BT_RC_CT_TAG, "AVRC remote features %"PRIx32", TG features %x", rc->rmt_feats.feat_mask, rc->rmt_feats.tg_feat_flag);
break;
}
/* when get supported notification events capability of peer device, this event comes */
case ESP_AVRC_CT_GET_RN_CAPABILITIES_RSP_EVT: {
ESP_LOGI(BT_RC_CT_TAG, "remote rn_cap: count %d, bitmask 0x%x", rc->get_rn_caps_rsp.cap_count,
rc->get_rn_caps_rsp.evt_set.bits);
s_avrc_peer_rn_cap.bits = rc->get_rn_caps_rsp.evt_set.bits;
// Check if volume control is available
if (esp_avrc_rn_evt_bit_mask_operation(ESP_AVRC_BIT_MASK_OP_TEST, &s_avrc_peer_rn_cap, ESP_AVRC_RN_VOLUME_CHANGE)) {
s_volume_control_available = true;
ESP_LOGI(BT_RC_CT_TAG, "Volume control is available");
} else {
s_volume_control_available = false;
ESP_LOGI(BT_RC_CT_TAG, "Volume control is not available");
}
bt_av_volume_changed();
break;
}
/* when set absolute volume responded, this event comes */
case ESP_AVRC_CT_SET_ABSOLUTE_VOLUME_RSP_EVT: {
ESP_LOGI(BT_RC_CT_TAG, "Set absolute volume response: volume %d", rc->set_volume_rsp.volume);
// Update our stored volume level with the confirmed value
s_volume_level = rc->set_volume_rsp.volume;
break;
}
/* other */
default: {
ESP_LOGE(BT_RC_CT_TAG, "%s unhandled event: %d", __func__, event);
break;
}
}
}
static bool bt_app_send_msg(bt_app_msg_t *msg)
{
if (msg == NULL) {
return false;
}
if (pdTRUE != xQueueSend(s_bt_app_task_queue, msg, 10 / portTICK_PERIOD_MS)) {
ESP_LOGE(BT_APP_CORE_TAG, "%s xQueue send failed", __func__);
return false;
}
return true;
}
static void bt_app_work_dispatched(bt_app_msg_t *msg)
{
if (msg->cb) {
msg->cb(msg->event, msg->param);
}
}
static void bt_app_task_handler(void *arg)
{
bt_app_msg_t msg;
int core_id = xPortGetCoreID();
ESP_LOGI("MY_TASK", "Running on core %d", core_id);
for (;;) {
// Check for system events first
uint32_t notifiedBits = 0;
if (xTaskNotifyWait(0xFFFFFFFF, 0xFFFFFFFF, &notifiedBits, pdMS_TO_TICKS(10)) == pdTRUE) {
if (notifiedBits & EM_EVENT_BT_REFRESH) {
ESP_LOGI(BT_AV_TAG, "BT Refresh event received");
bt_clear_discovered_devices();
bt_start_discovery(); // Start new discovery after clearing
// Notify GUI that refresh is done - could add completion event if needed
}
if (notifiedBits & EM_EVENT_BT_CONNECT) {
int device_index = system_getBtDeviceIndex();
ESP_LOGI(BT_AV_TAG, "BT Connect event received for device %d", device_index);
bt_connect_device(device_index);
}
if (notifiedBits & EM_EVENT_VOLUME_UP) {
ESP_LOGI(BT_AV_TAG, "Volume Up event received");
bt_volume_up();
}
if (notifiedBits & EM_EVENT_VOLUME_DOWN) {
ESP_LOGI(BT_AV_TAG, "Volume Down event received");
bt_volume_down();
}
}
/* receive message from work queue and handle it */
if (pdTRUE == xQueueReceive(s_bt_app_task_queue, &msg, pdMS_TO_TICKS(10))) {
ESP_LOGD(BT_APP_CORE_TAG, "%s, signal: 0x%x, event: 0x%x", __func__, msg.sig, msg.event);
switch (msg.sig) {
case BT_APP_SIG_WORK_DISPATCH:
bt_app_work_dispatched(&msg);
break;
default:
ESP_LOGW(BT_APP_CORE_TAG, "%s, unhandled signal: %d", __func__, msg.sig);
break;
}
if (msg.param) {
free(msg.param);
}
}
}
}
/*********************************
* EXTERN FUNCTION DEFINITIONS
********************************/
bool bt_app_work_dispatch(bt_app_cb_t p_cback, uint16_t event, void *p_params, int param_len, bt_app_copy_cb_t p_copy_cback)
{
ESP_LOGD(BT_APP_CORE_TAG, "%s event: 0x%x, param len: %d", __func__, event, param_len);
bt_app_msg_t msg;
memset(&msg, 0, sizeof(bt_app_msg_t));
msg.sig = BT_APP_SIG_WORK_DISPATCH;
msg.event = event;
msg.cb = p_cback;
if (param_len == 0) {
return bt_app_send_msg(&msg);
} else if (p_params && param_len > 0) {
if ((msg.param = malloc(param_len)) != NULL) {
memcpy(msg.param, p_params, param_len);
/* check if caller has provided a copy callback to do the deep copy */
if (p_copy_cback) {
p_copy_cback(msg.param, p_params, param_len);
}
return bt_app_send_msg(&msg);
}
}
return false;
}
void bt_app_task_start_up(void)
{
s_bt_app_task_queue = xQueueCreate(10, sizeof(bt_app_msg_t));
//xTaskCreate(bt_app_task_handler, "BtAppTask", 8192, NULL, 10, &s_bt_app_task_handle);
xTaskCreatePinnedToCore(bt_app_task_handler, "BtAppTask", 8192, NULL, 10, &s_bt_app_task_handle, 1);
// Subscribe to system events for GUI communication
system_subscribe(s_bt_app_task_handle);
}
void bt_app_task_shut_down(void)
{
if (s_bt_app_task_handle) {
vTaskDelete(s_bt_app_task_handle);
s_bt_app_task_handle = NULL;
}
if (s_bt_app_task_queue) {
vQueueDelete(s_bt_app_task_queue);
s_bt_app_task_queue = NULL;
}
}
void bt_app_init(void)
{
esp_err_t ret;
char bda_str[18] = {0};
esp_bluedroid_disable();
esp_bluedroid_deinit();
//esp_err_t esp_bredr_tx_power_get(esp_power_level_t *min_power_level, esp_power_level_t *max_power_level)
esp_power_level_t pmin;
esp_power_level_t pmax;
/*
* This example only uses the functions of Classical Bluetooth.
* So release the controller memory for Bluetooth Low Energy.
*/
ESP_ERROR_CHECK(esp_bt_controller_mem_release(ESP_BT_MODE_BLE));
esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
if (esp_bt_controller_init(&bt_cfg) != ESP_OK) {
ESP_LOGE(BT_AV_TAG, "%s initialize controller failed", __func__);
return;
}
if (esp_bt_controller_enable(ESP_BT_MODE_CLASSIC_BT) != ESP_OK) {
ESP_LOGE(BT_AV_TAG, "%s enable controller failed", __func__);
return;
}
pmin = ESP_PWR_LVL_P7;
pmax = ESP_PWR_LVL_P7;
// pmin = ESP_PWR_LVL_N12;
// pmax = ESP_PWR_LVL_N12;
esp_err_t err = esp_bredr_tx_power_set(pmin, pmax);
if (err != ESP_OK) {
ESP_LOGE(BT_APP_CORE_TAG, "Failed to set TX power: %s", esp_err_to_name(err));
}
esp_bredr_tx_power_get(&pmin, &pmax);
ESP_LOGI(BT_APP_CORE_TAG, "BT Power min = %d\nBT Power max = %d", pmin, pmax);
esp_bluedroid_config_t bluedroid_cfg = BT_BLUEDROID_INIT_CONFIG_DEFAULT();
#if (CONFIG_EXAMPLE_SSP_ENABLED == false)
bluedroid_cfg.ssp_en = false;
#endif
if ((ret = esp_bluedroid_init_with_cfg(&bluedroid_cfg)) != ESP_OK) {
ESP_LOGE(BT_AV_TAG, "%s initialize bluedroid failed: %s", __func__, esp_err_to_name(ret));
return;
}
if (esp_bluedroid_enable() != ESP_OK) {
ESP_LOGE(BT_AV_TAG, "%s enable bluedroid failed", __func__);
return;
}
#if (CONFIG_EXAMPLE_SSP_ENABLED == true)
/* set default parameters for Secure Simple Pairing */
esp_bt_sp_param_t param_type = ESP_BT_SP_IOCAP_MODE;
esp_bt_io_cap_t iocap = ESP_BT_IO_CAP_IO;
esp_bt_gap_set_security_param(param_type, &iocap, sizeof(uint8_t));
#endif
/*
* Set default parameters for Legacy Pairing
* Use variable pin, input pin code when pairing
*/
esp_bt_pin_type_t pin_type = ESP_BT_PIN_TYPE_VARIABLE;
esp_bt_pin_code_t pin_code;
esp_bt_gap_set_pin(pin_type, 0, pin_code);
ESP_LOGI(BT_AV_TAG, "Own address:[%s]", bda2str((uint8_t *)esp_bt_dev_get_address(), bda_str, sizeof(bda_str)));
bt_app_task_start_up();
/* Bluetooth device name, connection mode and profile set up */
bt_app_work_dispatch(bt_av_hdl_stack_evt, BT_APP_STACK_UP_EVT, NULL, 0, NULL);
audio_stream_buf = xStreamBufferCreate(STREAM_BUF_SIZE, 1);
assert(audio_stream_buf != NULL);
//xTaskCreate(audio_producer_task, "audio_producer", 4096, NULL, 5, NULL);
xTaskCreatePinnedToCore(audio_producer_task, "audio_producer", 4096, NULL, 5, NULL, 1);
ESP_LOGI(BT_APP_CORE_TAG, "Audio synth producer started");
vTaskDelay(pdMS_TO_TICKS(1000));
}
/*********************************
* BLUETOOTH DEVICE LIST MANAGEMENT FOR GUI
********************************/
static void add_device_to_list(esp_bd_addr_t bda, const char *name, bool is_paired, int rssi) {
if (!bda) {
ESP_LOGE(BT_AV_TAG, "Null BDA in add_device_to_list");
return;
}
// Check if device already exists
for (int i = 0; i < s_device_list.count; i++) {
if (memcmp(s_device_list.devices[i].bda, bda, ESP_BD_ADDR_LEN) == 0) {
// Update existing device
strncpy(s_device_list.devices[i].name, name ? name : "Unknown", MAX_BT_NAME_LEN - 1);
s_device_list.devices[i].name[MAX_BT_NAME_LEN - 1] = '\0';
s_device_list.devices[i].is_paired = is_paired;
s_device_list.devices[i].rssi = rssi;
ESP_LOGI(BT_AV_TAG, "Updated existing device: %s (%s)",
s_device_list.devices[i].name,
is_paired ? "paired" : "discovered");
return;
}
}
// Add new device if there's space
if (s_device_list.count < MAX_BT_DEVICES) {
memcpy(s_device_list.devices[s_device_list.count].bda, bda, ESP_BD_ADDR_LEN);
strncpy(s_device_list.devices[s_device_list.count].name, name ? name : "Unknown", MAX_BT_NAME_LEN - 1);
s_device_list.devices[s_device_list.count].name[MAX_BT_NAME_LEN - 1] = '\0';
s_device_list.devices[s_device_list.count].is_paired = is_paired;
s_device_list.devices[s_device_list.count].rssi = rssi;
s_device_list.count++;
ESP_LOGI(BT_AV_TAG, "Added new device to list: %s (%s), total devices: %d",
s_device_list.devices[s_device_list.count - 1].name,
is_paired ? "paired" : "discovered",
s_device_list.count);
} else {
ESP_LOGW(BT_AV_TAG, "Device list full, cannot add device: %s", name ? name : "Unknown");
}
}
static void load_paired_devices_to_list(void) {
paired_device_t paired_devices[MAX_PAIRED_DEVICES];
size_t count = MAX_PAIRED_DEVICES;
ESP_LOGI(BT_AV_TAG, "Attempting to load paired devices from NVS");
esp_err_t err = system_loadPairedDevices(paired_devices, &count);
if (err == ESP_OK) {
ESP_LOGI(BT_AV_TAG, "Successfully loaded %d paired devices from NVS", (int)count);
for (size_t i = 0; i < count; i++) {
add_device_to_list(paired_devices[i].bda, paired_devices[i].name, true, 0);
}
ESP_LOGI(BT_AV_TAG, "Added %d paired devices to device list", (int)count);
} else {
ESP_LOGW(BT_AV_TAG, "Failed to load paired devices from NVS: %s", esp_err_to_name(err));
}
}
bt_device_list_t* bt_get_device_list(void) {
// Initialize device list if needed
if (s_device_list.count == 0) {
ESP_LOGI(BT_AV_TAG, "Loading paired devices to list");
load_paired_devices_to_list();
}
ESP_LOGI(BT_AV_TAG, "Device list has %d devices", s_device_list.count);
return &s_device_list;
}
bool bt_start_discovery(void) {
if (s_device_list.discovery_active) {
ESP_LOGW(BT_AV_TAG, "Discovery already active");
return false; // Already discovering
}
// Check if Bluetooth stack is initialized
if (!esp_bluedroid_get_status()) {
ESP_LOGE(BT_AV_TAG, "Bluetooth stack not initialized");
return false;
}
// Check current A2DP state - avoid discovery during connection attempts
if (s_a2d_state == APP_AV_STATE_CONNECTING || s_a2d_state == APP_AV_STATE_DISCOVERING) {
ESP_LOGW(BT_AV_TAG, "Cannot start discovery - A2DP state: %d", s_a2d_state);
// Still load paired devices for display
load_paired_devices_to_list();
return false;
}
// Bluetooth stack is initialized and A2DP state is good - proceed with discovery
// Load paired devices first
ESP_LOGI(BT_AV_TAG, "Loading paired devices before discovery");
load_paired_devices_to_list();
ESP_LOGI(BT_AV_TAG, "Starting Bluetooth device discovery (A2DP state: %d)", s_a2d_state);
// Cancel any previous discovery to ensure clean state
esp_bt_gap_cancel_discovery();
// Small delay to ensure clean state
vTaskDelay(pdMS_TO_TICKS(100));
// Set discovery state first to prevent race conditions
s_device_list.discovery_active = true;
esp_err_t result = esp_bt_gap_start_discovery(ESP_BT_INQ_MODE_GENERAL_INQUIRY, 10, 0);
if (result == ESP_OK) {
ESP_LOGI(BT_AV_TAG, "Device discovery started successfully");
return true;
} else {
ESP_LOGE(BT_AV_TAG, "Failed to start discovery: %s (0x%x)", esp_err_to_name(result), result);
s_device_list.discovery_active = false; // Reset on failure
return false;
}
}
bool bt_stop_discovery(void) {
esp_err_t result = esp_bt_gap_cancel_discovery();
s_device_list.discovery_active = false;
ESP_LOGI(BT_AV_TAG, "Device discovery stopped");
return (result == ESP_OK);
}
bool bt_connect_device(int device_index) {
if (device_index < 0 || device_index >= s_device_list.count) {
ESP_LOGE(BT_AV_TAG, "Invalid device index: %d", device_index);
return false;
}
bt_device_info_t *device = &s_device_list.devices[device_index];
// Stop any ongoing discovery
if (s_device_list.discovery_active) {
bt_stop_discovery();
}
// Copy device info for connection attempt
memcpy(s_peer_bda, device->bda, ESP_BD_ADDR_LEN);
strncpy((char*)s_peer_bdname, device->name, ESP_BT_GAP_MAX_BDNAME_LEN);
s_peer_bdname[ESP_BT_GAP_MAX_BDNAME_LEN] = '\0';
// If device is paired, connect directly
if (device->is_paired) {
ESP_LOGI(BT_AV_TAG, "Connecting to paired device: %s", device->name);
s_a2d_state = APP_AV_STATE_CONNECTING;
esp_a2d_source_connect(device->bda);
} else {
ESP_LOGI(BT_AV_TAG, "Pairing and connecting to device: %s", device->name);
s_a2d_state = APP_AV_STATE_DISCOVERED;
// The GAP callback will handle the connection after discovery stops
esp_bt_gap_cancel_discovery();
}
return true;
}
void bt_clear_discovered_devices(void) {
int new_count = 0;
// Keep only paired devices
for (int i = 0; i < s_device_list.count; i++) {
if (s_device_list.devices[i].is_paired) {
if (new_count != i) {
s_device_list.devices[new_count] = s_device_list.devices[i];
}
new_count++;
}
}
s_device_list.count = new_count;
ESP_LOGI(BT_AV_TAG, "Cleared discovered devices, kept %d paired devices", new_count);
}
void bt_clear_all_devices(void) {
s_device_list.count = 0;
ESP_LOGI(BT_AV_TAG, "Cleared all devices from device list");
}
void bt_disconnect_current_device(void) {
if (s_a2d_state == APP_AV_STATE_CONNECTED) {
ESP_LOGI(BT_AV_TAG, "Disconnecting from current device");
// Stop media first if playing
if (s_media_state == APP_AV_MEDIA_STATE_STARTED) {
esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_SUSPEND);
s_media_state = APP_AV_MEDIA_STATE_STOPPING;
}
// Disconnect A2DP
esp_a2d_source_disconnect(s_peer_bda);
s_a2d_state = APP_AV_STATE_DISCONNECTING;
} else if (s_a2d_state == APP_AV_STATE_CONNECTING) {
ESP_LOGI(BT_AV_TAG, "Cancelling connection attempt");
// Cancel connection attempt
s_a2d_state = APP_AV_STATE_UNCONNECTED;
} else {
ESP_LOGI(BT_AV_TAG, "No device connected (state: %d)", s_a2d_state);
}
}
void bt_volume_up(void) {
if (!s_volume_control_available) {
ESP_LOGW(BT_AV_TAG, "Volume control not available");
return;
}
if (s_volume_level < 127) {
s_volume_level += 10; // Increase by ~8%
if (s_volume_level > 127) s_volume_level = 127;
ESP_LOGI(BT_AV_TAG, "Setting volume to %d", s_volume_level);
esp_avrc_ct_send_set_absolute_volume_cmd(APP_RC_CT_TL_RN_VOLUME_CHANGE, s_volume_level);
}
}
void bt_volume_down(void) {
if (!s_volume_control_available) {
ESP_LOGW(BT_AV_TAG, "Volume control not available");
return;
}
if (s_volume_level > 0) {
if (s_volume_level < 10) {
s_volume_level = 0;
} else {
s_volume_level -= 10; // Decrease by ~8%
}
ESP_LOGI(BT_AV_TAG, "Setting volume to %d", s_volume_level);
esp_avrc_ct_send_set_absolute_volume_cmd(APP_RC_CT_TL_RN_VOLUME_CHANGE, s_volume_level);
}
}
int bt_get_current_volume(void) {
// Convert from 0-127 to 0-100 for GUI
return (s_volume_level * 100) / 127;
}