/*!
 * @file        main.c
 *
 * @brief       Main program body
 *
 * @version     V1.0.0
 *
 * @date        2026-02-25
 *
 * @attention
 *
 *  Copyright (C) 2026 Geehy Semiconductor
 *
 *  You may not use this file except in compliance with the
 *  GEEHY COPYRIGHT NOTICE (Geehy Semiconductor Software License Agreement).
 *
 *  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 Semiconductor Software License Agreement for the governing permissions
 *  and limitations under the License.
 */

/* Includes */
#include "Board.h"
#include "stdio.h"
#include "g32a10xx_gpio.h"
#include "g32a10xx_misc.h"
#include "g32a10xx_eint.h"
#include "g32a10xx_rtc.h"
#include "g32a10xx_pmu.h"
#include "user_rtc_config.h"

/** @addtogroup Examples
  @{
  */

/** @addtogroup RTC_Examples
  @{
  */

/** @addtogroup RTC_LSI
  @{
  */

/** @defgroup RTC_LSI_Macros Macros
  @{
*/

/* printf function configs to USART1 */
#define DEBUG_USART  USART1

/**@} end of group RTC_LSI_Macros */

/** @defgroup RTC_LSI_Functions Functions
  @{
  */

/* Delay */
static void Delay(void);
/* RTC Init */
static void Rtc_Init(void);

/*!
 * @brief       Main program
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
int main(void)
{
    uint8_t presec;

    Board_LedInit(LED2);
    Board_ComInit(COM1);

    /* RTC Reset */
    Rtc_Init();

    printf("Use the LSI(32KHz) clock source! \r\n");
    
    /* config 16 second calibration cycle, so the CALM[0] bit is always 0.
    reduced calibration value is 2, it base on frequency drift of your board
    The calibration value needs to be determined through testing. */
    Rtc_ConfigSmoothCalib(RTC_SCP_16SEC, RTC_SCPP_RESET, 2U);
    printf("Config auto calibration! \r\n");
    
    /* RTC Enable Init */
    Rtc_EnableInit();

    /* Init Date 2020/8/8/ 6 */
    Rtc_ConfigDate(RTC_FORMAT_BIN, &dateConfig);
    
    /* Init Time 23:59:30 */
    Rtc_ConfigTime(RTC_FORMAT_BIN, &timeConfig);

    /* Wait is neccessary */
    Delay();

    /* RTC Disable Init */
    Rtc_DisableInit();

    for (;;)
    {
        /* Read last Time */
        presec = timeConfig.seconds;

        /* Read time */
        Rtc_ReadTime(RTC_FORMAT_BIN, &timeConfig);

        /* If pass 1 second */
        if (presec != timeConfig.seconds)
        {
            Board_LedToggle(LED2);

            /* Read Date */
            Rtc_ReadDate(RTC_FORMAT_BIN, &dateConfig);

            printf("\r\n Date: 20%d/%02d/%02d ",dateConfig.year, dateConfig.month, dateConfig.date);
            printf(" Weekday: %d ", dateConfig.weekday);
            printf(" Time: %02d:%02d:%02d \r\n",(timeConfig.hours), (timeConfig.minutes), (timeConfig.seconds));
        }
        else
        {
             /* nothing */
        }
    }
}

/*!
 * @brief       RTC Init
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
static void Rtc_Init(void)
{
    /* Enable the PWR clock */
    Rcm_EnableApb1PeriphClock(RCM_APB1_PERIPH_PMU);

    /* Allow access to RTC */
    Pmu_EnableBackupAccess();
    
    /* Enable the LSI OSC */
    Rcm_EnableLsi();
    
    /* Wait till LSI is ready */
    while (Rcm_ReadStatusFlag(RCM_FLAG_LSIRDY) == (uint16_t)RESET)
    {
        /* do nothing */
    }
    
    /* Reset RTC */
    Rtc_Reset();
    
    /* Select the RTC Clock Source */
    Rcm_ConfigRtcClk(RCM_RTCCLK_LSI);

    /* Enable RTC Clock */
    Rcm_EnableRtcClk();

    /* Wait Synchro */
    Rtc_WaitForSynchro();

    /* Configure RTC */
    Rtc_Config(&rtcConfig);
}

/*!
 * @brief       Delay
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
static void Delay(void)
{
    volatile uint32_t delay = 0x1FFFFU;

    while (delay > 0U)
    {
        delay -= 1U;
    }
}

#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) == (uint8_t)RESET)
    {
        /* do nothing */
    }

    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
#pragma message("Not supported compiler type")
#endif

/**@} end of group RTC_LSI_Functions */
/**@} end of group RTC_LSI */
/**@} end of group RTC_Examples */
/**@} end of group Examples */
