#include "usart0.h"
#include <ctype.h>
#include "Systick.h"
#include "main.h"


uint8_t  U1_RxBuff[RXBUFFLENGTH];
uint16_t U1_Rxlen = 0;
uint16_t U1_RxlencntPre = 0;

static volatile bool uart_send_complete_flag = false;



RINGBUF RX_BUF;
uint8_t rx_buffer[BUF_SIZE];
uint8_t tempRX;


void UART0_Init(void)
{	
	fsp_err_t err = FSP_SUCCESS;
	
	err = R_SCI_UART_Open(&g_uart0_ctrl,&g_uart0_cfg);
	
	assert(err == FSP_SUCCESS);
	
	RINGBUF_Init(&RX_BUF, rx_buffer, BUF_SIZE);
}


void uart0_Send_Byte(uint8_t ch)
{
    /* 发送一个字节数据到UART */
    R_SCI_UART_Write(g_uart0.p_ctrl, (uint8_t *)&ch, 1);

    /* 等待发送完毕 */
    while(uart_send_complete_flag == false);
    uart_send_complete_flag = false;
}

void uart0_Send_Bytes(uint8_t *data, uint32_t len)
{
    /* 发送一个字节数据到UART */
    R_SCI_UART_Write(g_uart0.p_ctrl, data, len);

    /* 等待发送完毕 */
    while(uart_send_complete_flag == false);
    uart_send_complete_flag = false;
}

void uart0_Send_String_Length(uint8_t *str,uint32_t strlen)
{
    unsigned int k=0;
    do 
    {
        uart0_Send_Byte (*(str + k));
        k++;
    } while(k < strlen);
}


void uart9_Send_String(uint8_t *str)
{
    unsigned int k=0;
    do 
    {
        uart0_Send_Byte (*(str + k));
        k++;
    } while(*(str + k)!='\0');
}



void user_uart_clear(void)
{

	memset(U1_RxBuff, 0, sizeof(U1_RxBuff));
	U1_Rxlen = 0;

}


uint8_t user_uart_wait_receive(void)
{

	if(U1_Rxlen == 0) 							//如果接收计数为0 则说明没有处于接收数据中，所以直接跳出，结束函数
		return REV_WAIT;
		
	if(U1_Rxlen == U1_RxlencntPre)				//如果上一次的值和这次相同，则说明接收完毕
	{
		U1_Rxlen = 0;							//清0接收计数
			
		return REV_OK;								//返回接收完成标志
	}
		
	U1_RxlencntPre = U1_Rxlen;					//置为相同
	
	return REV_WAIT;								//返回接收未完成标志

}








void uart0_callback (uart_callback_args_t * p_args)
{
    if(p_args->event == UART_EVENT_TX_COMPLETE)
    {
        uart_send_complete_flag = true;
    }
    if(p_args->event == UART_EVENT_RX_CHAR)
    {
		tempRX = (uint8_t)p_args->data;
		RINGBUF_Put(&RX_BUF, tempRX);
    }
}




void SysTick_Handler(void)
{
  g_tick_count++;
 
  /* USER CODE END SysTick_IRQn 1 */
}



#if 1
/* 重定向 printf 输出 */
#if defined __GNUC__ && !defined __clang__
int _write(int fd, char *pBuffer, int size); //防止编译警告
int _write(int fd, char *pBuffer, int size)
{
	(void)fd;
	R_SCI_UART_Write(&g_uart0_ctrl, (uint8_t *)pBuffer, (uint32_t)size);
	while(uart_send_complete_flag == false);
	uart_send_complete_flag = false;
	return size;
}
#else
int fputc(int ch, FILE *f)
{
	(void)f;
	R_SCI_UART_Write(&g_uart0_ctrl, (uint8_t *)&ch, 1);
	while(uart_send_complete_flag == false);
	uart_send_complete_flag = false;
	return ch;
}
#endif
#endif

