
/******************************************************************************
*@file  : app.c
*@brief : application
******************************************************************************/

#include "app.h"   


IWDT_HandleTypeDef IWDT_Handle;

/******************************************************************************
*@brief : app test
*@param : none
*@return: none
******************************************************************************/
void APP_Test(void)
{
    uint32_t mode;
    RCC_OscInitTypeDef      RCC_OscInitStruct = {0};
    
	BSP_LED_Init();
    
    HAL_PMU_Init();
	
    BSP_LED_On();
    HAL_Delay(2000);
    
	/* 使能：RC32K */
    RCC_OscInitStruct.OscType = RCC_OSCTYPE_RC32K;
    RCC_OscInitStruct.RC32K = ENABLE;
    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
    {
        while (1);
    }  
	
	/* 使能：IWDT复位导致系统复位 */
	__HAL_RCC_IWDTRSTTOSYSRST_ENABLE();
    
    __HAL_RCC_EXTI_CLK_ENABLE();
    
    IWDT_Handle.Instance = IWDT;
    IWDT_Handle.Init.Prescaler  = IWDT_CLOCK_PRESCALER_256;
    IWDT_Handle.Init.Reload     = 0xfff;//250;
    IWDT_Handle.Init.Window     = 0xfff;//250;
    IWDT_Handle.Init.Wakeup     = 0xcff;
    IWDT_Handle.Init.WakeupMode = IWDT_WAKEUP_MODE_IT;
    
    HAL_IWDT_Init(&IWDT_Handle);

	NVIC_ClearPendingIRQ(IWDT_WAKEUP_IRQn);
	NVIC_SetPriority(IWDT_WAKEUP_IRQn, 0x00);
	NVIC_EnableIRQ(IWDT_WAKEUP_IRQn);
    
    HAL_IWDT_Refresh(&IWDT_Handle);
    
    mode = PMU_CTL0_LPMS_STOP1;
    while(1)
    {
        printfS("mcu enter stop mode!\r\n"); 
        
        HAL_SuspendTick();
        HAL_EXTI_ClearAllPending();
        
        HAL_RCC_SwitchSYSCLK(RCC_SYSCLKSOURCE_RC64M);
        
        HAL_PMU_EnterStopMode(WAIT_FOR_INT, mode);
        
        SystemClock_Config();
        
		printfS("mcu has exited stop mode!\r\n");
		printfS("\r\n");

        HAL_IWDT_Refresh(&IWDT_Handle);
    };
}

void HAL_IWDT_Callback(IWDT_HandleTypeDef *hiwdt)
{
    BSP_LED_Toggle();
}
