#include "bt_mgr.h"

#include "rtthread.h"
#include "ble_connection_manager.h"
#include "bt_connection_manager.h"
#include "bf0_pm.h"
#include <drivers/rt_drv_encoder.h>
#include "drv_flash.h"

// #include "lwip/dns.h"
#include "ulog.h"

// #include "lwip/netif.h"
// #include "lwip/dhcp.h"

#include <string.h>
#include <stdio.h>
// #include <rtdef.h>

#include "drv_flash.h"
#include "mem_section.h"

#define BT_MGR_THREAD_NAME              ("bt_mgr_thread")   /**< 蓝牙管理器线程名称 */
#define BT_MGR_THREAD_STACK_SIZE        (4 * 1024)          /**< 蓝牙管理器线程栈大小 */
#define BT_MGR_THREAD_PRIORITY          (17)                /**< 蓝牙管理器线程优先级 */
#define BT_MGR_THREAD_TIMESLICE         (10)                /**< 蓝牙管理器线程时间片大小 */

#define BT_MGR_MAILBOX_NAME             ("bt_mgr_mbox")     /**< 蓝牙管理器邮箱名称 */
#define BT_MGR_MAILBOX_NUM              (10)                /**< 蓝牙管理器邮箱数量 */


#define BT_RECONNECT_MAX_ATTEMPTS       (10)    /**< 蓝牙重连最大尝试次数 */
#define BT_RECONNECT_INTERVAL_MS        (5000)  /**< 蓝牙重连时间间隔 */

#define PAN_RECONNECT_MAX_ATTEMPTS      (0)     /**< 蓝牙PAN重连最大尝试次数 */
#define PAN_RECONNECT_INTERVAL_MS       (5000)  /**< 蓝牙PAN重连时间间隔 */

#define DHCP_RECONNECT_MAX_ATTEMPTS     (0)     /**< 蓝牙DHCP重连最大尝试次数 */
#define DHCP_RECONNECT_INTERVAL_MS      (5000)  /**< 蓝牙DHCP重连时间间隔 */

/*
 * @brief: 应用管理器线程栈，映射线程堆栈到BSS段
*/
#if defined(__CC_ARM) || defined(__CLANG_ARM)
L2_RET_BSS_SECT_BEGIN(g_bt_mgr_thread_stack)
    static uint32_t g_bt_mgr_thread_stack[BT_MGR_THREAD_STACK_SIZE / sizeof(uint32_t)];
L2_RET_BSS_SECT_END
#else
    static uint32_t g_bt_mgr_thread_stack[BT_MGR_THREAD_STACK_SIZE / sizeof(uint32_t)] L2_RET_BSS_SECT(g_bt_mgr_thread_stack);
#endif


static struct bt_mgr_t g_bt_mgr;

