/********************************** (C) COPYRIGHT *******************************
* File Name          : main.c
* Author             : WCH
* Version            : V1.0.0
* Date               : 2021/08/08
* Description        : Main program body.
*********************************************************************************
* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd.
* Attention: This software (modified or not) and binary are used for 
* microcontroller manufactured by Nanjing Qinheng Microelectronics.
*******************************************************************************/

/*
 *@Note
  This routine demonstrates the use of the USBD to emulate a custom device(CH372 like device),
  with endpoints 1/3 downlinking data and uploading it via endpoints 2/4 respectively
  where endpoint 1/2 is implemented via a ring buffer and data is not inverted,and endpoints
  3/4  is directly copied and inverted for upload
  The device can be operated using Bushund or other upper computer software.
*/
 
#include "debug.h"
#include "usb_lib.h"
#include "usb_desc.h"
#include "hw_config.h"
#include "usb_pwr.h"
#include "usb_prop.h"
#include "usb_conf.h"

/* Global define */
/* Global Variable */    
/*********************************************************************
 * @fn      main
 *
 * @brief   Main program.
 *
 * @return  none
 */
 
uint8_t  USB_Rx_Buffer[1000];
uint32_t USB_Rx_len = 0;

uint32_t ctr_call = 0; 
char cbuf[1024];
int main(void)
{   
	
	
	uint8_t ret;
	uint32_t len;
	unsigned long h;		
	ir.in = ir.out = 0;
	for(h=0;h<200000;h++){}	
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	SystemCoreClockUpdate();
	Delay_Init(); 
	USART_Printf_Init(115200);
	for(h=0;h<20000000;h++){}
	printf("SystemClk:%d\r\n",SystemCoreClock);
	printf( "ChipID:%08x\r\n", DBGMCU_GetCHIPID() );
	printf("USBD CH372 Device Demo\r\n");

	Set_USBConfig(); 
  USB_Init( PWR_VDD_SupplyVoltage() );	     
 	USB_Interrupts_Config();    
 	h = 0;

	 SetEPRxValid(ENDP2);
	while(1)
	{	

//		while(ir.in != ir.out){
//					 if(ir.wIstr[ir.out] != 0X200){
//							printf("intr = %08X\r\n",ir.wIstr[ir.out]);
//					 }
////					 if(ir.wIstr[ir.out] & 0X03){
////							len = USB_SIL_Read(ENDP2,cbuf);
////									if(len){
////									printf("recv data = %ld!\r\n",len);
////								}
////					 }
//					 ir.out = (ir.out + 1) % max_wIstr;
//				}
		
				if(USB_Rx_len){
					  printf("recv data = %ld!\r\n",USB_Rx_len);
					  USB_Rx_len = 0;
				}
				
	    if( bDeviceState == CONFIGURED )
	    {
//				len = USB_SIL_Read(ENDP2,cbuf);
//				if(len){
//					 printf("recv data = %ld!\r\n",len);
//				}
				if(++h > 600000){
					 h = 0;
				//	printf("ctr_call = %ld\r\n",ctr_call);
				//	USBD_ENDPx_DataUp(ENDP2,"AAA",3);
					
				}
				

				
			/* Data Transfer */
	        if(RingBuffer_Comm.RemainPack)
	        {printf("1");
	            ret = USBD_ENDPx_DataUp(ENDP2, &EP1_Data_Buffer[(RingBuffer_Comm.DealPtr) * DEF_USBD_MAX_PACK_SIZE], RingBuffer_Comm.PackLen[RingBuffer_Comm.DealPtr]);
	            if(ret == READY)
	            {
	                NVIC_DisableIRQ(USB_LP_CAN1_RX0_IRQn);
	                RingBuffer_Comm.RemainPack--;
	                NVIC_EnableIRQ(USB_LP_CAN1_RX0_IRQn);
	                RingBuffer_Comm.DealPtr++;
	                if(RingBuffer_Comm.DealPtr == DEF_Ring_Buffer_Max_Blks)
	                {
	                    RingBuffer_Comm.DealPtr = 0;
	                }
	            }
	        }

			/* Monitor whether the remaining space is available for further downloads */
	        if(RingBuffer_Comm.RemainPack < (DEF_Ring_Buffer_Max_Blks - DEF_RING_BUFFER_RESTART))
	        {
	            if(RingBuffer_Comm.StopFlag)
	            {
	                printf("USB ring buffer full, stop receiving further data.\n");
							    RingBuffer_Comm.StopFlag = 0;
									SetEPRxValid(ENDP1);
	            }
	        }
	    }
	}
}


void CTR_Callback(void)
{
		ctr_call++;
	 //printf("t\r\n");
	
}


void EP2_OUT_Callback(void)
{

        uint8_t i;
        //将EP2端点输入的缓存数据读取到USB_Rx_Buffer数组里面
        //当然这个可以自己定义一个数组变量，并返回接收数据的长度
        //USB_Rx_Cnt = USB_SIL_Read(EP2_OUT, USB_Rx_Buffer);
        //我们这里不需要
        USB_Rx_len = USB_SIL_Read(EP2_OUT, USB_Rx_Buffer);
    //接收到的数据取反
        //这里屏蔽
//    for(i=0;i<USB_Rx_Cnt;i++)
//        {
//                //USB_Rx_Buffer[i] = ~USB_Rx_Buffer[i];
//        }

        //添加动作控制
        //随意写的，数组前2为为11 开灯
        //12 关灯
//        if((USB_Rx_Buffer[0]==1)&&(USB_Rx_Buffer[1]==1))
//        {
//                PAout(0) = 1;
//                //更改回复
//                SetEPTxValid(ENDP2);
//                USB_SIL_Write(EP2_IN, "LEDOFF", sizeof( "LEDOFF"));
//                //Delay_Us(10);
//        }

//        if((USB_Rx_Buffer[0]==1)&&(USB_Rx_Buffer[1]==2))
//        {
//                PAout(0) = 0;
//                //更改回复
//                SetEPTxValid(ENDP2);
//                USB_SIL_Write(EP2_IN, "LEDON", sizeof( "LEDON"));
//                //Delay_Us(10);
//        }
        //随便回复一个OKMMM
        //使能发送
//        SetEPTxValid(ENDP2);
//    USB_SIL_Write(EP2_IN, "OKMMM", sizeof( "OKMMM"));
        //不用之前的输出程序
    //EP2_IN_Callback();
    //使能接收
        SetEPRxValid(ENDP2);
					USB_Rx_len = 1;
}



