/*!
 * @file        main.c
 *
 * @brief       Main program body
 *
 * @version     V1.0.3
 *
 * @date        2025-07-03
 *
 * @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 "g32a10xx_fls.h"
#include "g32a10xx_syscfg.h"
#include "user_rtc_config.h"

/** @addtogroup Examples
  @{
*/

/** @addtogroup RTC_Examples
  @{
*/

/** @addtogroup RTC_LPWR_Wakeup
  @{
*/

/** @defgroup RTC_LPWR_Wakeup_Macros Macros
  @{
*/

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

#define FMC_SetLatency_2   FMC_SetWS2

/**@} end of group RTC_LPWR_Wakeup_Macros */

/** @defgroup RTC_LPWR_Wakeup_Functions Functions
  @{
*/

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

void Rtc_Isr(void);

#ifndef STANDBY_MODE
    static void System_Clock64M(void);
#endif

/*!
 * @brief       Main program
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
int main(void)
{
    Board_LedInit(LED2);
    Board_ComInit(COM1);

    printf("\r\n startup! Wakes up the loop every 100 ms...\r\n");
    
    /* must wait some time for debug or download */
    Delay();
    
    /* Config RTC */
    Rtc_Init();

    /* Config EINT */
    Eint_Config(&eintConfig);
    
    /*Config Alarm*/
    Rtc_AlarmsConfig();

    /* Alarm Enable */
    Rtc_EnableAlarm();

    while (1)
    {
        Board_LedToggle(LED2); 
        
#ifdef STANDBY_MODE
        if (Pmu_ReadStatusFlag(PMU_FLAG_WUPF) == 1)
        {
            /* quit the standby mode should clear the WUEFLG flag */
            Pmu_ClearStatusFlag(PMU_FLAG_WUPF);
        }
        Pmu_EnterStandbyMode();
#else
        Pmu_EnterStopMode(PMU_REGULATOR_ON, PMU_STOPENTRY_WFI);
        /* quit the stop mode should reconfigure frequency of master clock */
        System_Clock64M();
#endif
    }
}


/*!
 * @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);
    
    /* Open RTC ALARM interrupt whether into standby mode or stop mode */
    Rtc_EnableInterrupt((uint32_t)RTC_INT_ALR);
    Nvic_EnableIrqRequest(RTC_IRQn, 1U);
}


/*!
 * @brief       Config Alarm
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
static void Rtc_AlarmsConfig(void)
{
    /* Config Alarm */
    Rtc_ConfigAlarm(RTC_FORMAT_BIN, &alarmConfig);
    /* Config subsecond alarm  100ms */
    Rtc_ConfigAlarmSubSecond(ALRMA_SUB_SECOND_VALUE, ALRMA_SUB_SECOND_MASK); 
}

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

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

#ifndef STANDBY_MODE
void Rtc_Isr(void)
{
    Rtc_TimeType timeStruct;

    if (Rtc_ReadIntFlag(RTC_INT_FLAG_ALR) == 1U)
    {
        /* The interrupt flag bit must be cleared first. */
        Rtc_ClearIntFlag((uint32_t)RTC_INT_FLAG_ALR);
        /* Clear the EINT17 interrupt flag which is related to RTC alarm interrupt */
        Eint_ClearIntFlag((uint32_t)EINT_LINE17);

        /* reload the time of RTC*/
        timeStruct.H12 = (uint8_t)RTC_H12_AM;
        timeStruct.hours = 0;
        timeStruct.minutes = 0;
        timeStruct.seconds = 0;
        Rtc_ConfigTime(RTC_FORMAT_BIN, &timeStruct);
    }
    else
    {
        /* do nothing */
    }
}
#endif


#ifndef STANDBY_MODE
/*!
 * @brief       Sets System clock frequency to 64MHz and configure HCLK, PCLK2 and PCLK1 prescalers
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
static void System_Clock64M(void)
{
    uint32_t i;

    RCM->CTRL1_R.CTRL1_B.HSEEN = BIT_SET;

    for (i = 0U; i < HSE_STARTUP_TIMEOUT; i++)
    {
        if (RCM->CTRL1_R.CTRL1_B.HSERDYFLG == 1U)
        {
            break;
        }
        else
        {
            /* do nothing */
        }
    }

    if (RCM->CTRL1_R.CTRL1_B.HSERDYFLG == 1U)
    {
        /* Enable Prefetch Buffer */
        FMC->CTRL1_R.CTRL1_B.PBEN = BIT_SET;
        /* Flash 2 wait state */
        FMC_SetLatency_2();

        /* HCLK = SYSCLK */
        RCM->CFG1_R.CFG1_B.AHBPSC = 0x00U;

        /* PCLK = HCLK */
        RCM->CFG1_R.CFG1_B.APB1PSC = 0x00U;

        /* PLL: HSE(16MHz) * 4 */
        RCM->CFG1_R.CFG1_B.PLLSRCSEL = 1U;
        RCM->CFG1_R.CFG1_B.PLLMULCFG = 2U;

        /* Enable PLL */
        RCM->CTRL1_R.CTRL1_B.PLLEN = 1;

        /* Wait PLL Ready */
        while (RCM->CTRL1_R.CTRL1_B.PLLRDYFLG == (uint8_t)BIT_RESET)
        {
            /* do nothing */
        }

        /* Select PLL as system clock source */
        RCM->CFG1_R.CFG1_B.SCLKSEL = 2U;

        /* Wait till PLL is used as system clock source */
        while (RCM->CFG1_R.CFG1_B.SCLKSELSTS != 0x02U)
        {
            /* do nothing */
        }
    }
    else
    {
        /* do nothing */
    }
}
#endif


#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_LPWR_Wakeup_Functions */
/**@} end of group RTC_LPWR_Wakeup */
/**@} end of group RTC_Examples */
/**@} end of group Examples */
