/*!
 * @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_pmu.h"
#include "g32a10xx_eint.h"
#include "g32a10xx_syscfg.h"
#include "g32a10xx_misc.h"
#include "g32a10xx_iwdt.h"

/** @addtogroup Examples
  @{
  */

/** @addtogroup PMU_Examples
  @{
  */

/** @addtogroup PMU_WakeUp
  @{
  */

/** @defgroup PMU_WakeUp_Macros Macros
  @{
*/

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

/**@} end of group PMU_WakeUp_Macros */

/** @defgroup PMU_WakeUp_Functions Functions
  @{
  */

/* Pmu_Delay */
void Pmu_Delay(uint32_t count);
/* Init WakeUp Line */
void Eint_WakeUp_Line_Init(void);
/* IWDT init */
void Iwdt_Init(void);
void Pmu_G32aEval_PB_Isr(void);

void Eint_WakeUp_From_Stop_Isr(void);
void Eint_WakeUp_From_Sleep_Isr(void);

extern void SystemClockConfig(void);

/*!
 * @brief    main program
 *
 * @param    None
 *
 * @retval   None
 *
 * @note
 */
int main(void)
{
    Board_LedInit(LED2);
    Board_LedInit(LED3);
    Board_ButtonInit(BUTTON_KEY1, BUTTON_MODE_EINT);
    Board_ButtonInit(BUTTON_KEY2, BUTTON_MODE_EINT);
    Board_ButtonInit(BUTTON_KEY3, BUTTON_MODE_EINT);
    Board_ComInit(COM1);

    Pmu_Reset();
    Rcm_EnableApb1PeriphClock(RCM_APB1_PERIPH_PMU);

    /* Init PA6 as wakeup pin for sleep mode*/
    Eint_WakeUp_Line_Init();

    printf("\r\nSystem is Init\r\n");
    if (Rcm_ReadStatusFlag(RCM_FLAG_IWDTRST) == (uint16_t)SET)
    {
        Rcm_ClearStatusFlag();
        printf("\r\nSystem IWDT Reset Occur\r\n");
    }
    else
    {
        /* do nothing */
    }
    printf("Press KEY1   : ENTER Sleep   Mode\r\n");
    printf("Press KEY2   : ENTER StandBy Mode\r\n");
    printf("Press KEY3   : ENTER Stop    Mode\r\n\r\n");

    for (;;)
    {
        Pmu_Delay(0xfffff);
        Board_LedToggle(LED3);
        printf("\r\nSystem is running\r\n");
    }
}

/*!
 * @brief    WakeUp line configure
 *
 * @param    None
 *
 * @retval   None
 *
 * @note
 */
void Eint_WakeUp_Line_Init(void)
{
    Gpio_ConfigType gpioConfig;
    Eint_ConfigType eintConfig;
    /* Enable the BUTTON Clock */
    Rcm_EnableAhbPeriphClock(RCM_AHB_PERIPH_GPIOA);
    Rcm_EnableApb2PeriphClock(RCM_APB2_PERIPH_SYSCFG);

    /* Configure Button pin as input floating */
    gpioConfig.mode = GPIO_MODE_IN;
    gpioConfig.pupd = GPIO_PUPD_PU;
    gpioConfig.pin = (uint16_t)GPIO_PIN_5;
    Gpio_Config(GPIOA, &gpioConfig);

    gpioConfig.pin = (uint16_t)GPIO_PIN_6;
    Gpio_Config(GPIOA, &gpioConfig);

    gpioConfig.pin = (uint16_t)GPIO_PIN_7;
    Gpio_Config(GPIOA, &gpioConfig);

    Gpio_SetBit(GPIOA, (uint16_t)GPIO_PIN_5);
    /* PA6,PA7 set Bits and wait for falling to enter interrupt*/
    Gpio_SetBit(GPIOA, (uint16_t)GPIO_PIN_6);
    Gpio_SetBit(GPIOA, (uint16_t)GPIO_PIN_7);

    /* Configure GPIO pin used as EINT Line */
    Syscfg_EintLine(SYSCFG_PORT_GPIOA, SYSCFG_PIN_6);
    Syscfg_EintLine(SYSCFG_PORT_GPIOA, SYSCFG_PIN_7);

    /* Configure EINT6 line */
    eintConfig.line    =  (uint32_t)EINT_LINE6;
    eintConfig.lineCmd =  ENABLE;
    eintConfig.mode    =  EINT_MODE_INTERRUPT;
    eintConfig.trigger =  EINT_TRIGGER_FALLING;
    Eint_Config(&eintConfig);

    eintConfig.line    =  (uint32_t)EINT_LINE7;
    Eint_Config(&eintConfig);

    /* Enable and set EINTx Interrupt */
    Nvic_EnableIrqRequest(EINT4_15_IRQn, 0x0e);
}

/*!
 * @brief    enter STOP mode interrupt
 *
 * @param    None
 *
 * @retval   None
 *
 * @note
 */
