/**
 * @file hv_pm51_driver_WDG.c
 * @brief PM51 watch dog driver.
 * @details 
 * @author HiView SoC Software Team
 * @version 0.0.1
 * @date 20230301
 * @copyright Copyright(c),2023-3, Hiview Software. All rights reserved.
 * @par History: 
 * <table>
 * <tr><th>author                     <th>date           <th>description
 * <tr><td>HiView SoC Software Team   <td>20230301       <td>Create and first Version.
 * </table>
**/

#include "hv_pm51_Reg.h"
#include "hv_pm51_driver_UART.h"
#include "hv_pm51_driver_WDG.h"
#include "hv_pm51_driver_Reg.h"
#if MIPS_HEART_MONITOR
#include "hv_pm51_app_Sys.h"
#include "hv_pm51_app_Mailbox.h"
#endif

#if WATCHDOG_ENABLE

#if MIPS_HEART_MONITOR
static xUCHAR8 s_ucHeartMonitorRetry = 0;    
#endif

static iBOOL s_bWdgEn = HV_FALSE;

void Hv_PM51_Wdg_SetTimer(UCHAR8 ucVal)
{
    EWDG = ucVal;
}

void Hv_PM51_Wdg_SetEnable(WdgEn enEnable)
{
    UCHAR8 reg;
    
    reg = ETEA;
    s_bWdgEn = enEnable;
    ETEA = (enEnable == HV_FALSE) ? (reg & 0xFB) : (reg | 0x04);
}

void Hv_PM51_Wdg_Feed(void)
{
    if(!s_bWdgEn) 
    {
        return;
    }
        
#if MIPS_HEART_MONITOR
    if(Hv_PM51_Sys_GetMipsBootState())
    {
        xULONG32 ulRegVal = 0;
        xdata MsgHeader *pstMsgHeader = NULL;
        
        ulRegVal = Hv_PM51_Reg_ReadArray(HS_Standby__standby_mcu_reg__reg_stby_reg0_ADDR);
        pstMsgHeader = (MsgHeader *)&ulRegVal;
        
        if(pstMsgHeader->u8MsgType == E_MAILBOX_CMD_NULL)
        {
            xdata Msg stMsg;
            stMsg.stMsgHeader.u8MsgType = E_MAILBOX_CMD_PM_TO_RISC_HEART_MONITOR;
            stMsg.stMsgHeader.pu8MsgLen[0] = 0;
            Hv_PM51_Mailbox_Send(&stMsg);
            Hv_PM51_Wdg_SetEnable(WDG_DISABLE);
            Hv_PM51_Wdg_SetEnable(WDG_ENABLE);    
        }
        else
        {
            if(s_ucHeartMonitorRetry++ <= 3)
            {
                Hv_PM51_Wdg_SetEnable(WDG_DISABLE);
                Hv_PM51_Wdg_SetEnable(WDG_ENABLE);        
            }
        }
    }
    else
    {
        Hv_PM51_Wdg_SetEnable(WDG_DISABLE);
        Hv_PM51_Wdg_SetEnable(WDG_ENABLE);    
    }    
#else
    Hv_PM51_Wdg_SetEnable(WDG_DISABLE);
    Hv_PM51_Wdg_SetEnable(WDG_ENABLE);    
#endif    
}

#endif
