/**
 * @file        main.c
 *
 * @brief       Main program body
 *
 * @version     V1.0.0
 *
 * @date        2024-08-01
 *
 * @attention
 *
 *  Copyright (C) 2024-2025 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"

/* Private includes *******************************************************/
#include "apm32f4xx_device_cfg.h"
#include "log.h"

/* Private macro **********************************************************/

/* Private typedef ********************************************************/

/* Private variables ******************************************************/
static const char* tag = "main";
static volatile uint8_t enterLowPowerMode = 0;

/* Private function prototypes ********************************************/
static void Delay(uint32_t time);

/* External variables *****************************************************/

/* External functions *****************************************************/

/**
 * @brief   Main program
 *
 * @param   None
 *
 * @retval  None
 */
int main(void)
{
    /* Device configuration */
    DAL_DeviceConfig();

    /* Infinite loop */
    while (1)
    {
        if(enterLowPowerMode)
        {
            __WFI();
        }
        BOARD_LED_Toggle(LED2);
        Delay(0xFFFFF);
    }
}

/**
 * @brief  EINT line detection callbacks
 *
 * @param  GPIO_Pin Specifies the pins connected EINT line
 *
 * @retval None
 */
void DAL_GPIO_EINT_Callback(uint16_t GPIO_Pin)
{
    if (GPIO_Pin == GPIO_PIN_0)
    {
        BOARD_LED_Off(LED3);
        LOGI(tag, "Enter sleep mode\r\n");
        enterLowPowerMode = 1;
        DAL_NVIC_DisableIRQ(EINT0_IRQn);
    }

    if (GPIO_Pin == GPIO_PIN_1)
    {
        BOARD_LED_On(LED3);
        LOGI(tag, "Wake up\r\n");
        enterLowPowerMode = 0;
        DAL_NVIC_EnableIRQ(EINT0_IRQn);
    }
}

/**
 * @brief  Software delay
 *
 * @param  GPIO_Pin Specifies the pins connected EINT line
 *
 * @retval None
 */
static void Delay(uint32_t time)
{
    volatile uint32_t cnt = 0;
    while(cnt < time)
    {
        cnt++;
    }
}
