/**************************************************************************//**
* @file     pan_uart.c
* @version  V1.10
* $Revision: 2 $
* $Date:    19/10/08 09:25 $
* @brief    Panchip series UART driver source file
*
* @note
* Copyright (C) 2025 Panchip Technology Corp. All rights reserved.
*****************************************************************************/
#include "pan271x.h"
#include "pan_uart.h"
#include "pan_clk.h"

/**
  * @brief  Initializes the UARTx peripheral according to the specified
  *         parameters in the UART_InitStruct .
  * @param  UARTx: where x can be 1, 2 to select the
  *         UART peripheral.
  * @param  UART_InitStruct: pointer to a UART_InitTypeDef structure that contains
  *         the configuration information for the specified UART peripheral.
  * @retval UART init success (true) or fail (false)
  */

bool UART_Init(UART_T* UARTx, uint32_t UART_BaudRate)
{
    uint32_t baudRateCnt = 0x00;
    uint64_t apbClock = 0x00;

	if (UART_BaudRate == 0) {
		return false;
	}
    /* Configure the UART Baud Rate */
    apbClock = CLK_GetPeripheralFreq((void*)UARTx);

	baudRateCnt = apbClock * 100 / UART_BaudRate;
	
	if ((baudRateCnt % 100) > 50) {
		baudRateCnt = baudRateCnt / 100 + 1;
	} else {
		baudRateCnt = baudRateCnt / 100;
	}
	
	if (baudRateCnt == 0) {
		return false;
	}
	
	UARTx->UART_BCNT = baudRateCnt;
	UARTx->UART_CTL |= UART_CTL_RX_EN_Msk | UART_CTL_TX_EN_Msk;
    return true;
}

void UART_DeInit(UART_T* UARTx)
{
	
}

bool UART_SendMultipleData(UART_T* UARTx, uint8_t* Buf, size_t BufSize, size_t SendSize)
{
    if (BufSize < SendSize)
        return false;

    while (SendSize--)
    {
        UART_SendData(UARTx, *Buf++);
        while(UARTx->UART_STATUS & UART_STATUS_TX_BUSY_Msk);    // Wait until THR is empty to avoid data lost
    }

    return true;
}

bool UART_ReceiveMultipleData(UART_T* UARTx, uint8_t* Buf, size_t BufSize, size_t ExpectSize)
{
    if (BufSize < ExpectSize)
        return false;

    while (!(UARTx->UART_STATUS & UART_STATUS_RX_EMPTY_FLAG_Msk) && ExpectSize)
    {
        *Buf++ = UART_ReceiveData(UARTx);
        ExpectSize--;
    }

    return true;
}


/*** (C) COPYRIGHT 2016 Panchip Technology Corp. ***/
