/*!
 * @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 RS485 examples
  @{
  */

/** @addtogroup USART_RS485
  @{
  */

/** @defgroup USART_RS485_Macros Macros
  @{
*/

/* printf using UART4 */
#define DEBUG_USART           UART4

/* Delay for RS485 Control line */
#define RS485_BUS_DELAY       1000

/* Time out for data receive */
#define RS485_RX_TIME_OUT     5000

/* max number of rx buffer */
#define RS485_RXBUF_MAX_NUM   512

/**@} end of group USART_RS485_Macros */

/** @defgroup USART_RS485_Enumerates Enumerates
  @{
  */

typedef enum
{
    RS485_STATUS_TX,
    RS485_STATUS_RX
} RS485_STATUS_T;

/**@} end of group USART_RS485_Enumerates */


/** @defgroup USART_RS485_Variables Variables
  @{
  */

/* Timer tick */
uint16_t cntTick = 0;

/* RS485 Receive Buffer */
uint8_t rxBuffer[RS485_RXBUF_MAX_NUM];

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

/* Menu item string */
const char* menuItemStr[] =
{
    "Press KEY1 to send data to  ",
    "the serial assistant through",
    "RS485.                      "
};

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

/**@} end of group USART_RS485_Variables */

/** @defgroup USART_RS485_Functions Functions
  @{
  */

/* Private functions declaration */
void APM_EVAL_Init(void);
void RS485_Init(uint32_t baud);
void RS485_ConfigTxRx(RS485_STATUS_T status);
void RS485_TxString(char* pStr);
void Menu_DisplayInit(void);
void APM_EVAL_TMR7_Init(uint16_t period, uint16_t div);
void Delay(uint32_t delayTime);

/*!
 * @brief       Main program
 *
 * @param       None
 *
 * @retval      None
 *
 */
int main(void)
{
    APM_EVAL_Init();
    
    printf("[UART4] This is a USART RS485 Example.\r\n");

    RS485_TxString("[RS485 Send] This is a USART RS485 Example.\r\n");
    
    while (1)
    {
        if (APM_EVAL_PBGetState(BUTTON_KEY1) == 0)
        {
            RS485_TxString("[RS485 Send] APM32F107 EVAL USART RS485 Test.\r\n");
            while (APM_EVAL_PBGetState(BUTTON_KEY1) == 0);
        }
    }
}

/*!
 * @brief       Init EVAL board
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
void APM_EVAL_Init(void)
{
    USART_Config_T usartConfigStruct;
    
    /* 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);
    
    /* UART4 Config */
    usartConfigStruct.baudRate = 115200;
    usartConfigStruct.hardwareFlow = USART_HARDWARE_FLOW_NONE;
    usartConfigStruct.mode = USART_MODE_TX_RX;
    usartConfigStruct.parity = USART_PARITY_NONE;
    usartConfigStruct.stopBits = USART_STOP_BIT_1;
    usartConfigStruct.wordLength = USART_WORD_LEN_8B;
    APM_EVAL_COMInit(COM4, &usartConfigStruct);

    APM_EVAL_TMR7_Init(1000, 72);

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

    APM_EVAL_DelayMs(100);

    Menu_DisplayInit();
    
    /* RS485 Init */
    RS485_Init(9600);
}