/*
 * @brief 初始化蓝牙管理器
 * @return 初始化结果
*/
rt_err_t bt_mgr_init(void)
{
    struct bt_mgr_t *mgr = &g_bt_mgr;

    if (mgr == RT_NULL || mgr->is_initlized) {
        rt_kprintf("func: %s, invalid parameter.\r\n", __func__);
        return -RT_ERROR;
    }

    memset(mgr, 0, sizeof(struct bt_mgr_t));
    mgr->bt.is_connected = false;
    mgr->bt.reconnect.is_reconnecting = false;
    mgr->bt.reconnect.current_attempts = 0;
    mgr->bt.reconnect.max_attempts = BT_RECONNECT_MAX_ATTEMPTS;
    mgr->bt.reconnect.interval_ms = BT_RECONNECT_INTERVAL_MS;
    mgr->bt.reconnect.timer_name = "bt_reconnect_timer";
    mgr->bt.reconnect.timer = RT_NULL;
    
    mgr->pan.is_connected = false;
    mgr->pan.reconnect.is_reconnecting = false;
    mgr->pan.reconnect.current_attempts = 0;
    mgr->pan.reconnect.max_attempts = PAN_RECONNECT_MAX_ATTEMPTS;
    mgr->pan.reconnect.interval_ms = PAN_RECONNECT_INTERVAL_MS;
    mgr->pan.reconnect.timer_name = "pan_reconnect_timer";
    mgr->pan.reconnect.timer = RT_NULL;
    
    mgr->dhcp.reconnect.is_reconnecting = false;
    mgr->dhcp.reconnect.current_attempts = 0;
    mgr->dhcp.reconnect.max_attempts = DHCP_RECONNECT_MAX_ATTEMPTS;
    mgr->dhcp.reconnect.interval_ms = DHCP_RECONNECT_INTERVAL_MS;
    mgr->dhcp.reconnect.timer_name = "dhcp_reconnect_timer";
    mgr->dhcp.reconnect.timer = RT_NULL;

    mgr->a2dp.play_state = false;

    mgr->avrcp.abs_volume_enable = false;

    mgr->mbox = rt_mb_create(BT_MGR_MAILBOX_NAME, BT_MGR_MAILBOX_NUM, RT_IPC_FLAG_FIFO);
    RT_ASSERT(mgr->mbox);

    rt_err_t err = rt_thread_init(&mgr->thread,
                                    BT_MGR_THREAD_NAME,
                                    bt_mgr_thread_entry_handle,
                                    mgr,
                                    g_bt_mgr_thread_stack,
                                    BT_MGR_THREAD_STACK_SIZE,
                                    BT_MGR_THREAD_PRIORITY,
                                    BT_MGR_THREAD_TIMESLICE);
    RT_ASSERT(!err);

    rt_thread_startup(&mgr->thread);

    bt_interface_register_bt_event_notify_callback(bt_mgr_notify_event_handle);

    sifli_ble_enable();

    mgr->is_initlized = true;

    rt_kprintf("func: %s, bt manager initilized.\r\n", __func__);

    return RT_EOK;
}

/**
 * @brief 反初始化蓝牙管理器
 * @return 反初始化结果
*/  
rt_err_t bt_mgr_deinit(void)
{
    struct bt_mgr_t *mgr = &g_bt_mgr;

    if (mgr == RT_NULL || !mgr->is_initlized) {
        rt_kprintf("func: %s, invalid parameter.\r\n", __func__);
        return -RT_ERROR;
    }

    rt_thread_detach(&mgr->thread);
    rt_mb_delete(mgr->mbox);

    mgr->is_initlized = false;

    rt_kprintf("func: %s, bt manager deinitilized.\r\n", __func__);

    return RT_EOK;
}

/**
 * @brief 蓝牙管理器线程入口函数
 * @param parameter 线程参数
*/
static void bt_mgr_thread_entry_handle(void *parameter)
{
    struct bt_mgr_t *mgr = (struct bt_mgr_t *)parameter;

    while (1) {
        rt_uint32_t msg;
        rt_mb_recv(mgr->mbox, &msg, RT_WAITING_FOREVER);

        switch (msg) {
        case BT_MGR_EVENT_STACK_READY:
            bt_mgr_set_local_name("dsc_luxpeaker");
            break;

        case BT_MGR_EVENT_RECONNECTED_START:
            bt_mgr_bt_timer_start();
            break;
        case BT_MGR_EVENT_RECONNECTED_HANDLE:
            bt_mgr_bt_reconnect_handle();
            break;
        case BT_MGR_EVENT_RECONNECTED_STOP:
            bt_mgr_bt_timer_stop();
            break;

        case BT_MGR_EVENT_PAN_RECONNECTED_START:
            bt_mgr_pan_timer_start();
            break;
        case BT_MGR_EVENT_PAN_RECONNECTED_HANDLE:
            bt_mgr_pan_reconnect_handle();
            break;
        case BT_MGR_EVENT_PAN_RECONNECTED_STOP:
            bt_mgr_pan_timer_stop();
            break;

        case BT_MGR_EVENT_DHCP_RECONNECTED_START:
            bt_mgr_dhcp_timer_start();
            break;
        case BT_MGR_EVENT_DHCP_RECONNECTED_HANDLE:
            bt_mgr_dhcp_reconnect_handle();
            break;
        case BT_MGR_EVENT_DHCP_RECONNECTED_STOP:
            bt_mgr_dhcp_timer_stop();
            break;
        case BT_MGR_EVENT_DHCP_RECONNECT_SUCCESS:
            rt_kprintf("func: %s, dhcp reconnect success.\r\n", __func__);
            break;
        }
    }
}

