/******************************************************************************/
/* Williams Advanced Engineering Limited                     Copyright(C) 2021*/
/* Grove                                                  All rights reserved */
/*                                                                            */
/******************************************************************************/


#include "Ios_BoardExtWdgMngt.h"

/*------------------------------------------------------------*/
/*          Local Global Definition                           */
/*------------------------------------------------------------*/
static uint16_t wPeriodCounter = 0;
static uint16_t wTimeSinceLastKick = 0;


//For correct operation we need to have a rising edge on the WDI pin between Tboundary _max and Twindow_min so between 2.35ms and 2sec.
//This function should run at 10ms.
//The pulse will be 500ms period with 10ms ON at start

void fnIosKickExternalWdg(void)
{

    if(wPeriodCounter < (uint16)(WDG_KICK_PULSEHIGH_LENGTH_MS))
    {
        fnIosSetDigitalChannel(ExternalWDG, (uint8) ON);
        wTimeSinceLastKick = 0;
    }
    else
    {
        fnIosSetDigitalChannel(ExternalWDG, (uint8) OFF);
    }


    wPeriodCounter += (uint16_t)EXT_WDG_KICK_FUNC_CALL_RATE_MS;
    wTimeSinceLastKick += (uint16_t)EXT_WDG_KICK_FUNC_CALL_RATE_MS;
    wPeriodCounter %= ((uint16_t)(WDG_KICK_PULSE_PERIOD_MS));

}

// Return time since last rising edge on the WDI pin
uint16_t fnIosGetExtWgdLastKick(void)
{
    return ((uint16_t)wTimeSinceLastKick);
}

void fnIosForceExtrernalWdgKick(void)
{
    uint16_t wCounter = 0;

    if((uint8_t)OFF == (uint8_t)fnIosGetDigitalChannel(ExternalWDG))
    {
        //Set pin ON
        fnIosSetDigitalChannel(ExternalWDG, (uint8_t) ON);

        //Wait
        while(wCounter++ < ((uint16_t)WDG_FORCEKICK_ON_PULSE));

    }

    //Set pin OFF
    fnIosSetDigitalChannel(ExternalWDG, (uint8_t) OFF);
}




