#include "usb_cdc_uart_demo.h"
#include "usb_cdc_uart_desc.h"

#if USB_DEVICE_TYPE & BIT(4)

/**USB send buff**/
#define BUF_LEN     50
u8 usb_send_buf[BUF_LEN];
/****************/

/**Custom send data**/
#define USER_DATA_MAX_LEN   255
u8 user_data[USER_DATA_MAX_LEN];
u8 user_data_len;
u8 *user_data_p;

u8 usb_send_flag = 0;
/*******************/

AT(.com_rodata.const_str)
const char tx_tip[] = "---> tx finished!\n";

AT(.com_rodata.const_str)
const char rx_tip[] = "---> rx_buf[%d]: \n";

AT(.com_rodata.const_str)
const char tx_show_buf_tip[] = "senf_buf[%d]:\n";

void usb_insert_callback(void)  //usb initialize
{
    for (u8 i = 0; i < USER_DATA_MAX_LEN; i++) {
        user_data[i] = i;
    }
    user_data_p = user_data;
    usb_printer_ep_config(USB_DEV_OUT_EP, USB_DEV_IN_EP);
}

/**usb sends rely on bulk_tx_handler, which is in the main loop but is called only once during the send**/
void usb_event_process(void)
{
    u8 len;
    if (usb_send_flag == 1)
    {
        usb_send_flag = 0;
        user_data_len = USER_DATA_MAX_LEN;
        user_data_p = user_data;

        len = (user_data_len < BUF_LEN) ? user_data_len: BUF_LEN;
        memcpy(usb_send_buf, user_data_p, len);
        user_data_len -= len;
        user_data_p += len;

        printf(tx_show_buf_tip, len);
        print_r(usb_send_buf, len);

        // kick send usb data.
        usb_bulk_send(usb_send_buf, len, 1);        // Blocking time 1ms.
    }

}

/**send data**/
AT(.com_text.isr)
void bulk_tx_handler(void)
{
    u8 len;
    if (user_data_len) {
        len = (user_data_len < BUF_LEN) ? user_data_len: BUF_LEN;
        memcpy(usb_send_buf, user_data_p, len);
        user_data_len -= len;
        user_data_p += len;

        printf(tx_show_buf_tip, len);
        print_r(usb_send_buf, len);

        usb_bulk_send(usb_send_buf, len, 1);        // Blocking time 1ms.
    } else {
        printf(tx_tip);
    }
}

AT(.com_text.isr)
void bulk_rx_handler(u8 *buf, u8 len)
{
    printf(rx_tip, len);
    print_r(buf, len);
    usb_bulk_send(buf, len, 1);        // Blocking time 1ms.
    if(buf[0] == 0x13 && buf[1] ==0x4b)
    {
        usb_send_flag = 1;
    }
    ude_rx_ack();
}

#endif // USB_DEVICE_TYPE & BIT(4)
