#include "include.h"
#include "api.h"

#if BT_SPP_EN

#define SPP_MTU_SIZE        512     //max=666

//----------------------------------------------------------------------------
// SPP TX memory pool
//----------------------------------------------------------------------------
#define SPP_TX_BUF_INX      8
#define SPP_POOL_SIZE       (SPP_MTU_SIZE + sizeof(struct txbuf_tag)) * SPP_TX_BUF_INX

AT(.spp_tx_buff.spp_tx_pool)
uint8_t spp_tx_pool[SPP_POOL_SIZE];

void spp_txpkt_init(void)
{
    txpkt_init(&spp_tx, spp_tx_pool, SPP_TX_BUF_INX, SPP_MTU_SIZE);
    spp_tx.send_kick = spp_send_kick;
}

//----------------------------------------------------------------------------
// SPP RX buffer and flow control
//----------------------------------------------------------------------------
#if BT_SPP_RX_FLOW_CTRL_EN
#define SPP_RX_BUFF_LEN     2048
u16 spp_rxpkt_init(void)
{
    //do something about rx buffer initial and return rx buffer length
    return SPP_RX_BUFF_LEN;
}
#endif // BT_SPP_RX_FLOW_CTRL_EN

//----------------------------------------------------------------------------
// SPP process function
//----------------------------------------------------------------------------
void bsp_spp_process(void)
{

}

//----------------------------------------------------------------------------
// SPP callback function
//----------------------------------------------------------------------------
u16 get_spp_mtu_size(void)
{
    return SPP_MTU_SIZE;
}

void spp_connect_callback(void)
{
    printf("--->spp_connect_callback\n");
#if BT_SPP_FOT_EN
    fot_spp_connect_callback();
#endif // BT_SPP_FOT_EN
}

void spp_disconnect_callback(void)
{
    printf("--->spp_disconnect_callback\n");
#if BT_SPP_FOT_EN
    fot_spp_disconnect_callback();
#endif // BT_SPP_FOT_EN
}

/**流控开始标志位**/
u8 BtFlowControl_start=0;    //流控开始标志位
/******************/
/**流控计数**/
u8 SPP_CreditCount=0;
/*************/
/**蓝牙转串口例程宏定义**/
#define BT_Huart 0  //如果是其它例程就给0，蓝牙转串口给1
/*************/


void spp_rx_callback(uint8_t *packet, uint16_t size)
{
#if BT_SPP_FOT_EN
    if(fot_app_connect_auth(packet, size))
    {
        fot_recv_proc(packet,size);
        spp_set_rx_new_credit(1);
        return;
    }
#endif // BT_SPP_FOT_EN

#if BT_Huart == 1
/**蓝牙数据直接发送给串口，串口收发流控**/
    hsuart_dma_start(HSUT_TRANSMIT, (uint32_t)packet, size);
#else
//    printf("SPP_rec:[%x]%x %x...%x\n",size,packet[0],packet[1],packet[size-1]);        /*Test serial port*/
    print_r(packet, size);
#endif

    /**流控判断**/
    if(gpio_read_bit(GPIOB_REG, GPIO_PIN_5) == SET )     //流控-置高-忙
    {
        SPP_CreditCount++;
        BtFlowControl_start = 1;
        printf("BTFlowsControl_Stop :%d,%d\n",SPP_CreditCount,size);
    }
    else if(gpio_read_bit(GPIOB_REG, GPIO_PIN_5) == RESET )   //流控-置低-不忙
    {
        BtFlowControl_start = 0;
        spp_set_rx_new_credit(1);
    }
}

#endif // BT_SPP_EN
