#include "include.h"
#include "ble_init.h"
#include "ble_client.h"

void ble_txpkt_init(void);
void ble_init_att(void);

#if LE_ROLE_MASTER

void btstack_ble_init_callback(void)
{
#if LE_PAIR_EN
    le_sm_init(1, 3, 5);
#else
    le_sm_init(0, 3, 0);
#endif // LE_PAIR_EN

    ble_txpkt_init();
    gap_random_address_set_mode(GAP_RANDOM_ADDRESS_TYPE_OFF);
    ble_gatts_init();
    att_server_init(ble_get_profile_data());
    gatt_client_init();
    ble_client_init();
    ble_set_scan_param(1, 100, 50);     // SCAN: type(8bits)  interval(16bits)  window(16bits)
    ble_scan_en();
}

void ble_init_register(void)
{
    ble_init_callback_register(btstack_ble_init_callback);
}

#else // !LE_ROLE_MASTER

WEAK u32 ble_get_scan_data(u8 *scan_buf, u32 buf_size)
{
    return 0;
}

WEAK u32 ble_get_adv_data(u8 *adv_buf, u32 buf_size)
{
    return 0;
}

static void le_adv_param_init(void)
{
    adv_param_t param;

    memset((u8 *)&param, 0, sizeof(param));

    param.adv_en = 1;
    param.adv_type = ADV_TYPE_IND;
    param.adv_len = ble_get_adv_data(param.adv_data, sizeof(param.adv_data));
    param.scan_rsp_len = ble_get_scan_data(param.scan_rsp, sizeof(param.scan_rsp));
    param.adv_int_min = param.adv_int_max = 0x030;      // Unit: 625us, set value to 0x030 means expected interval is 30ms
    ble_set_adv_params(&param);
}

void btstack_ble_init_callback(void)
{
#if LE_PAIR_EN
    le_sm_init(1, 3, 5);
#else
    le_sm_init(0, 3, 0);
#endif // LE_PAIR_EN

    ble_txpkt_init();
    gap_random_address_set_mode(GAP_RANDOM_ADDRESS_TYPE_OFF);
    le_adv_param_init();
    ble_init_att();
    att_server_init(ble_get_profile_data());
}

void ble_init_register(void)
{
    ble_init_callback_register(btstack_ble_init_callback);
}

#endif // LE_ROLE_MASTER
