#include "omw_config.h"
#include "omw_dbg.h"
#include "omw_uart.h"
#include "periph_gpio.h"
#include "periph_uart.h"

volatile int i,tcnt, rcnt;
volatile uint8_t rxd, rbuf[256];

ATTRIBUTE_ISR void UART1_Handler(void)
{
    if(UART_GetITStatus(UART1,UART_IT_FLAG_RECEIVED_AVAILABLE)!=0)
	{
		tcnt = 0;
		while(UART_GetLineStatus(UART1, UART_LINE_FLAG_DR) != 0)
        {
            rxd = (uint8_t)(UART_ReceiveData(UART1));
            if (rcnt < 256)
            {
                rbuf[rcnt] = rxd; // store data
            }
            rcnt++;
        }
	}
}

int main()
{
    omw_set_irq_prio(UART1_IRQn,3);
	omw_enable_irq(UART1_IRQn);

    GPIO_InitTypeDef GPIO_InitStruct;
    UART_InitTypeDef UART_InitStruct;

    // init
    tcnt = 0;
    rcnt = 0;
	i = 0;
	for(i=0;i<256;i++)
	{
		rbuf[i]=0xFF;
	}
    omw_dbg_init();
    printf("UART test ...\n");
    
    // UART1 configuration
    UART_DeInit(UART1);
    UART_StructInit(&UART_InitStruct);
    UART_InitStruct.UART_BaudRate = UART_BAUDRATE_115200;
    UART_InitStruct.UART_WordLength = UART_WORD_LENGTH_8BIT;
    UART_InitStruct.UART_StopBits = UART_STOPBITS_1BIT;
    UART_InitStruct.UART_Parity = UART_PARITY_NONE;
    UART_Init(UART1, &UART_InitStruct);
	
    // FIFO configuration
    // RX 1 char trigger recv data valid
    // TX half-full trigger transmit empty
    UART_FIFOTrigConfig(UART1, UART_RX_FIFO_QUARTER_FULL, UART_TX_FIFO_HALF_FULL);
	UART_ITConfig(UART1,UART_IT_RXF,ENABLE);
    // UART1 GPIO configuration, GPIO[6] RXD, GPIO[7]: TXD
    GPIO_StructInit(&GPIO_InitStruct);
    GPIO_InitStruct.GPIO_Pin = GPIO_PIN_6;
    GPIO_InitStruct.GPIO_Mode = GPIO_MODE_IPU;
    GPIO_InitStruct.GPIO_AltFunc = OMW_GPIO6_UART1_RX;
    GPIO_Init(&GPIO_InitStruct);
    GPIO_InitStruct.GPIO_Pin = GPIO_PIN_7;
    GPIO_InitStruct.GPIO_Mode = GPIO_MODE_IN_FLOATING;
    GPIO_InitStruct.GPIO_AltFunc = OMW_GPIO7_UART1_TX;
    GPIO_Init(&GPIO_InitStruct);

    printf("  UART0\n");
    printf("    TXD: GPIO21\n");
    printf("    Baudrate: 115200\n");
    printf("    Function: UART0 used by printf, display UART1 RXD data\n");
    printf("  UART1\n");
    printf("    RXD: GPIO6\n");
    printf("    TXD: GPIO7\n");
    printf("    Baudrate: 115200\n");
    printf("    Function: UART1 RXD receive uart data and send to UART1 TXD\n");

    // loop
    while(1){
		tcnt++;
		if(tcnt == 2000*20) // wait about 20ms
		{
			tcnt = 0;
			if (rcnt != 0)
			{
				printf("  -> UART1 RX cnt: %d, content: ", rcnt); // print at most 12 bytes
				for (i = 0; i < rcnt; i++)
				{
					if (i < 12)
					{
//						printf("0x%02x ", rbuf[i]);
						UART_SendData(UART1, rbuf[i]);
					}
//					else
//					{
//						break;
//					}
				}
                    printf("\n");
                    rcnt = 0;
			}
		}

    }
    
    while(1);
    return 0;
}