/*!
 * @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);
    LCD_DisplayString(10, LCD_LINE_3, menuItemStr[1], LCD_TEXT_FC, LCD_TEXT_BC, 16, 0);
    LCD_DisplayString(10, LCD_LINE_4, menuItemStr[2], 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       RS485 Init
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
void RS485_Init(uint32_t baud)
{
    USART_Config_T usartConfigStruct;
    GPIO_Config_T gpioConfig;

    /* RS485_EN Config Rx or Tx */
    RCM_EnableAPB2PeriphClock(RCM_APB2_PERIPH_GPIOC);
    gpioConfig.mode = GPIO_MODE_OUT_PP;
    gpioConfig.pin = GPIO_PIN_6;
    gpioConfig.speed = GPIO_SPEED_50MHz;
    GPIO_Config(GPIOC, &gpioConfig);
    
    /* Default receive mode */
    GPIO_ResetBit(GPIOC, GPIO_PIN_6);
    
    /* RS485 Rx/Tx GPIO PinRemap */
    RCM_EnableAPB2PeriphClock(RCM_APB2_PERIPH_AFIO);
    GPIO_ConfigPinRemap(GPIO_REMAP_USART2);
    
    /* USART configuration */
    USART_ConfigStructInit(&usartConfigStruct);
    usartConfigStruct.baudRate = baud;
    usartConfigStruct.mode = USART_MODE_TX_RX;
    usartConfigStruct.parity = USART_PARITY_NONE;
    usartConfigStruct.stopBits = USART_STOP_BIT_1;
    usartConfigStruct.wordLength = USART_WORD_LEN_8B;
    usartConfigStruct.hardwareFlow = USART_HARDWARE_FLOW_NONE;

    /* RS485 init, use COM2 */
    APM_EVAL_COMInit(COM2, &usartConfigStruct);

    /* Enable USART2 RXBNE interrput */
    USART_EnableInterrupt(EVAL_COM2, USART_INT_RXBNE);
    USART_ClearStatusFlag(EVAL_COM2, USART_FLAG_RXBNE);
    NVIC_EnableIRQRequest(EVAL_COM2_IRQn, 1, 10);
}

/*!
 * @brief       Config RS485 to Rx or Tx.
 *
 * @param       status : Choose Send or Receive.
 *                       This parameter can be one of the following values:
 *                       @arg RS485_STATUS_TX : Send data
 *                       @arg RS485_STATUS_RX : Receive data
 *
 * @retval      None
 */
void RS485_ConfigTxRx(RS485_STATUS_T status)
{
    /** Prepare to thransfer data though RS485 */
    Delay(RS485_BUS_DELAY);

    if (status == RS485_STATUS_TX)
    {
        GPIO_SetBit(GPIOC, GPIO_PIN_6);
    }
    else
    {
        GPIO_ResetBit(GPIOC, GPIO_PIN_6);
    }
}

/*!
 * @brief       RS485 Send a byte data.
 *
 * @param       data : data to send.
 *
 * @retval      None
 */
void RS485_TxByte(uint8_t data)
{
    USART_TxData(USART2, data);

    while (!USART_ReadStatusFlag(USART2, USART_FLAG_TXBE));
}

/*!
 * @brief       RS485 Send String.
 *
 * @param       pStr : pointer to the string to send.
 *
 * @retval      None
 */
void RS485_TxString(char* pStr)
{
    RS485_ConfigTxRx(RS485_STATUS_TX);
    
    while (*pStr != 0)
    {
        USART_TxData(USART2, *pStr++);

        while (!USART_ReadStatusFlag(USART2, USART_FLAG_TXBE));
    }
    
    RS485_ConfigTxRx(RS485_STATUS_RX);
}

/*!
 * @brief       RS485 Reveive Interrupt handler.
 *
 * @param       None
 *
 * @retval      None
 */
void RS485_RxIsr(void)
{
    __IO uint32_t timeCnt = 0, buffIndex = 0;
    
    while(timeCnt < RS485_RX_TIME_OUT)
    {
        /* Keep Receive the a serie data */
        if (USART_ReadStatusFlag(USART2, USART_FLAG_RXBNE))
        {
            rxBuffer[buffIndex++] = USART_RxData(USART2);
            timeCnt = 0;
        }
        else
        {
            timeCnt++;
        }

        /* If data more than buffer then break out */
        if (buffIndex == RS485_RXBUF_MAX_NUM)
        {
            printf("RS485 Receive buffer is full!\r\n");
            break;
        }
    }
    
    /* Send data */
    RS485_ConfigTxRx(RS485_STATUS_TX);

    for (uint32_t i = 0; i < buffIndex; i++)
    {
        RS485_TxByte(rxBuffer[i]);
    }

    RS485_ConfigTxRx(RS485_STATUS_RX);
}

/*!
 * @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       Delay
 *
 * @param       None
 *
 * @retval      None
 */
void Delay(uint32_t delayTime)
{
    __IO uint32_t i = 0;
    __IO uint32_t j = 0;

    do
    {
        i++;
        j++;
    }
    while (i < (delayTime * 6));
}

/*!
 * @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_RS485_Functions */
/**@} end of group USART_RS485 */
/**@} end of group Examples */
