#include "include.h"
#include "ble_user_service.h"
#include "ble_hid_service.h"
#include "ble_fota_service.h"
#include "wireless_service.h"
#include "fota_proc.h"


#define BLE_ADV_SLEEP_INTERVAL    800   //500ms
#define BLE_CON_SLEEP_INTERVAL    400   //500ms
#define BLE_CON_SLEEP_LATENCY     0
#define BLE_CON_SLEEP_TIMEOUT     1000   //10s


static struct ble_param_t {
    uint16_t adv_interval;
    uint16_t conn_interval;
    uint16_t conn_latency;
    uint16_t conn_timeout;
} ble_param;


static void ble_update_param_before_enter_sleep(void)
{
    if (ble_cb.con_hanle) {
        ble_enable_latency(ble_cb.con_hanle);
    } else {
        ble_get_adv_interval(&ble_param.adv_interval);
        ble_set_adv_interval(BLE_ADV_SLEEP_INTERVAL);
    }
}

static void ble_update_param_after_exit_sleep(void)
{
    if (ble_cb.con_hanle) {
        ble_disable_latency(ble_cb.con_hanle);
    } else {
        ble_set_adv_interval(ble_param.adv_interval);
    }
}

void ble_enter_sleep_proc(void)
{
    if (func_cb.sta == FUNC_BT) {
        ble_update_param_before_enter_sleep();
    } else if (func_cb.sta == FUNC_WIRELESS) {
        wireless_enter_sleep_hook();
    }
}

void ble_exit_sleep_proc(void)
{
    if (func_cb.sta == FUNC_BT) {
        ble_update_param_after_exit_sleep();
    } else if (func_cb.sta == FUNC_WIRELESS) {
        wireless_exit_sleep_hook();
    }
}

AT(.text.app.proc.ble)
void ble_app_proc(void)
{
    ble_user_service_proc();
#if USB_EN
    ble_hid_service_proc();
#endif // USB_EN
}

AT(.com_sleep.ble.sleep)
bool ble_proc_pending(void)
{
    bool res = false;

#if (AB_FOT_CHANNEL & AB_FOT_CHANNEL_BLE)
    res = fota_is_start();
#endif

    if(!res){
        res = ble_user_service_pending();
    }

    return res;
}