/**
 * @brief 蓝牙管理器通知事件处理函数
 * @param type 通知事件类型
 * @param event_id 通知事件ID
 * @param data 通知事件数据
 * @param data_len 通知事件数据长度
 * @return 处理结果 0: 成功 -1: 失败
*/
static int bt_mgr_notify_event_handle(uint16_t type, uint16_t event_id, uint8_t *data, uint16_t data_len)
{
    struct bt_mgr_t *mgr = &g_bt_mgr;

    switch (type) {
    case BT_NOTIFY_COMMON:
        switch (event_id) {
        case BT_NOTIFY_COMMON_BT_STACK_READY:
            rt_mb_send(mgr->mbox, BT_MGR_EVENT_STACK_READY);
            break;
        case BT_NOTIFY_COMMON_ENCRYPTION:
            bt_notify_device_mac_t *mac_addr = (bt_notify_device_mac_t *)data;
            mgr->mac_addr = *mac_addr;
            mgr->bt.is_connected = true;

            /* 如果蓝牙重连定时器正在运行，则停止蓝牙重连定时器 */
            if (mgr->bt.reconnect.is_reconnecting) {
                rt_mb_send(mgr->mbox, BT_MGR_EVENT_RECONNECTED_STOP);
            }

            /* 如果DHCP重连定时器正在运行，则停止DHCP重连定时器 */
            if (mgr->dhcp.reconnect.is_reconnecting) {
                rt_mb_send(mgr->mbox, BT_MGR_EVENT_DHCP_RECONNECTED_STOP);
            }

            /* 如果PAN重连定时器正在运行，则停止PAN重连定时器 */
            if (mgr->pan.reconnect.is_reconnecting) {
                rt_mb_send(mgr->mbox, BT_MGR_EVENT_PAN_RECONNECTED_STOP);
            }

            /* 启动PAN重连定时器 */
            rt_mb_send(mgr->mbox, BT_MGR_EVENT_PAN_RECONNECTED_START);
            break;
        case BT_NOTIFY_COMMON_KEY_MISSING:
            bt_notify_device_base_info_t *info_key = (bt_notify_device_base_info_t *)data;
            memset(&mgr->mac_addr, 0xFF, sizeof(mgr->mac_addr));
            bt_cm_delete_bonded_devs_and_linkkey(info_key->mac.addr);
            break;
        case BT_NOTIFY_COMMON_ACL_CONNECTED:
            /* 如果蓝牙重连定时器正在运行，则停止蓝牙重连定时器 */
            if (mgr->bt.reconnect.is_reconnecting) {
                rt_mb_send(mgr->mbox, BT_MGR_EVENT_RECONNECTED_STOP);
            }
            break;
        case BT_NOTIFY_COMMON_ACL_DISCONNECTED:
            bt_notify_device_base_info_t *info_acl = (bt_notify_device_base_info_t *)data;

            rt_kprintf("func: %s, bluetooth disconnected mac: 0x%.2x:%.2x:%.2x:%.2x:%.2x:%.2x, res: %d.\r\n",
                    __func__, info_acl->mac.addr[5], info_acl->mac.addr[4], info_acl->mac.addr[3],
                    info_acl->mac.addr[2], info_acl->mac.addr[1], info_acl->mac.addr[0], info_acl->res);

            mgr->bt.is_connected = false;

            /* 如果蓝牙连接断开，正常断开则发送断开事件，异常断开则启动蓝牙重连定时器 */
            if (info_acl->res == BT_NOTIFY_COMMON_SCO_DISCONNECTED) {
                rt_mb_send(mgr->mbox, BT_MGR_EVENT_DISCONNECTED);
            } else {
                rt_mb_send(mgr->mbox, BT_MGR_EVENT_RECONNECTED_START);
            }
            break;
        }
        break;

    case BT_NOTIFY_A2DP:
        switch (event_id) {
        case BT_NOTIFY_A2DP_START_IND:
            mgr->a2dp.play_state = true;
            rt_kprintf("func: %s, bluetooth audio play start.\r\n", __func__);
            break;
        case BT_NOTIFY_A2DP_SUSPEND_IND:
            mgr->a2dp.play_state = false;
            rt_kprintf("func: %s, bluetooth audio play pause.\r\n", __func__);
            break;
        }
        break;

    case BT_NOTIFY_AVRCP:
        switch (event_id) {
        case BT_NOTIFY_AVRCP_VOLUME_CHANGED_REGISTER:
            mgr->avrcp.abs_volume_enable = true;
            break;
        case BT_NOTIFY_AVRCP_ABSOLUTE_VOLUME:
            uint8_t *absolute_volume = (uint8_t*)data;
            uint8_t local_volume = bt_interface_avrcp_abs_vol_2_local_vol(*absolute_volume, audio_server_get_max_volume());

            // uint8_t *absolute_volume = (uint8_t*)data;
            // uint8_t local_volume = bt_interface_avrcp_abs_vol_2_local_vol(*absolute_volume, audio_server_get_max_volume());

            // audio_server_set_private_volume(AUDIO_TYPE_BT_MUSIC, local_volume);
            break;
        }
        break;

    case BT_NOTIFY_PAN:
        switch (event_id) {
        case BT_NOTIFY_PAN_PROFILE_CONNECTED:
            /* 如果蓝牙连接成功，PAN重连定时器已开启，DHCP重连定时器未开启，开启DHCP重连定时器 */
            if (mgr->bt.is_connected && mgr->pan.reconnect.is_reconnecting && !mgr->dhcp.reconnect.is_reconnecting) { 
                rt_mb_send(mgr->mbox, BT_MGR_EVENT_DHCP_RECONNECTED_START);
            }
            break;
        case BT_NOTIFY_PAN_PROFILE_DISCONNECTED:
            /* 如果蓝牙连接成功，PAN重连定时器未开启，开启PAN重连定时器 */
            if (mgr->bt.is_connected && !mgr->pan.reconnect.is_reconnecting) {
                rt_mb_send(mgr->mbox, BT_MGR_EVENT_PAN_RECONNECTED_START);
            }
            break;
        }
        break;
    }
    return 0;
}


