/**
  ******************************************************************************
  * @file    PMU/STOP/main.c 
  * @author  IOT Development Team
  * @version V1.0.0
  * @date    10-January-2020
  * @brief   Main program body.
  ******************************************************************************
  */ 

/* Includes ------------------------------------------------------------------*/
#include "apm32f10x.h"
#include "platform_config.h"

/** @addtogroup APM32F10x_StdPeriph_Examples
  * @{
  */

/** @addtogroup PMU_STOP
  * @{
  */ 

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
extern __IO uint32_t TimingDelay;
uint8_t HXTStartUpStatus;

/* Private function prototypes -----------------------------------------------*/
void SYSCLKConfig_STOP(void);
void EINT_Configuration(void);
void RTC_Configuration(void);
void NVIC_Configuration(void);
void SysTick_Configuration(void);
void Delay(__IO uint32_t nTime);

/* Private functions ---------------------------------------------------------*/

/**
  * @brief   Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
  /*!< At this stage the microcontroller clock setting is already configured, 
       this is done through SystemInit() function which is called from startup
       file (startup_apm32f10x_xx.s) before to branch to application main.
       To reconfigure the default setting of SystemInit() function, refer to
       system_apm32f10x.c file
     */ 
#if defined (APM32_MINI)	
  /* Initialize LEDs and Key Button mounted on APM3210X-MINI board */       
  APM_MINI_LEDInit(LED2);
  APM_MINI_LEDInit(LED3);
#elif defined(APM32_DISCOVERY)
	/* Initialize Leds mounted on APM32-DISCOVERY board */
	APM_DISCOVERY_LEDInit(LED2);
	APM_DISCOVERY_LEDInit(LED3);
#elif defined(APM32F103V_EVAL)
	APM_EVAL_LEDInit(LED2);
	APM_EVAL_LEDInit(LED3);
#endif

  /* Enable PMU and BAKR clock */
  RCM_EnableAPB1PeriphClock(RCM_APB1_PERIPH_PMU | RCM_APB1_PERIPH_BAKR);

  /* Configure EINT Line to generate an interrupt on falling edge */
  EINT_Configuration();

  /* Configure RTC clock source and prescaler */
  RTC_Configuration();

  /* NVIC configuration */
  NVIC_Configuration();

  /* Configure the SysTick to generate an interrupt each 1 millisecond */
//  SysTick_Configuration();

  
  while (1)
  {
    /* Insert 1.5 second delay */
//    Delay(1500);

    /* Wait till RTC Second event occurs */
    RTC_ClearFlag(RTC_FLAG_SECIF);
    while(RTC_ReadFlag(RTC_FLAG_SECIF) == RESET);

    /* Alarm in 3 second */
    RTC_SetAlarm(RTC_ReadCounter()+ 10);
    /* Wait until last write operation on RTC registers has finished */
    RTC_WaitForLastTask();


    /* Request to enter STOP mode with regulator in low power mode*/
    PMU_EnterSTOPMode(PMU_Regulator_LowPower, PMU_STOPEntry_WFI);
    
    /* At this stage the system has resumed from STOP mode -------------------*/

    /* Configures system clock after wake-up from STOP: enable HXT, PLL and select 
       PLL as system clock source (HXT and PLL are disabled in STOP mode) */
    SYSCLKConfig_STOP();
		
  }
}

/**
  * @brief  Configures system clock after wake-up from STOP: enable HXT, PLL
  *         and select PLL as system clock source.
  * @param  None
  * @retval None
  */
