#include "usb_keyboard_demo.h"
#include "usb_hid_desc.h"

#if 1//USB_DEVICE_TYPE & BIT(2)

#define BUF_LEN     8
u8 key_buf[BUF_LEN];

void usb_insert_callback(void)
{
    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);

    usb_hid_ep_config(HID_IN_EP);
    usb_user_ep_config(2, 0, 1);
}

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

    if (gpio_read_bit(GPIOB_REG, GPIO_PIN_5) == RESET) {
        if (last_key_status == 0) {
            key_cnt = 0;
        } else {
            key_cnt++;
            if (key_cnt >= 10) {
                last_key_status = 0;

                key_buf[2] = 0x04;
                usb_device_hid_send(key_buf, 8);
                printf("send key buf[%d]: ", sizeof(key_buf));
                print_r(key_buf, sizeof(key_buf));
            }
        }
    } else {
        if (last_key_status == 1) {
            key_cnt = 0;
        } else {
            key_cnt++;
            if (key_cnt >= 10) {
                last_key_status = 1;

                memset(key_buf, 0, 8);
                usb_device_hid_send(key_buf, 8);
                printf("send key buf[%d]: ", sizeof(key_buf));
                print_r(key_buf, sizeof(key_buf));
            }
        }
    }
}

AT(.com_rodata.isr_text)
char tip_rx[] = "usb user ep receive[%d]: \n";

AT(.com_text.isr_callback)
void usb_user_ep_rx_handler(u8 *buf, u8 len)
{
    printf(tip_rx);
    print_r(buf, len);
    usb_user_ep_rx_ack();
}

#endif // USB_DEVICE_TYPE & BIT(2)
