/*!
 * @file        main.c
 *
 * @brief       Main program body
 *
 * @version     V1.0.0
 *
 * @date        2022-11-08
 *
 * @attention
 *
 *  Copyright (C) 2022 Geehy Semiconductor
 *
 *  You may not use this file except in compliance with the
 *  GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE).
 *
 *  The program is only for reference, which is distributed in the hope
 *  that it will be useful and instructional for customers to develop
 *  their software. Unless required by applicable law or agreed to in
 *  writing, the program is distributed on an "AS IS" BASIS, WITHOUT
 *  ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions
 *  and limitations under the License.
 */

/* Includes */
#include "main.h"

/** @addtogroup Examples
  * @brief USART Printf examples
  @{
  */

/** @addtogroup USART_Printf
  @{
  */

/** @defgroup USART_Printf_Macros Macros
  @{
*/

/* printf using UART4 */
#define DEBUG_USART           UART4

/**@} end of group USART_Printf_Macros */

/** @defgroup USART_Printf_Variables Variables
  @{
  */

uint8_t txBuf[] = "APM32F107 EVAL UART4 Printf Test.\r\n";

/* Timer tick */
uint16_t cntTick = 0;

/* Menu title string */
const char* menuTitleStr[] =
{
    "    UART4 Printf Example  ",
};

/* Menu item string */
const char* menuItemStr[] =
{
    "Press KEY1 to UART4 Printf",
};

/* Menu bottom column string */
const char* menuBottomColStr[] =
{
    "   GEEHY SEMICONDUCTOR   ",
};

/**@} end of group USART_Printf_Variables */

/** @defgroup USART_Printf_Functions Functions
  @{
  */

/* Private functions declaration */
void APM_EVAL_Init(void);
void UART4_Printf(void);
void UART4_Init(void);
void Menu_DisplayInit(void);
void APM_EVAL_TMR7_Init(uint16_t period, uint16_t div);

/*!
 * @brief       Main program
 *
 * @param       None
 *
 * @retval      None
 *
 */
int main(void)
{
    APM_EVAL_Init();
    
    printf("This is an example of UART4 print information through the serial port assistant.\r\n");

    while (1)
    {
        if (APM_EVAL_PBGetState(BUTTON_KEY1) == 0)
        {
            UART4_Printf();

            while (APM_EVAL_PBGetState(BUTTON_KEY1) == 0);
        }
    }
}

/*!
 * @brief       Init EVAL board
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
void APM_EVAL_Init(void)
{
    /* Init delay function */
    APM_EVAL_DelayInit();

    APM_EVAL_LEDInit(LED1);
    APM_EVAL_LEDInit(LED2);
    APM_EVAL_LEDInit(LED3);

    APM_EVAL_PBInit(BUTTON_KEY1, BUTTON_MODE_GPIO);

    APM_EVAL_TMR7_Init(1000, 72);

    APM_LCDInit();
    LCD_Clear(0, 0, LCD_WIDTH, LCD_HEIGHT, LCD_BCOLOR);

    UART4_Init();

    APM_EVAL_DelayMs(100);

    Menu_DisplayInit();
}

/*!
 * @brief       Initialize the Menu UI
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
void Menu_DisplayInit(void)
{
    /* Menu title */
    LCD_Clear(0, 0, LCD_WIDTH, 40, LCD_FCOLOR);
    LCD_DisplayString(10, LCD_LINE_TITLE, menuTitleStr[0], LCD_TEXT_SELECT_FC, LCD_TEXT_SELECT_BC, 16, 0);

    /* Menu item */
    LCD_DisplayString(10, LCD_LINE_2, menuItemStr[0], LCD_TEXT_FC, LCD_TEXT_BC, 16, 0);

    /* Menu bottom */
    LCD_Clear(0, LCD_LINE_BOTTOM, LCD_WIDTH, LCD_HEIGHT, LCD_FCOLOR);
    LCD_DisplayString(20, LCD_LINE_BOTTOM, menuBottomColStr[0], LCD_TEXT_SELECT_FC, LCD_TEXT_SELECT_BC, 16, 0);
}

