#include "pipe.h"

#if DEBUG == Debug_USB
Pipe_t debug_pipe;
#endif

Pipe_t sys_pipe;
Pipe_t coor_pipe;
Pipe_t uart_cmd_pipe;
extern UINT8 print_log;
void pipe_init(Pipe_t *pipe)
{
	pipe->tail = pipe->header = 0;
}

UINT8 pipe_read(Pipe_t *pipe, UINT8 * value, UINT8 len)
{
    //NVIC_DisableIRQ( USBFS_IRQn );
	UINT8 cnt = 0;
	do
	{
		if(pipe->tail==pipe->header)
		{
			break;
		}
		
		value[cnt++] = pipe->buf[pipe->tail];
		
		pipe->tail = (pipe->tail+1)&OFFSET_MASK;//%BUF_MAX;
	
	}while(--len);
	
	//NVIC_EnableIRQ( USBFS_IRQn );
	
	return cnt;
}

void pipe_write_c(Pipe_t *pipe, UINT8 value) 
{	
    //NVIC_DisableIRQ( USBFS_IRQn );
	pipe->buf[pipe->header] = value;
	
	pipe->header = (pipe->header+1)&OFFSET_MASK;//%BUF_MAX;
	
	if(pipe->tail==pipe->header)
	{
		pipe->tail = (pipe->tail+1)&OFFSET_MASK;//%BUF_MAX;
	}
	//NVIC_EnableIRQ( USBFS_IRQn );
}

void pipe_write(Pipe_t *pipe, UINT8* value, UINT8 len)
{
  UINT8 cnt = 0;

  //NVIC_DisableIRQ( USBFS_IRQn );

  UINT16 res = pipe->tail <= pipe->header ? pipe->tail + BUF_MAX - pipe->header : pipe->tail -  pipe->header;
  if(res < len)
  {
      //NVIC_EnableIRQ( USBFS_IRQn );
    return;
  }

  while(cnt < len)
  {
    pipe->buf[pipe->header] = value[cnt++];

    pipe->header = (pipe->header+1)&OFFSET_MASK;//%BUF_MAX;
  }
  //NVIC_EnableIRQ( USBFS_IRQn );
}


//void pipe_write_t(Pipe_t *pipe, UINT8* value, UINT8 len, COMMAND_TYPE cmd)
//{
//    NVIC_DisableIRQ( USBFS_IRQn );
//	UINT8 cnt = 0;
//
//	UINT16 res = pipe->tail <= pipe->header ? pipe->tail + BUF_MAX - pipe->header : pipe->tail -  pipe->header;
//	if(res < len+2)
//	{
//	    NVIC_EnableIRQ( USBFS_IRQn );
//		return;
//	}
//
//	pipe_write_c(pipe, len);
//
//	pipe_write_c(pipe, cmd);
//
//	while(cnt < len)
//	{
//		pipe->buf[pipe->header] = value[cnt++];
//
//		pipe->header = (pipe->header+1)&OFFSET_MASK;//%BUF_MAX;
//	}
//	NVIC_EnableIRQ( USBFS_IRQn );
//}