void SYSCLKConfig_STOP(void)
{
  /* Enable HXT */
  RCM_ConfigHXT(RCM_HXT_OPEN);

  /* Wait till HXT is ready */
  HXTStartUpStatus = RCM_WaitHXTReady();

  if(HXTStartUpStatus == SUCCESS)
  {

#ifdef APM32F10X_CL
    /* Enable PLL2 */ 
    RCM_PLL2Cmd(ENABLE);

    /* Wait till PLL2 is ready */
    while(RCM_GetFlagStatus(RCM_FLAG_PLL2RDY) == RESET)
    {
    }

#endif

    /* Enable PLL */ 
    RCM_EnablePLL();

    /* Wait till PLL is ready */
    while(RCM_ReadFlag(RCM_FLAG_PLLRDY) == RESET)
    {
    }

    /* Select PLL as system clock source */
    RCM_ConfigSYSCLK(RCM_SYSCLK_SEL_PLL);

    /* Wait till PLL is used as system clock source */
    while(RCM_GetSYSCLKSource() != RCM_SYSCLK_SEL_PLL)
    {
    }
  }
}

/**
  * @brief  Configures EINT Lines.
  * @param  None
  * @retval None
  */
void EINT_Configuration(void)
{
  EINT_ConfigStruct_T EINT_configStruct;

  /* Configure EINT Line17(RTC Alarm) to generate an interrupt on rising edge */
  EINT_ClearIntFlag(0x20000);
  EINT_configStruct.EINT_Line = 0x20000;
  EINT_configStruct.EINT_Mode = EINT_MODE_Interrupt;
  EINT_configStruct.EINT_Trigger = EINT_Trigger_Rising;
  EINT_configStruct.EINT_LineCmd = ENABLE;
  EINT_Config(&EINT_configStruct);
}

/**
  * @brief  Configures RTC clock source and prescaler.
  * @param  None
  * @retval None
  */
void RTC_Configuration(void)
{
  /* RTC clock source configuration ------------------------------------------*/
  /* Allow access to BAKR Domain */
  PMU_EnableBakrAccess();

  /* Reset Bakr Domain */
  BAKR_Reset();
  
  /* Enable the LXT OSC */
  RCM_ConfigLXT(RCM_LXT_OPEN);
  /* Wait till LXT is ready */
  while(RCM_ReadFlag(RCM_FLAG_LXTRDY) == RESET)
  {
  }

  /* Select the RTC Clock Source */
  RCM_ConfigRTCCLK(RCM_RTCCLK_SEL_LXT);

  /* Enable the RTC Clock */
  RCM_EnableRTCCLK();

  /* RTC configuration -------------------------------------------------------*/
  /* Wait for RTC APB registers synchronisation */
  RTC_WaitForSynchor();

  /* Set the RTC time base to 1s */
  RTC_SetPrescaler(32767);  
  /* Wait until last write operation on RTC registers has finished */
  RTC_WaitForLastTask();

  /* Enable the RTC Alarm interrupt */
  RTC_EnableInterrupt(RTC_INT_ALM);
  /* Wait until last write operation on RTC registers has finished */
  RTC_WaitForLastTask();
}

/**
  * @brief  Configures NVIC and Vector Table base location.
  * @param  None
  * @retval None
  */
void NVIC_Configuration(void)
{
  /* 2 bits for Preemption Priority and 2 bits for Sub Priority */
  NVIC_ConfigPriorityGroup(NVIC_PRIORITY_GROUP_2);  
  NVIC_EnableIRQRequest(RTCAlarm_IRQn, 0x00, 0x00);
}

/**
  * @brief  Configures the SysTick to generate an interrupt each 1 millisecond.
  * @param  None
  * @retval None
  */
void SysTick_Configuration(void)
{
  /* Setup SysTick Timer for 1 msec interrupts  */
  if (SysTick_Config(SystemCoreClock / 1000))
  { 
    /* Capture error */ 
    while (1);
  }
  /* Set SysTick Priority to 3 */
  NVIC_SetPriority(SysTick_IRQn, 0x0C);
}

/**
  * @brief  Inserts a delay time.
  * @param  nTime: specifies the delay time length, in milliseconds.
  * @retval None
  */
void Delay(__IO uint32_t nTime)
{
  TimingDelay = nTime;

  while(TimingDelay != 0);

}

#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)
{ 
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

  /* Infinite loop */
  while (1)
  {
  }
}

#endif

/**
  * @}
  */

/**
  * @}
  */

