#include "uart_log.h"

UART_HandleTypeDef UartHandle;

extern void uart_log_set_console(void);

static void UART_LOG_Msp_Init(void)
{
    GPIO_InitTypeDef  GPIO_InitStruct;

    RCC_PeriphCLKInitTypeDef RCC_PeriphClkInit;

    /*##-1- Enable peripherals and GPIO Clocks #################################*/
    /* Enable GPIO TX/RX clock */
    USART_LOG_TX_GPIO_CLK_ENABLE();
    USART_LOG_RX_GPIO_CLK_ENABLE();

    /* Select HSI as source of USARTx clocks */
    RCC_PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART_LOG;
    RCC_PeriphClkInit.Usart16ClockSelection = RCC_USART_LOG_CLKSOURCE_HSI;
    HAL_RCCEx_PeriphCLKConfig(&RCC_PeriphClkInit);

    /* Enable USARTx clock */
    USART_LOG_CLK_ENABLE();

    /*##-2- Configure peripheral GPIO ##########################################*/
    /* UART TX GPIO pin configuration  */
    GPIO_InitStruct.Pin       = USART_LOG_TX_PIN;
    GPIO_InitStruct.Mode      = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull      = GPIO_PULLUP;
    GPIO_InitStruct.Speed     = GPIO_SPEED_FREQ_VERY_HIGH;
    GPIO_InitStruct.Alternate = USART_LOG_TX_AF;

    HAL_GPIO_Init(USART_LOG_TX_GPIO_PORT, &GPIO_InitStruct);

    /* UART RX GPIO pin configuration  */
    GPIO_InitStruct.Pin = USART_LOG_RX_PIN;
    GPIO_InitStruct.Alternate = USART_LOG_RX_AF;

    HAL_GPIO_Init(USART_LOG_RX_GPIO_PORT, &GPIO_InitStruct);
    
    /* NVIC for USART */
    HAL_NVIC_SetPriority(USART_LOG_IRQn, 0, 1);
    HAL_NVIC_EnableIRQ(USART_LOG_IRQn);
}

void uart_log_init(void)
{
    UartHandle.Instance             = USART_LOG;
    UartHandle.Init.BaudRate        = UART_LOG_BAUDRATE;
    UartHandle.Init.WordLength      = UART_WORDLENGTH_8B;
    UartHandle.Init.StopBits        = UART_STOPBITS_1;
    UartHandle.Init.Parity          = UART_PARITY_NONE;
    UartHandle.Init.HwFlowCtl       = UART_HWCONTROL_NONE;
    UartHandle.Init.Mode            = UART_MODE_TX_RX;
    UartHandle.Init.ClockPrescaler  = UART_PRESCALER_DIV1;
    UartHandle.Init.OneBitSampling  = UART_ONE_BIT_SAMPLE_DISABLE;
    UartHandle.Init.OverSampling    = UART_OVERSAMPLING_16;

    UART_LOG_Msp_Init();

    if(HAL_UART_Init(&UartHandle) != HAL_OK)
    {
        while (1) {
        }
    }
    /* Set the RXFIFO threshold */
    HAL_UARTEx_SetRxFifoThreshold(&UartHandle, UART_RXFIFO_THRESHOLD_1_2);

    /* Enable the FIFO mode */
    HAL_UARTEx_EnableFifoMode(&UartHandle);
    uart_log_set_console();
}
