/* Includes ------------------------------------------------------------------*/
#include "FE82160.h"
#include "bsp_uart1.h"
#include "stdio.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
AWK_InitTypeDef AWK_InitStructure;

/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/

void delay(volatile uint32_t n)
{
  while (n--)
    ;
}

int main(void)
{
  SystemCoreClockUpdate();
  uart1_init(24000000, 115200);
  printf("AWK wakeup sleep mode!!\r\n");

  delay(4000000);

  RCC_LSIConfig(LSI_VALUE, RCC_LSI_STARTUP_64CYCLE, ENABLE);
  /* wait LSI clock ready */
  while ((RCC->LSICR & RCC_LSICR_LSIRDY) == RESET)
    ;

  // Enable clock
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOC, ENABLE);
  GPIO_Init(GPIOC, GPIO_Pin_4, GPIO_MODE_OUT | GPIO_OTYPE_PP);

  RCC_APBPeriphClockCmd(RCC_APBPeriph_AWK, ENABLE);

  AWK_InitStructure.AWK_CLK_SEL = AWK_CLK_SEL_LSI;
  AWK_InitStructure.AWK_HSE_PRSC = 0;
  AWK_InitStructure.AWK_DIV_SEL = AWK_CLOCK_DIV_512;
  AWK_InitStructure.AWK_RLOAD_VAL = 200;
  AWK_Init(&AWK_InitStructure);

  /* enable AWK_IRQn interrupt*/
  NVIC_SetPriority(AWK_IRQn, 1);
  NVIC_EnableIRQ(AWK_IRQn);

  AWK_Cmd(ENABLE);

  SCB->SCR &= (~(0x1 << 2));

  /* Infinite loop */
  while (1)
  {
    __WFI();
    printf("AWK wakeup sleep!!\r\n");
  }
}

/**
  * @brief This function handles AWK Interrupt.
  */
void AWK_IRQHandler(void)
{
  AWK->INTCLR |= (0x01 << 0);
  GPIO_ToggleBits(GPIOC, GPIO_Pin_4);
}

#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
