#include "HW_Config.h"
#include "usbd_cdc_if.h"
#include "task.h"
#include "CnCpp.h"

#define USB_CDC_HEAD 	0xD7
#define USB_CDC_END 	0xEE

T_usb_cdc_data_struct usb_cdc_data;

void usccdc_config_app_handle(void);

void usb_cdc_rx_data(unsigned char *buf, unsigned int len)
{
	unsigned int i;
	
	if((len < 7)||(len > USB_CDC_BUF_MAX))return;
	
	usb_cdc_data.rx_len = len;
	for(i=0;i<len;i++){
		usb_cdc_data.rx_buf[i] = buf[i];
	}
	
	if((USB_CDC_HEAD == usb_cdc_data.rx_buf[0]) && (USB_CDC_END == usb_cdc_data.rx_buf[len-1])){
		if(!check_crc(usb_cdc_data.rx_buf,(len-1))){
			usb_cdc_data.rx_complete = 1;
		}
	}
}

void usb_cdc_rx_handle(void)
{
	unsigned int len = 0;
	
	if(usb_cdc_data.rx_complete){
		usb_cdc_data.rx_complete = 0;
		
		if(usb_cdc_data.rx_buf[1] > 0x80){
			len = usb_cdc_data.rx_buf[3];
			len<<=8;
			len |= usb_cdc_data.rx_buf[2];
			len +=7;
			if(len == usb_cdc_data.rx_len){
				;//gbk
			}
		}else{
			if((usb_cdc_data.rx_buf[3] + 7) == usb_cdc_data.rx_len){
				usccdc_config_app_handle();//cfg
			}
		}
	}
}

void usb_cdc_tx(unsigned char * pdata, unsigned int len)
{
	unsigned int i = 0;
	unsigned short crc_value = 0;
	
	for(i=0;i<len;i++){
		usb_cdc_data.tx_buf[i] = pdata[i];
	}
	
	crc_value = crc16_data(usb_cdc_data.tx_buf, len);
	usb_cdc_data.tx_buf[len] = (crc_value&0xFF);
	usb_cdc_data.tx_buf[len+1] = ((crc_value&0xFF00)>>8);
	
	usb_cdc_data.tx_buf[len+2] = USB_CDC_END;
	usb_cdc_data.tx_len = len+3;
	
	CDC_Transmit_FS(usb_cdc_data.tx_buf, usb_cdc_data.tx_len);
}

void usccdc_config_app_handle(void)
{
	GetCfgViaUsbCdcRx();
}
