/**
 * \file    sys_uart1.c
 * \brief   UART1 handler
 * 
 * \par     Copyright (c) 2018 UWE Technologies Corp., Ltd. All Rights Reserved.
 * \author  James
 * \date    2018-08-01
 * \version 
 * 
 * \history 
 *  Date        Note
 *  2018-08-01  Original Creation
 * 
 */

#include "libc.h"
#include "drivers.h"
#include "sys_uart1.h"
#include "sys_config.h"

#if (!UART1_TEST_ENABLED)  /* modified by James Gan - 2018-08-09 */
/** UART1 buffer for tx data */
volatile u8_t uart1_tx_data[SYS_UART1_BUFFER_SIZE];
/** Length of UART1 tx data */
volatile u8_t uart1_tx_data_len = 0;
/** Index of UART1 tx data */
volatile u8_t uart1_tx_data_index = 0;

/** UART1 buffer for data received */
volatile u8_t uart1_rx_data[SYS_UART1_BUFFER_SIZE];
/** Length of UART1 receive data */
volatile u8_t uart1_rx_data_len = 0;
/** Index of UART1 receive data */
volatile u8_t uart1_rx_data_index = 0;
sys_tick_t uart1_rx_start_time = 0;
#endif /* #if (!UART1_TEST_ENABLED) */

volatile u8_t g_uart1_loopback_en = 0;


void sys_uart1_handler(u8_t input)
{
#if (!UART1_TEST_ENABLED)  /* modified by James Gan - 2018-08-09 */
    uart1_rx_data_len++;
    if (uart1_rx_data_len > SYS_UART1_BUFFER_SIZE)
    {
        goto rx_reset;
    }

    uart1_rx_data[uart1_rx_data_index++] = input;
    
    if (uart1_rx_data_len >= 2)
    {
        u16_t cmd = *(u16_t *)(&uart1_rx_data[0]);
        // invalid command checking
        if (cmd)
        {
            // init tx buffer
            uart1_tx_data_index = 0;
            uart1_tx_data_len = 0;
            // parsing cmd
            switch (cmd)
            {
                default:
                    break;
            }
//data_send:
            for (int i = 0; i < uart1_tx_data_len; i++)
                drv_uart1_putbyte(uart1_tx_data[i]);
            goto rx_reset;
        }

        if (!uart1_rx_start_time)
            uart1_rx_start_time = now();

        if ((uart1_rx_start_time) && 
            (u32_t)(now() > uart1_rx_start_time) && 
            ((u32_t)(now() - uart1_rx_start_time) > SYS_UART1_TIMEOUT))
        {
            goto rx_reset;
        }
    }
    return;

rx_reset:
    uart1_rx_data_index = 0;
    uart1_rx_data_len = 0;
    uart1_rx_start_time = 0;
#else
    if (sys_uart1_loopback_get())
        drv_uart1_putbyte(input);
#if CLI_ENABLED
    if (sys_cfg_dbg_get())
    {
        drv_uart_puthex8(input);
    }
#endif /* CLI_ENABLED */
#endif /* #if (!UART1_TEST_ENABLED) */
}

