#include "uart_interface.h"
#include <uart4.h>

uart_type uart_msg = {
    .rx_count_u8        = 0,
    .tx_count_u8        = 0,
    .rx_finished_flg    = 0,
    .disconnect_flg     = 0,
    .rx_over_time       = 5,
    .rx_over_time_count = 0xFF,
    .disconnect_count   = 0,
};

void uart_rx_ticks(void)
{
    if (uart_msg.rx_over_time_count != 0xFF)
    {
        if (++uart_msg.rx_over_time_count >= uart_msg.rx_over_time)
        {
            uart_msg.rx_over_time_count = 0xFF;
            uart_msg.rx_finished_flg    = 1;
        }
    }

    if (uart_msg.disconnect_count != 0xFFFF)
    {
        if (++uart_msg.disconnect_count >= 2500) // 5000ms
        {
            uart_msg.disconnect_count = 0xFFFF;
            uart_msg.disconnect_flg   = 1;
        }
    }
}

void uart_start_send(uart_type *p_msg)
{
    p_msg->tx_count_u8 = 0;

    UART_RXNE_IT_DISABLE();
    USART_SendData(UART4, p_msg->tx[p_msg->tx_count_u8++]);
    UART_TXE_IT_ENABLE();
}

void uart4_it(void)
{
    // 接收中断处理
    if (RESET != USART_GetITStatus(UART4, USART_IT_RXNE))
    {
        USART_ClearITPendingBit(UART4, USART_IT_RXNE);

        uart_msg.rx_over_time_count = 0;
        uart_msg.disconnect_count   = 0;
        uart_msg.disconnect_flg     = 0;

        if (uart_msg.rx_count_u8 >= RX_TX_BUF_LEN)
        {
            uart_msg.rx_count_u8 = 0;
        }

        uart_msg.rx[uart_msg.rx_count_u8++] = USART_ReceiveData(UART4);
    }

    // 发送中断处理
    if (RESET != USART_GetITStatus(UART4, USART_IT_TXE))
    {
        USART_ClearITPendingBit(UART4, USART_IT_TXE);

        USART_SendData(UART4, uart_msg.tx[uart_msg.tx_count_u8++]);

        if (uart_msg.tx_count_u8 >= uart_msg.tx_len)
        {
            USART_ITConfig(UART4, USART_IT_TXE, DISABLE);
            USART_ITConfig(UART4, USART_IT_TC, ENABLE);
        }
    }

    // 发送完成中断
    if (RESET != USART_GetITStatus(UART4, USART_IT_TC))
    {
        USART_ClearITPendingBit(UART4, USART_IT_TC);

        USART_ITConfig(UART4, USART_IT_TC, DISABLE);
        USART_ITConfig(UART4, USART_IT_RXNE, ENABLE);
    }

    // 发送错误
    if (RESET != USART_GetITStatus(UART4, USART_IT_ORE))
        USART_ClearITPendingBit(UART4, USART_IT_ORE);
}
