/**
  ******************************************************************************
  * @file    main.c
  * @author  MCU Application Team
  * @brief   Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2023 Puya Semiconductor Co.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by Puya under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2016 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "py32l090xx_ll_Start_Kit.h"

/* Private define ------------------------------------------------------------*/
/* Defines related to Clock configuration */
/* ck_apre=LSIFreq/(ASYNC prediv + 1) with LSIFreq=32768Hz RC */
#define RTC_ASYNCH_PREDIV          ((uint32_t)0x7F)
/* ck_spre=ck_apre/(SYNC prediv + 1) = 1 Hz */
#define RTC_SYNCH_PREDIV           ((uint32_t)0x00FF)

/* Private variables ---------------------------------------------------------*/
/* Private user code ---------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
static void APP_SystemClockConfig(void);
static void APP_RTC_Init(void);
static void APP_RTC_WakeUpTimerConfig(void);
static void APP_EnterStop0(void);

/**
  * @brief  Main program.
  * @param  None
  * @retval int
  */
int main(void)
{
  /* Enable SYSCFG and PWR clock */
  LL_APB1_GRP2_EnableClock(LL_APB1_GRP2_PERIPH_SYSCFG);
  LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_PWR);

  /* Configure system clock */
  APP_SystemClockConfig();

  /* Initialize LED */
  BSP_LED_Init(LED_GREEN);

  /* Initialize BUTTON */
  BSP_PB_Init(BUTTON_KEY,BUTTON_MODE_GPIO);
  
  /* Initialize RTC */
  APP_RTC_Init();
  
  /* Turn on LED */
  BSP_LED_On(LED_GREEN);
  
  /* Wait for the button to be pressed */
  while(BSP_PB_GetState(BUTTON_KEY) == 0);

  /* Configure the WakeUp Timer*/
  APP_RTC_WakeUpTimerConfig();

   /* Turn off LED */
  BSP_LED_Off(LED_GREEN);

  while (1)
  {
    /* Enter stop mode */
    APP_EnterStop0();
  }
}

/**
  * @brief  Configure system clock
  * @param  None
  * @retval None
  */
static void APP_SystemClockConfig(void)
{
  /* Enable HSI */
  LL_RCC_HSI_Enable();
  while(LL_RCC_HSI_IsReady() != 1)
  {
  }
  /* Enable access to the backup domain */
  LL_PWR_EnableBkUpAccess();
  
  /* Reset backup domain */
  LL_RCC_ForceBackupDomainReset();
  LL_RCC_ReleaseBackupDomainReset();
  
  /* Enable LSI */
  LL_RCC_LSI_Enable();
  
  /* Wait till LSI is ready */
  while(LL_RCC_LSI_IsReady() != 1)
  {
  }
  
  /* Set AHB prescaler: HCLK = SYSCLK */
  LL_RCC_SetAHBPrescaler(LL_RCC_SYSCLK_DIV_1);

  /* Select HSISYS as system clock source */
  LL_RCC_SetSysClkSource(LL_RCC_SYS_CLKSOURCE_HSISYS);
  while(LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_HSISYS)
  {
  }

  /* Set APB prescaler: PCLK = HCLK */
  LL_RCC_SetAPB1Prescaler(LL_RCC_APB1_DIV_1);
  LL_Init1msTick(8000000);

  /* Update the SystemCoreClock global variable(which can be updated also through SystemCoreClockUpdate function) */
  LL_SetSystemCoreClock(8000000);
  
  /* Set RTC Clock Source */
  LL_RCC_SetRTCClockSource(LL_RCC_RTC_CLKSOURCE_LSI);
  
  /* Enable RTC */
  LL_RCC_EnableRTC();
}

/**
  * @brief RTC Initialization Function
  * @param None
  * @retval None
  */
static void APP_RTC_Init(void)
{
  LL_RTC_InitTypeDef RTC_InitStruct = {0};

  /* RTC interrupt Init */
  NVIC_SetPriority(RTC_TAMP_IRQn, 0);
  NVIC_EnableIRQ(RTC_TAMP_IRQn);

  /* Initialize RTC and set the Time and Date */
  RTC_InitStruct.HourFormat = LL_RTC_HOURFORMAT_24HOUR;
  RTC_InitStruct.AsynchPrescaler = RTC_ASYNCH_PREDIV;
  RTC_InitStruct.SynchPrescaler = RTC_SYNCH_PREDIV;
  LL_RTC_Init(RTC, &RTC_InitStruct);

  /* Disable the WakeUpTimer */
  LL_RTC_DisableWriteProtection(RTC);
  LL_RTC_WAKEUP_Disable(RTC);
  LL_RTC_DisableIT_WUT(RTC);
  LL_RTC_EnableWriteProtection(RTC);
}

/**
  * @brief  Configure WakeUp Timer
  * @param  None
  * @retval None
  */
static void APP_RTC_WakeUpTimerConfig(void)
{
  LL_RTC_DisableWriteProtection(RTC);
  
  /*  Select WakeUpTimer clock */
  LL_RTC_WAKEUP_SetClock(RTC, LL_RTC_WAKEUPCLOCK_CKSPRE);
  
  /*  Set WakeUpTimer auto-reload value */
  LL_RTC_WAKEUP_SetAutoReload(RTC, 1-1);
  
  /* Enable WakeUpTimer */
  LL_RTC_WAKEUP_Enable(RTC);
  
  /* Enable WakeUpTimer interrupt */
  LL_RTC_EnableIT_WUT(RTC);
  
  LL_RTC_EnableWriteProtection(RTC);
}

/**
  * @brief  Enter stop mode
  * @param  None
  * @retval None
  */
static void APP_EnterStop0(void)
{
  /* Enable PWR clock */
  LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_PWR);

  LL_PWR_SetStopWakeUpFlashDelay(LL_PWR_STOPWAKEUP_FLASH_DELAY_5US);

  /* Set Low-Power mode */
  LL_PWR_SetPowerMode(LL_PWR_MODE_STOP0);
  
  /* STOP mode with DLPR ON */
  LL_PWR_SetVoltageRegulatorMode(LL_PWR_VOLTAGE_REGULATOR_MODE_DLPR);

  /* Set SLEEPDEEP bit of Cortex System Control Register */
  LL_LPM_EnableDeepSleep();

  /* Request Wait For interrupt */
  __WFI();

  LL_LPM_EnableSleep();
}

/**
  * @brief  Error executing function.
  * @param  None
  * @retval None
  */
void APP_ErrorHandler(void)
{
  while (1)
  {
  }
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* Users can add their own printing information as needed,
     for example: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* Infinite loop */
  while (1)
  {
  }
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT Puya *****END OF FILE******************/
