#include "include.h"
#include "wireless_client.h"
#include "wireless_service.h"

// #define WIRELESS_ADV_DATA_GET(buf, size)                ble_get_adv_data(buf, size)
#define WIRELESS_ADV_DATA_GET(buf, size)                wireless_get_adv_data(buf, size)

static const uint8_t adv_match_seq[4] = {0x03, 0xff, 0x42, 0x06};
BT_WORK_MODE cfg_bt_work_mode            = MODE_NORMAL;


void ble_set_work_mode(BT_WORK_MODE mode)
{
    cfg_bt_work_mode = mode;
}

BT_WORK_MODE ble_get_work_mode(void)
{
    return cfg_bt_work_mode;
}

static uint8_t wireless_get_adv_data(uint8_t *buf, uint8_t size)
{
    uint8_t len = sizeof(adv_match_seq);

    if (len <= size) {
        memset(buf, 0x00, size);
        memcpy(buf, adv_match_seq, len);
        return len;
    } else {
        return 0;
    }
}

void bsp_wireless_init(void)
{
#ifdef wireless_setup
    wireless_setup();
#else
    wireless_setup_param_t param;
    memset(&param, 0x00, sizeof(param));
    param.conn_nb_support = 1;
    param.conn_phy_forced = 2;
    wireless_setup(&param);
#endif

    if (bTransmitEn)  //transmitting set
    {
        wireless_client_init();
        wireless_scan_param_set(1, 10, 50);
        wireless_scan_ctrl(true);
    }
    else
    {
        wireless_service_init();
        /* ADV Initialize */
        wireless_adv_init(true);
    }
}

void bsp_wireless_link_info_write(wireless_addr_info_typedef *addr_info)
{
    bsp_param_write((u8 *)addr_info, PARAM_WL_ADDR_INFO, PARAM_WL_ADDR_INFO_LEN);
    bsp_param_sync();
}

bool bsp_wireless_link_info_read(wireless_addr_info_typedef *addr_info)
{
    u8 buf[7] = {0};
    bsp_param_read((u8 *)addr_info, PARAM_WL_ADDR_INFO, PARAM_WL_ADDR_INFO_LEN);
    return (0 != memcmp(buf, (u8 *)addr_info, 7));
}
void wireless_adv_init(bool adv_en)
{
    printf("[slave]wireless_adv_init\n");
    wireless_addr_info_typedef wireless_addr_info;
    wireless_adv_param_t wireless_adv_param;

    memset(&wireless_adv_param, 0x00, sizeof(wireless_adv_param));
    wireless_adv_param.intv = 0x30;
    wireless_adv_param.data_len = WIRELESS_ADV_DATA_GET(wireless_adv_param.data_buf, sizeof(wireless_adv_param.data_buf));

    if (bsp_wireless_link_info_read(&wireless_addr_info)) {
        wireless_adv_param.adv_type = ADV_TYPE_DIRECT_LO_IND;
        wireless_adv_param.peer_addr_type = wireless_addr_info.address_type;
        memcpy(wireless_adv_param.peer_addr, wireless_addr_info.addr, 6);
        printf("direct - tyep: %d addr: ", wireless_addr_info.address_type);
        print_r(wireless_addr_info.addr, 6);
    } else {
        wireless_adv_param.adv_type = ADV_TYPE_IND;
    }

    wireless_adv_param_set(wireless_adv_param);

    if (adv_en) {
        wireless_adv_ctrl(true);
        printf("[slave] wireless adv start\n");
    }
}