/******************************************************************************************/

/**
 * @brief 启动重连定时器
 * @details 检查重连定时器是否为空, 如果为空, 则初始化重连定时器, 并启动重连定时器
 * @param reconnect 重连参数结构体指针
 * @param timeout_handler 超时处理函数指针
 * @param parameter 超时处理函数参数指针
 * @return rt_err_t 错误码, RT_EOK表示成功, -RT_ERROR表示失败   
*/
static rt_err_t bt_mgr_reconnect_timer_start(struct reconnect_params_t *reconnect,
                                            void (*timeout_handler)(void *parameter),
                                            void *parameter)
{
    if (reconnect == RT_NULL || timeout_handler == RT_NULL) {
        rt_kprintf("func: %s, invalid parameter.\r\n", __func__);
        return -RT_ERROR;
    }

    if (!reconnect->timer) {
        reconnect->timer = rt_timer_create(reconnect->timer_name,
                                            timeout_handler,
                                            parameter,
                                            rt_tick_from_millisecond(reconnect->interval_ms),
                                            RT_TIMER_FLAG_PERIODIC);
        RT_ASSERT(reconnect->timer);
    } else {
        rt_timer_stop(reconnect->timer);
    }

    reconnect->current_attempts = 0;
    reconnect->is_reconnecting = true;

    rt_timer_start(reconnect->timer);

    rt_kprintf("func: %s, %s timer start.\r\n", __func__, reconnect->timer_name);

    return RT_EOK;
}

