/*!
 * @file        main.c
 *
 * @brief       Main program body
 *
 * @version     V1.0.2
 *
 * @date        2023-03-31
 *
 * @attention
 *
 *  Copyright (C) 2023 Geehy Semiconductor
 *
 *  You may not use this file except in compliance with the
 *  GEEHY COPYRIGHT NOTICE (GEEHY SOFTWARE PACKAGE LICENSE).
 *
 *  The program is only for reference, which is distributed in the hope
 *  that it will be useful and instructional for customers to develop
 *  their software. Unless required by applicable law or agreed to in
 *  writing, the program is distributed on an "AS IS" BASIS, WITHOUT
 *  ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the GEEHY SOFTWARE PACKAGE LICENSE for the governing permissions
 *  and limitations under the License.
 */

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

/** @addtogroup Examples
  @{
*/

/** @addtogroup WWDT
  @{
*/

/** @defgroup WWDT_Macros Macros
  @{
*/

/* WWDT counter */
#define WWDT_COUNTER_VALUE          (110)
/* WWDT window value */
#define WWDT_WINDOW_VALUE           (90)

/**@} end of group WWDT_Macros */

/** @defgroup WWDT_Functions Functions
  @{
*/

/* Process when reset occured */
void ResetProc(void);

/*!
 * @brief       Main program
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
int main(void)
{
    APM_MINI_LEDInit(LED2);
    APM_MINI_LEDInit(LED3);
    APM_MINI_PBInit(BUTTON_KEY1, BUTTON_MODE_EINT);
    APM_DelayInit(APM_DELAY_MS);
    NVIC_EnableIRQRequest(EINTD_IRQn, 0X01);

    ResetProc();
    /*
     *  WWDT Clock = 48MHZ;
     *  Watchdog Window     = (WWDT_COUNTER_VALUE - 63) * 1 step
     *                      = (110 - 63) * (12288 / 48)
     *                      = 12.032ms
     *  Non Allowed Window  = (WWDT_COUNTER_VALUE - WWDT_WINDOW_VALUE) * 1 step
     *                      = (110 - 90) * (12288 / 48)
     *                      = 5.12ms
    */
    WWDT_Config(WWDT_COUNTER_VALUE, WWDT_WINDOW_VALUE);

    while(1)
    {
        while(WWDT_ReadCounter() >= WWDT_WINDOW_VALUE);
        WWDT_SetCounter(WWDT_COUNTER_VALUE);
    }
}

/*!
 * @brief       Key interrupt sever routine
 *
 * @param       None
 *
 * @retval      None
 *
 * @note        This functions need put into EINTD_IRQHandler
 */
void Key_Isr(void)
{
    WWDT_SetCounter(WWDT_COUNTER_VALUE);

    EINT_ClearIntFlag(EINT_PORT_D);
}

/*!
 * @brief       Reset process
 *
 * @param       None
 *
 * @retval      None
 */
void ResetProc(void)
{
    uint8_t i;

    if(RCM_ReadResetFlag(RCM_RTS_FLAG_WWDTRST) == SET)
    {
        RCM_ClearResetFlag(RCM_RTS_FLAG_WWDTRST);
        for(i = 0; i < 5; i++)
        {
            APM_Delay(500);
            APM_MINI_LEDToggle(LED2);
        }
    }
}

/**@} end of group WWDT_Functions */
/**@} end of group WWDT */
/**@} end of group Examples */