void Eint_WakeUp_From_Stop_Isr(void)
{
    if (Eint_ReadStatusFlag((uint32_t)EINT_LINE7) == (uint8_t)SET)
    {
        /* The interrupt flag bit must be cleared first. */
        Eint_ClearStatusFlag((uint32_t)EINT_LINE7);
        SystemClockConfig();
        Board_ComInit(COM1);
        printf("\r\nSystem have exit Stop mode\r\n");
        while(0u == Usart_ReadStatusFlag(DEBUG_USART, USART_FLAG_TXC))
        {
            /* nothing */
        }
    }
    else
    {
         /*  nothing */
    }
}
/*!
 * @brief    WakeUp from Sleep mode Interrupt
 *
 * @param    None
 *
 * @retval   None
 *
 * @note
 */
void Eint_WakeUp_From_Sleep_Isr(void)
{
    if (Eint_ReadStatusFlag((uint32_t)EINT_LINE6) == (uint8_t)SET)
    {
        Board_LedOff(LED2);
        /* The interrupt flag bit must be cleared first. */
        Eint_ClearStatusFlag((uint32_t)EINT_LINE6);
        printf("\r\nSystem have exit Sleep mode\r\n");
        while(0u == Usart_ReadStatusFlag(DEBUG_USART, USART_FLAG_TXC))
        {
            /* nothing */
        }
    }
    else
    {
         /*  nothing */
    }
}

/*!
 * @brief    enter STANDBY mode or Sleep mode Interrupt
 *
 * @param    None
 *
 * @retval   None
 *
 * @note
 */
void Pmu_G32aEval_PB_Isr(void)
{

    if (Eint_ReadStatusFlag((uint32_t)KEY1_BUTTON_EXTI_LINE) == (uint8_t)SET)
    {
        /* The interrupt flag bit must be cleared first. */
        Eint_ClearStatusFlag((uint32_t)KEY1_BUTTON_EXTI_LINE);

        printf("\r\nSystem have entered Sleep mode\r\n");
        printf("now, LED2 is on ,while LED3 remain in the previous state\r\n");
        printf("and you can low down PA6 or reset System to over Sleep mode\r\n\r\n");
        while(0u == Usart_ReadStatusFlag(DEBUG_USART, USART_FLAG_TXC))
        {
            /* nothing */
        }

        Board_LedOn(LED2);
        /* Enter Sleep Mode, and Wake up by interrupt*/
        Pmu_EnterSleepMode(PMU_SLEEPENTRY_WFI);
    }
    else
    {
         /*  nothing */
    }

    if (Eint_ReadStatusFlag((uint32_t)KEY2_BUTTON_EXTI_LINE) == (uint8_t)SET)
    {
        /* The interrupt flag bit must be cleared first. */
        Eint_ClearStatusFlag((uint32_t)KEY2_BUTTON_EXTI_LINE);

        printf("\r\nSystem have entered STANDBY mode\r\n");
        Iwdt_Init();
        printf("\r\nIWDT is enable\r\n");
        printf("now, LED2 and LED3 is off\r\n");
        printf("please wait for IWDT timeout to exit STANDBY mode\r\n\r\n");
        while(0u == Usart_ReadStatusFlag(DEBUG_USART, USART_FLAG_TXC))
        {
            /* nothing */
        }

        /* Clear flag bit to prevent repeated entry interrupt*/
        Pmu_ClearStatusFlag((uint8_t)PMU_FLAG_STDBYF);
        Pmu_ClearStatusFlag((uint8_t)PMU_FLAG_WUPF);

        /* Enter StandBy Mode*/
        Pmu_EnterStandbyMode();
    }
    else
    {
         /*  nothing */
    }

    if (Eint_ReadStatusFlag((uint32_t)KEY3_BUTTON_EXTI_LINE) == (uint8_t)SET)
    {
        /* The interrupt flag bit must be cleared first. */
        Eint_ClearStatusFlag((uint32_t)KEY3_BUTTON_EXTI_LINE);

        printf("\r\nSystem have entered STOP mode\r\n");
        printf("now, LED2 and LED3 remain in the previous state\r\n");
        printf("and you can low down PA7 or reset System to over STOP mode\r\n\r\n");
        while(0u == Usart_ReadStatusFlag(DEBUG_USART, USART_FLAG_TXC))
        {
            /* nothing */
        }

        /* Enter STOP Mode in WFI*/
        Pmu_EnterStopMode(PMU_REGULATOR_ON, PMU_STOPENTRY_WFI);
    }
    else
    {
         /*  nothing */
    }
}

/*!
 * @brief       Pmu_Delay
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
void Pmu_Delay(uint32_t count)
{
    volatile uint32_t delay = count;

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

/*!
 * @brief       IWDT Init
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
void Iwdt_Init(void)
{

    /* clear IWDTRST Flag*/
    if (Rcm_ReadStatusFlag(RCM_FLAG_IWDTRST) != (uint16_t)RESET)
    {
        Rcm_ClearStatusFlag();
    }
    else
    {
        /* nothing */
    }

    /* set IWDT Write Access */
    Iwdt_EnableWriteAccess();

    /* set IWDT Divider*/
    Iwdt_ConfigDivider(IWDT_DIV_64);

    /* set IWDT Reloader*/
    Iwdt_ConfigReload(40000 / 32);

    /* Refresh*/
    Iwdt_Refresh();

    /* Enable IWDT*/
    Iwdt_Enable();
}

#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)
    {
        /* 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 PMU_WakeUp_Functions */
/**@} end of group PMU_WakeUp */
/**@} end of group PMU_Examples */
/**@} end of group Examples */
