#include "hal_low_power.h"
#include "hc32_ll_pwc.h"
#include "hc32_ll.h"

#include "FreeRTOS.h"
#include "task.h"


/**
 * @brief  Whether ready to entry stop mode.
 * @param  None
 * @retval int32_t:
 * @note Ensure DMA stops transmit and no flash erase/program operation.
 */
int32_t stop_is_ready(void)
{
    int32_t i32Ret = LL_OK;
    uint8_t tmp1;
    uint8_t tmp2;
    uint8_t tmp3;

    tmp1 = (uint8_t)((READ_REG32(CM_EFM->FSR) & EFM_FSR_RDY) == EFM_FSR_RDY);

    tmp2 = (uint8_t)((READ_REG32(CM_DMA1->CHSTAT) & DMA_CHSTAT_DMAACT) == 0x00U);
    tmp3 = (uint8_t)((READ_REG32(CM_DMA2->CHSTAT) & DMA_CHSTAT_DMAACT) == 0x00U);

    if (0U == (tmp1 & tmp2 & tmp3)) {
        i32Ret = LL_ERR_NOT_RDY;
    }
    return i32Ret;
}


/**
 * @brief  MCU behavior config for stop mode.
 * @param  None
 * @retval None
 */
void sleep_config(void)
{
    stc_pwc_stop_mode_config_t stcStopConfig;

    (void)PWC_STOP_StructInit(&stcStopConfig);

    stcStopConfig.u16ExBusHold = PWC_STOP_EXBUS_HIZ;
    stcStopConfig.u16Clock = PWC_STOP_CLK_KEEP;
    stcStopConfig.u16FlashWait = PWC_STOP_FLASH_WAIT_ON;

    (void)PWC_STOP_Config(&stcStopConfig);

    /* Wake-up source config (EXINT Ch.6 here) */
    INTC_WakeupSrcCmd(INTC_STOP_WKUP_EXTINT_CH0, ENABLE);//唤醒脚配置
		INTC_WakeupSrcCmd(INTC_STOP_WKUP_EXTINT_CH1, ENABLE);//唤醒脚配置
		INTC_WakeupSrcCmd(INTC_STOP_WKUP_EXTINT_CH8, ENABLE);//唤醒脚配置
	  INTC_WakeupSrcCmd(INTC_STOP_WKUP_EXTINT_CH9, ENABLE);//唤醒脚配置
		INTC_WakeupSrcCmd(INTC_STOP_WKUP_EXTINT_CH10, ENABLE);//唤醒脚配置
		INTC_WakeupSrcCmd(INTC_STOP_WKUP_EXTINT_CH11, ENABLE);//唤醒脚配置
	  INTC_WakeupSrcCmd(INTC_STOP_WKUP_EXTINT_CH12, ENABLE);//唤醒脚配置
		INTC_WakeupSrcCmd(INTC_STOP_WKUP_EXTINT_CH13, ENABLE);//唤醒脚配置
		INTC_WakeupSrcCmd(INTC_STOP_WKUP_EXTINT_CH14, ENABLE);//唤醒脚配置
}


 
void test_task3(void *pvParameters)
{
		uint8_t u8Count;
		vTaskDelay(3000);
		static uint16_t cnt = 0;
		while(1)
		{
			if (LL_OK == stop_is_ready()) 
			{									
				u8Count = 10U;
				vTaskDelay(5000);
				GPIO_TogglePins(GPIO_PORT_A, GPIO_PIN_02);
				SysTick_Suspend();				
				PWC_STOP_Enter(PWC_STOP_WFI);				
			}		
			cnt++;
			printf("cnt=%d\n",cnt);
			SysTick_Resume();
			vTaskDelay(5000);
		}
}
 
//进入休眠的时候不允许有flash读写，DMA等操作