/**
 * @brief 停止重连定时器
 * @details 检查重连定时器是否为空, 如果不为空, 则停止重连定时器, 并将重连定时器指针设为NULL
 * @param reconnect 重连参数结构体指针
 * @return rt_err_t 错误码, RT_EOK表示成功, -RT_ERROR表示失败   
*/  
static rt_err_t bt_mgr_reconnect_timer_stop(struct reconnect_params_t *reconnect)
{
    if (reconnect == RT_NULL || !reconnect->timer) {
        rt_kprintf("func: %s, invalid parameter.\r\n", __func__);
        return -RT_ERROR;
    }

    rt_timer_stop(reconnect->timer);

    reconnect->timer = RT_NULL;
    reconnect->current_attempts = 0;
    reconnect->is_reconnecting = false;

    rt_kprintf("func: %s, %s timer stop.\r\n", __func__, reconnect->timer_name);

    return RT_EOK;
}


/**
 * @brief 启动蓝牙重连定时器
 * @details 检查重连定时器是否为空, 如果为空, 则初始化重连定时器, 并启动重连定时器  
 * @return rt_err_t 错误码, RT_EOK表示成功, -RT_ERROR表示失败   
*/
static rt_err_t bt_mgr_bt_timer_start(void)
{
    struct bt_mgr_t *mgr = &g_bt_mgr;

    if (mgr->bt.is_connected) {
        rt_kprintf("func: %s, bt is connected.\r\n", __func__);
        return -RT_ERROR;
    }
    bt_mgr_reconnect_timer_start(&mgr->bt.reconnect,
                                bt_mgr_bt_timeout_handle,
                                RT_NULL);

    return RT_EOK;
}

/**
 * @brief 停止蓝牙重连定时器
 * @details 检查重连定时器是否为空, 如果不为空, 则停止重连定时器, 并将重连定时器指针设为NULL
 * @return rt_err_t 错误码, RT_EOK表示成功, -RT_ERROR表示失败   
*/
static rt_err_t bt_mgr_bt_timer_stop(void)
{
    struct bt_mgr_t *mgr = &g_bt_mgr;

    if (!mgr->bt.reconnect.timer) {
        rt_kprintf("func: %s, %s is null.\r\n", __func__, mgr->bt.reconnect.timer_name);
        return -RT_ERROR;
    }
    bt_mgr_reconnect_timer_stop(&mgr->bt.reconnect);    

    return RT_EOK;
}

/**
 * @brief 蓝牙断线重连超时处理函数
 * @details 检查重连次数是否超过最大值, 如果没有超过, 则尝试连接A2DP协议, 如果超过, 则发送蓝牙重连失败事件
 * @param parameter 定时器参数  
*/  
static void bt_mgr_bt_timeout_handle(void *parameter)
{
    struct bt_mgr_t *mgr = &g_bt_mgr;

    rt_mb_send(mgr->mbox, BT_MGR_EVENT_RECONNECTED_HANDLE);
    
    rt_kprintf("func: %s, %s timeout.\r\n", __func__, mgr->bt.reconnect.timer_name);
}

/**
 * @brief 蓝牙断线重连处理函数
 * @details 检查重连次数是否超过最大值, 如果没有超过, 则尝试连接A2DP协议, 如果超过, 则发送蓝牙重连失败事件
 * @return rt_err_t 错误码, RT_EOK表示成功, -RT_ERROR表示失败   
*/
static rt_err_t bt_mgr_bt_reconnect_handle(void)
{
    struct bt_mgr_t *mgr = &g_bt_mgr;
        
    if (mgr->bt.reconnect.max_attempts > 0 &&
        mgr->bt.reconnect.current_attempts >= mgr->bt.reconnect.max_attempts) {
        rt_kprintf("func: %s, bt reconnect attempts exceeds max attempts.\r\n", __func__);
        bt_mgr_bt_timer_stop();
        return -RT_ERROR;
    }
    mgr->bt.reconnect.current_attempts++;
    bt_interface_conn_ext((char *)&mgr->mac_addr, BT_PROFILE_A2DP);

    rt_kprintf("func: %s, %s reconnect, attempts: %d.\r\n", __func__, mgr->bt.reconnect.timer_name, mgr->bt.reconnect.current_attempts);

    return RT_EOK;
}