/*!
 * @brief       UART4 Init
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
void UART4_Init(void)
{
    GPIO_Config_T GPIO_ConfigStruct;
    USART_Config_T USART_ConfigStruct;
    
    /* Enable GPIO peripheral Clock */
    RCM_EnableAPB2PeriphClock(RCM_APB2_PERIPH_GPIOC);
    
    /* Enable USART peripheral Clock */
    RCM_EnableAPB1PeriphClock(RCM_APB1_PERIPH_UART4);

    /* Configure USART Tx as alternate function push-pull */
    GPIO_ConfigStruct.mode = GPIO_MODE_AF_PP;
    GPIO_ConfigStruct.pin = GPIO_PIN_10;
    GPIO_ConfigStruct.speed = GPIO_SPEED_50MHz;
    GPIO_Config(GPIOC, &GPIO_ConfigStruct);

    /* Configure USART Rx as input floating */
    GPIO_ConfigStruct.mode = GPIO_MODE_IN_FLOATING;
    GPIO_ConfigStruct.pin = GPIO_PIN_11;
    GPIO_Config(GPIOC, &GPIO_ConfigStruct);

    /* USART configuration */
    USART_ConfigStruct.baudRate = 115200;
    USART_ConfigStruct.hardwareFlow = USART_HARDWARE_FLOW_NONE;
    USART_ConfigStruct.mode = USART_MODE_TX_RX;
    USART_ConfigStruct.parity = USART_PARITY_NONE;
    USART_ConfigStruct.stopBits = USART_STOP_BIT_1;
    USART_ConfigStruct.wordLength = USART_WORD_LEN_8B;
    USART_Config(UART4, &USART_ConfigStruct);
    
    /* Enable UART4 RXBNE interrput */
    USART_EnableInterrupt(UART4, USART_INT_RXBNE);
    USART_ClearStatusFlag(UART4, USART_FLAG_RXBNE);
    NVIC_EnableIRQRequest(UART4_IRQn, 1, 0);
    
    /* Enable USART */
    USART_Enable(UART4);
}

/*!
 * @brief       UART4 Printf
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
void UART4_Printf(void)
{
    uint8_t i;

    for (i = 0; i < (sizeof(txBuf)-1); i++)
    {
        USART_TxData(UART4, txBuf[i]);

        while (USART_ReadStatusFlag(UART4, USART_FLAG_TXBE) == RESET);
    }
}

/*!
 * @brief        This function handles UART4 RX interrupt Handler
 *
 * @param        None
 *
 * @retval       None
 *
 * @note         This function need to put into void UART4_IRQHandler(void)
 */
void USART_Receive_Isr(void)
{
    uint8_t temp;

    if(USART_ReadStatusFlag(UART4, USART_FLAG_RXBNE) == SET)
    {
        temp = USART_RxData(UART4);

        USART_TxData(UART4, temp);
    }
}

/*!
 * @brief       TMR7 init
 *
 * @param       None
 *
 * @retval      None
 *
 */
void APM_EVAL_TMR7_Init(uint16_t period, uint16_t div)
{
    TMR_BaseConfig_T  timeBaseConfig;

    /* Enable Clock */
    RCM_EnableAPB1PeriphClock(RCM_APB1_PERIPH_TMR7);

    /* Set clockDivision = 1 */
    timeBaseConfig.clockDivision =  TMR_CLOCK_DIV_1;
    /* Up-counter */
    timeBaseConfig.countMode =  TMR_COUNTER_MODE_UP;
    /* Set divider */
    timeBaseConfig.division = div - 1 ;
    /* Set counter = 0xffff */
    timeBaseConfig.period = period - 1;
    /* Repetition counter = 0x0 */
    timeBaseConfig.repetitionCounter =  0;

    TMR_ConfigTimeBase(TMR7, &timeBaseConfig);

    /* Enable update interrupt */
    TMR_EnableInterrupt(TMR7, TMR_INT_UPDATE);
    NVIC_EnableIRQRequest(TMR7_IRQn, 2, 2);

    /* Enable TMR7 */
    TMR_Enable(TMR7);
}

/*!
 * @brief       TMR7 interrupt service runtine
 *
 * @param       None
 *
 * @retval      None
 *
 * @note        This function need to put into TMR7_IRQHandler() in apm32f10x_int.c
 */
void TMR7_Isr(void)
{
    if (TMR_ReadIntFlag(TMR7, TMR_INT_UPDATE) == SET)
    {
        TMR_ClearIntFlag(TMR7, TMR_INT_UPDATE);
        cntTick++;

        if (cntTick >= 500)
        {
            cntTick = 0;
            APM_EVAL_LEDToggle(LED1);
        }
    }
}

/*!
 * @brief       Redirect C Library function printf to serial port.
 *              After Redirection, you can use printf function.
 *
 * @param       ch:  The characters that need to be send.
 *
 * @param       *f:  pointer to a FILE that can recording all information
 *              needed to control a stream
 *
 * @retval      The characters that need to be send.
 */
int fputc(int ch, FILE *f)
{
    /** send a byte of data to the serial port */
    USART_TxData(DEBUG_USART, (uint8_t)ch);

    /** wait for the data to be send */
    while (USART_ReadStatusFlag(DEBUG_USART, USART_FLAG_TXBE) == RESET);

    return (ch);
}

/**@} end of group USART_Printf_Functions */
/**@} end of group USART_Printf */
/**@} end of group Examples */
