#include "usb_printer_demo.h"
#include "usb_printer_desc.h"

#if USB_DEVICE_TYPE & BIT(4)

#define BUF_LEN     50
u8 usb_send_buf[BUF_LEN];
u8 usb_send_busy = 0;

#define USER_DATA_MAX_LEN   233
u8 user_data[USER_DATA_MAX_LEN];
u8 user_data_len;
u8 *user_data_p;

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)
{
    u8 i;
    gpio_init_typedef gpio_init_structure;

    gpio_init_structure.gpio_pin = GPIO_PIN_5;
    gpio_init_structure.gpio_dir = GPIO_DIR_INPUT;
    gpio_init_structure.gpio_fen = GPIO_FEN_GPIO;
    gpio_init_structure.gpio_mode = GPIO_MODE_DIGITAL;
    gpio_init_structure.gpio_pupd = GPIO_PUPD_UP;
    gpio_init(GPIOB_REG, &gpio_init_structure);

    for (i = 0; i < BUF_LEN; i++) {
        usb_send_buf[i] = i;
    }

    for (i = 0; i < USER_DATA_MAX_LEN; i++) {
        user_data[i] = i;
    }
    user_data_len = i;
    user_data_p = user_data;

    usb_printer_ep_config(USB_DEV_OUT_EP, USB_DEV_IN_EP);
}

void usb_event_process(void)
{
    u8 len;
    static u8 key_down_en = 1;
    static u8 key_cnt = 0;

    if (gpio_read_bit(GPIOB_REG, GPIO_PIN_5) == RESET) {
        key_cnt++;
        delay_ms(1);
        if (key_cnt >= 10) {
            key_cnt = 0;
            if (key_down_en) {
                key_down_en = 0;

                if (usb_send_busy) {
                    printf("usb send busy!!!\n");
                    return;
                }

                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.
                usb_send_busy = 1;
            }
        }
    } else {
        key_down_en = 1;
        key_cnt = 0;
    }
}

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);
        usb_send_busy = 0;
    }
}

AT(.com_text.isr)
void bulk_rx_handler(u8 *buf, u8 len)
{
    printf(rx_tip, len);
    print_r(buf, len);
    ude_rx_ack();
}

#endif // USB_DEVICE_TYPE & BIT(4)