/**
 * @brief PAN重连定时器开始
 * @details 检查重连定时器是否为空, 如果为空, 则初始化重连定时器, 并启动重连定时器  
 * @return rt_err_t 错误码, RT_EOK表示成功, -RT_ERROR表示失败  
*/
static rt_err_t bt_mgr_pan_timer_start(void)
{
    struct bt_mgr_t *mgr = &g_bt_mgr;

    bt_mgr_reconnect_timer_start(&mgr->pan.reconnect,
                                bt_mgr_pan_timeout_handle,
                                RT_NULL);

    return RT_EOK;
}

/**
 * @brief PAN重连定时器停止
 * @details 检查重连定时器是否为空, 如果不为空, 则停止重连定时器, 并将重连定时器指针设为NULL
 * @return rt_err_t 错误码, RT_EOK表示成功, -RT_ERROR表示失败       
*/
static rt_err_t bt_mgr_pan_timer_stop(void)
{
    struct bt_mgr_t *mgr = &g_bt_mgr;
    
    if (!mgr->pan.reconnect.timer) {
        rt_kprintf("func: %s, %s is null.\r\n", __func__, mgr->pan.reconnect.timer_name);
        return -RT_ERROR;
    }
    bt_mgr_reconnect_timer_stop(&mgr->pan.reconnect);

    return RT_EOK;
}

/**
 * @brief PAN断线重连超时处理函数
 * @details 检查重连次数是否超过最大值, 如果没有超过, 则尝试连接HID协议, 如果超过, 则发送蓝牙重连失败事件
 * @param parameter 定时器参数  
*/  
static void bt_mgr_pan_timeout_handle(void *parameter)
{
    struct bt_mgr_t *mgr = &g_bt_mgr;

    rt_mb_send(mgr->mbox, BT_MGR_EVENT_PAN_RECONNECTED_HANDLE);
    
    rt_kprintf("func: %s, %s timeout.\r\n", __func__, mgr->pan.reconnect.timer_name);
}

/**
 * @brief PAN断线重连处理函数
 * @details 检查重连次数是否超过最大值, 如果没有超过, 则尝试连接HID协议, 如果超过, 则发送蓝牙重连失败事件
 * @return rt_err_t 错误码, RT_EOK表示成功, -RT_ERROR表示失败       
*/
static rt_err_t bt_mgr_pan_reconnect_handle(void)
{
    struct bt_mgr_t *mgr = &g_bt_mgr;
        
    if (mgr->pan.is_connected) { 
        rt_kprintf("func: %s, pan is connected.\r\n", __func__);        
        bt_mgr_pan_timer_stop();
        return -RT_ERROR;
    }
    mgr->pan.reconnect.current_attempts++;
    // bt_interface_conn_ext((char *)&mgr->mac_addr, BT_PROFILE_PAN);

    rt_kprintf("func: %s, %s reconnect, attempts: %d.\r\n", __func__, mgr->pan.reconnect.timer_name, mgr->pan.reconnect.current_attempts);
}


/**
 * @brief DHCP定时器启动函数
 * @details 检查DHCP定时器是否为空, 如果为空, 则初始化DHCP定时器, 并启动DHCP定时器  
 * @return rt_err_t 错误码, RT_EOK表示成功, -RT_ERROR表示失败   
*/
static rt_err_t bt_mgr_dhcp_timer_start(void)
{
    struct bt_mgr_t *mgr = &g_bt_mgr;
        
    if (!mgr->pan.is_connected) {
        rt_kprintf("func: %s, pan is not connected.\r\n", __func__);
        return -RT_ERROR;
    }

    bt_mgr_reconnect_timer_start(&mgr->dhcp.reconnect,
                                 bt_mgr_dhcp_timeout_handle,
                                 RT_NULL);

    return RT_EOK;
}

