/*
 *  usb_user.c
 *
 * Change Logs:
 * Date          Author      Notes
 * 2024-01-09    weijiac     user usb funcion  implementation routine
 */

#include "usb_common.h"
#include "hal_usbd.h"
#include "hal_usbd_init.h"
#include "hal_usbd_reg.h"
#include "usb_device.h"
#include "debug.h"

//#define usb_user_debug(fmt, ...)      debug(fmt, ##__VA_ARGS__)
#define usb_user_debug(fmt, ...)



void usb_init(void)
{
	usb_user_debug("usb_init \n\r");
    rt_usbd_device_list_init();
    usb_user_init();
    usb_update_init(USB_HS);
}



extern udevice_t _udevice;
void usb_user_init(void)
{
    //顺序不能改
    usb_device_init();
    usb_cfg_init(_udevice);
    //usb_function_init();
}




extern struct hal_usbd_ep_cb_struct hal_usbd_cb;



//
rt_err_t rt_usbd_ep_init(udevice_t device)
{
    //端点0 默认，不做修改
    int i = 1;
    uep_t ep;
    ufunction_t func;
    RT_ASSERT(device != RT_NULL);
    RT_ASSERT(device->dcd != RT_NULL);
    RT_ASSERT(device->dcd->ep_pool != RT_NULL);

    while (device->dcd->ep_pool[i].addr != 0xFF)
    {
        if (device->dcd->ep_pool[i].status == ID_UNASSIGNED)
        {
            i++;
            continue;
        }

        if (device->dcd->ep_pool[i].dir == USB_DIR_IN)
        {
            if (device->dcd->ep_ops->usb_ep_in_init != RT_NULL)
            {
                //debug("addr %d,type %d, USB_DIR_IN\n\r",device->dcd->ep_pool[i].addr,device->dcd->ep_pool[i].type);
                device->dcd->ep_ops->usb_ep_in_init(device->dcd->ep_pool[i].addr, device->dcd->ep_pool[i].type);
            }
        }
        else
        {
            if (device->dcd->ep_ops->usb_ep_out_init != RT_NULL)
            {
                //debug("addr %d, type %d,USB_DIR_OUT\n\r",device->dcd->ep_pool[i].addr,device->dcd->ep_pool[i].type);
                device->dcd->ep_ops->usb_ep_out_init(device->dcd->ep_pool[i].addr, device->dcd->ep_pool[i].type);
            }
        }

        ep = rt_usbd_find_endpoint(device, &func, device->dcd->ep_pool[i].addr);
        if (ep != RT_NULL)
        {
            if (ep->handler != RT_NULL)
            {
                hal_usbd_cb_register(i, ep->handler, (void *) NULL);
            }
        }
        else
        {
        	usb_user_debug("in rt_usbd_ep_init ,ep == RT_NULL\n\r");
        }

        i++;
    }

    return RT_EOK;
}
