#include "iwdg.h"

INT32U    g_dog      = 0;
OS_EVENT *iwdg_mutex = NULL;

// 初始化独立看门狗
//  prer:分频数:0~7(只有低3位有效!)
//  rlr:自动重装载值,0~0XFFF.
// 分频因子=4*2^prer.但最大值只能是256!
//  rlr:重装载寄存器值:低11位有效.
// 时间计算(大概):Tout=((4*2^prer)*rlr)/32 (ms).
void iwdg_init(void)
{
    IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable); // 使能对IWDG->PR IWDG->RLR的写

    IWDG_SetPrescaler(IWDG_Prescaler_128); // 设置IWDG分频系数

    IWDG_SetReload(0X9C4); // 设置IWDG装载值

    IWDG_ReloadCounter(); // reload

    IWDG_Enable(); // 使能看门狗
}

void iwdg_feed(INT32U dog)
{
    INT8U  err     = 0;
    INT32U all_dog = UART3_DOG | MISC_DOG;
    // INT32U all_dog = CURRENT_DOG | SOC_DOG | ADC_DOG | INCAN_RX_DOG | INCAN_TX_DOG | INCAN_INFO_DOG | CAN2_TX_DOG | CAN2_RX_DOG | FAULT_DIG_DOG | UART1_DOG | UART3_DOG | BALANCE_DOG | MISC_DOG | PROCESS_DOG;
    OSMutexPend(iwdg_mutex, 0, &err);
    g_dog |= dog;
    OSMutexPost(iwdg_mutex);
    if (g_dog == all_dog)
    {
        /* 重载IWDG计数 */
        IWDG_ReloadCounter();
        OSMutexPend(iwdg_mutex, 0, &err);
        g_dog = 0;
        OSMutexPost(iwdg_mutex);
    }
}

void iwdg_disable(void)
{
}