/**
 * @brief DHCP定时器停止函数
 * @details 检查DHCP定时器是否为空, 如果不为空, 则停止DHCP定时器, 并将DHCP定时器指针设为NULL    
*/  
static rt_err_t bt_mgr_dhcp_timer_stop(void)
{
    struct bt_mgr_t *mgr = &g_bt_mgr;
    
    if (!mgr->dhcp.reconnect.timer) {
        rt_kprintf("func: %s, %s is null.\r\n", __func__, mgr->dhcp.reconnect.timer_name);
        return -RT_ERROR;
    }

    bt_mgr_reconnect_timer_stop(&mgr->dhcp.reconnect);
}

/**
 * @brief DHCP定时器超时处理函数
 * @details 检查DHCP定时器是否为空, 如果不为空, 则停止DHCP定时器, 并发送DHCP获取IP事件  
 * @param parameter 定时器参数
*/
static void bt_mgr_dhcp_timeout_handle(void *parameter)
{
    struct bt_mgr_t *mgr = &g_bt_mgr;
    
    rt_mb_send(mgr->mbox, BT_MGR_EVENT_DHCP_RECONNECTED_HANDLE);
    
    rt_kprintf("func: %s, %s timeout.\r\n", __func__, mgr->dhcp.reconnect.timer_name);
}

/**
 * @brief DHCP重连处理函数
 * @details 增加DHCP获取地址尝试次数, 并尝试连接PAN协议, 如果成功, 则发送成功事件, 否则发送失败事件
 * @return rt_err_t 错误码, RT_EOK表示成功, -RT_ERROR表示失败   
*/ 
static rt_err_t bt_mgr_dhcp_reconnect_handle(void)
{
    struct bt_mgr_t *mgr = &g_bt_mgr;

    // if (bt_mgr_dhcp_get_ip()) {
    //     rt_kprintf("func: %s, dhcp get ip success.\r\n", __func__);
    //     bt_mgr_dhcp_timer_stop();
    //     mgr->pan.is_connected = true;  
    //     rt_mb_send(mgr->mbox, BT_MGR_EVENT_DHCP_RECONNECT_SUCCESS);
    //     return RT_EOK;
    // }
    mgr->dhcp.reconnect.current_attempts++;

    rt_kprintf("func: %s, %s reconnect, attempts: %d.\r\n", __func__, mgr->dhcp.reconnect.timer_name, mgr->dhcp.reconnect.current_attempts);
}


/**
 * @brief 检查蓝牙网络是否已获取有效 IP
 * @details 检查默认网络接口是否存在, 如果不存在, 则直接返回失败, 否则调用 lwIP 内部函数, 判断 DHCP 是否已拿到地址
 * @return true  已获取到有效地址, 网络可用
 *         false 仍在获取中或获取失败
*/
// static bool bt_mgr_dhcp_get_ip(void)
// {
//     if (netif_default == NULL)
//         return false;

//     return dhcp_supplied_address(netif_default) ? true : false;
// }

/**
 * @brief 设置蓝牙本地名称
 * @details 当 BT_NAME_MAC_ENABLE 定义时，将蓝牙本地名称设置为 name-XX:XX:XX:XX:XX:XX，
 *          其中 XX:XX:XX:XX:XX:XX 为蓝牙设备的 MAC 地址
 * @param name 蓝牙名称
 * @return rt_err_t 错误码，RT_EOK 表示成功，其他值表示失败
 */     
rt_err_t bt_mgr_set_local_name(const char *name)
{
#ifdef BT_NAME_MAC_ENABLE
    char local_name[32];
    bd_addr_t addr;
    ble_get_public_address(&addr);
    sprintf(local_name, "%s-%02x:%02x:%02x:%02x:%02x:%02x",
            name, addr.addr[0], addr.addr[1], addr.addr[2],
            addr.addr[3], addr.addr[4], addr.addr[5]);
#else
    const char *local_name = name;
#endif
    bt_interface_set_local_name(strlen(local_name), (void *)local_name);

    rt_kprintf("func: %s, bt %s.\r\n", __func__, local_name);

    return RT_EOK;
}
