/*!
 * @file        main.c
 *
 * @brief       Main program body
 *
 * @version     V1.0.0
 *
 * @date        2023-03-30
 *
 * @attention
 *
 *  Copyright (C) 2023 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"
#include "Board.h"
#include "stdio.h"
#include "apm32a0xx_rtc.h"
#include "apm32a0xx_pmu.h"
#include "apm32a0xx_eint.h"
#include "apm32a0xx_rcm.h"


/** @addtogroup Examples
  @{
  */

/** @addtogroup RTC_StopWatch
  @{
  */
  
/** @defgroup RTC_StopWatch_Macros Macros
  @{
*/

/* printf using USART1  */
#define DEBUG_USART  USART1

/**@} end of group RTC_StopWatch_Macros */

/** @defgroup RTC_StopWatch_Enumerations Enumerations
  @{
*/

/**@} end of group RTC_StopWatch_Enumerations */

/** @defgroup RTC_StopWatch_Structures Structures
  @{
*/

/**@} end of group RTC_StopWatch_Structures */

/** @defgroup RTC_StopWatch_Variables Variables
  @{
*/

/* Judgement flag bit */
static uint8_t s_key1Flag = 0;
static uint8_t s_key2Flag = 0;

/**@} end of group RTC_StopWatch_Variables */

/** @defgroup RTC_StopWatch_Functions Functions
  @{
  */

/* Delay */
void Delay(void);
/* RTC Init */
void RTC_Init(void);

/*!
 * @brief       Main program
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
int main(void)
{
    RTC_TIME_T rtc_TIME;
    
    /* Configures LED GPIO */
    APM_MINI_LEDInit(LED2);
    APM_MINI_LEDInit(LED3);
    
    /* Configures Button GPIO and EINT Line */
    APM_MINI_PBInit(BUTTON_KEY1,BUTTON_MODE_EINT);
    APM_MINI_PBInit(BUTTON_KEY2,BUTTON_MODE_EINT);
      
    /* Configures COM port */
    APM_MINI_COMInit(COM1);
    
    /* Enable the LSI OSC */
    RCM_EnableLSI();

    /* Reset RTC*/
    RTC_Reset();

    /* Config RTC */
    RTC_Init();
    
    printf("This example is for RTC StopWatch\r\n");
    printf(" please press key1 to start count\r\n");
    
    while(1)
    {
        /* Check whether key1 is pressed */ 
        if(s_key1Flag == 1)
        {
            /* Delay */
            Delay();
            s_key1Flag = 0;
            
            printf(" please press key2 to stop count\r\n");
            
            /* Configure RTC Time structure */
            rtc_TIME.hours = 0;
            rtc_TIME.minutes = 0;
            rtc_TIME.seconds = 0;
            rtc_TIME.H12 = RTC_H12_AM;
            RTC_ConfigTime(RTC_FORMAT_BCD,&rtc_TIME);
                
            while(GPIO_ReadInputBit(GPIOA,1))
            {
                /* Check whether key2 is pressed */ 
                if(s_key2Flag == 1)
                {
                    /* Delay */
                    Delay();
                    /* keystroke elimination */
                    s_key2Flag = 0;
                }
            }
            s_key2Flag = 0;
            
            /* Read the RTC current Time */
            RTC_ReadTime(RTC_FORMAT_BCD,&rtc_TIME);
            
            printf(" suspend time = %xh:%xm:%xs\r\n",rtc_TIME.hours,rtc_TIME.minutes,rtc_TIME.seconds);
            printf(" please press key1 to reset the conunt \r\n");
                 
            while(GPIO_ReadInputBit(GPIOA, 0))
            {
                /* Check whether key1 is pressed */ 
                if(s_key1Flag == 1)
                {
                    /* Delay */
                    Delay();
                    
                    /* keystroke elimination */
                    s_key1Flag = 0;
                }
            }
            
            Delay();
            s_key1Flag = 0;
            
        }
    }
}

/*!
 * @brief       EINT Time Record
 *
 * @param       None
 *
 * @retval      None
 *
 * @note        This function need to put into EINT0_1_IRQHandler in apm32a0xx_int.h
 */
void EINT_Time_Record(void)
{
    /* Read the specified EINT line interrupt flag */
    if (EINT_ReadIntFlag(EINT_LINE1) == SET)
    {
        /* Mark Key 1 Press */
        s_key1Flag = 1;
        /* Clears the EINT line pending bits */
        EINT_ClearIntFlag(EINT_LINE1);  
    }
        
    /* Read the specified EINT line interrupt flag */
    if(EINT_ReadIntFlag(EINT_LINE0) == SET)
    {
        /* Mark Key 2 Press */
        s_key2Flag = 1;
        /* Clears the EINT line pending bits */
        EINT_ClearIntFlag(EINT_LINE0);
    }
}
/*!
 * @brief       RTC Configuration
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
void RTC_Init(void)
{
    RTC_Config_T Struct;

    /* Enable PMU periph clock */
    RCM_EnableAPB1PeriphClock(RCM_APB1_PERIPH_PMU);

    /* Enable Access Backup */
    PMU_EnableBackupAccess();

    /* Enable LSI */
    RCM_EnableLSI();

    /* wait until LSI is ready */
    while (RCM_ReadStatusFlag(RCM_FLAG_LSIRDY) == RESET);

    /* Select LSI as RTC clock */
    RCM_ConfigRTCCLK(RCM_RTCCLK_LSI);

    /* Enable RTC clock */
    RCM_EnableRTCCLK();

    RTC_DisableWriteProtection();

    RTC_WaitForSynchro();

    /* LSI */
    RTC_ConfigStructInit(&Struct);
    Struct.AsynchPrediv = 0X63;
    Struct.SynchPrediv  = 0X18F;

    RTC_Config(&Struct);
      
}

/*!
 * @brief       Delay
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
void Delay(void)
{
    volatile uint32_t delay = 0xffff5;
    while (delay--);
}

#if defined (__CC_ARM) || defined (__ICCARM__) || (defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050))

/*!
* @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.
*
* @note
*/
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);
}

#elif defined (__GNUC__)

/*!
* @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.
*
* @retval      The characters that need to be send.
*
* @note
*/
int __io_putchar(int ch)
{
    /* send a byte of data to the serial port */
    USART_TxData(DEBUG_USART, ch);

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

    return ch;
}

/*!
* @brief       Redirect C Library function printf to serial port.
*              After Redirection, you can use printf function.
*
* @param       file:  Meaningless in this function.
*
* @param       *ptr:  Buffer pointer for data to be sent.
*
* @param       len:  Length of data to be sent.
*
* @retval      The characters that need to be send.
*
* @note
*/
int _write(int file, char* ptr, int len)
{
    int i;
    for (i = 0; i < len; i++)
    {
        __io_putchar(*ptr++);
    }

    return len;
}

#else
#warning Not supported compiler type
#endif

/**@} end of group RTC_StopWatch_Functions */
/**@} end of group RTC_StopWatch */
/**@} end of group Examples */
