//#include <proc/p32mx440f256h.h>

#include "ChaletPowerRelay.h"
#include "BoardCfg.h"
#include "timer.h"

#define PIN_ACTIVE 1
#define PIN_INACTIVE 0

bool PowerRelayState;

void InitChaletPowerRelay()
{
    POWER_RELAY_ON_PIN = PIN_INACTIVE;
    POWER_RELAY_OFF_PIN = PIN_INACTIVE;
    PowerRelayState = CHALET_POWER_RELAY_UNKNOWN_STATE;
    TimerStop(CHALET_POWER_RELAY_COIL_TIMER);
}

void ChaletPowerRelayTick()
{
    if(CHALET_12V_PRESENCE_PIN == CHALET_12V_POWER_STATE_ON)
    {
		if(PowerRelayState == CHALET_POWER_RELAY_OFF_STATE)
		{
			printf("Inverter turned ON\n");
		}
        PowerRelayState = CHALET_POWER_RELAY_ON_STATE;
    }
    else
    {
		if(PowerRelayState == CHALET_POWER_RELAY_ON_STATE)
		{
			printf("Inverter turned OFF\n");
		}
        PowerRelayState = CHALET_POWER_RELAY_OFF_STATE;
    }
    
    if(IsTimerRunning(CHALET_POWER_RELAY_COIL_TIMER) == true)
    {
        if(IsTimerExpired(CHALET_POWER_RELAY_COIL_TIMER))
        {
            POWER_RELAY_ON_PIN = PIN_INACTIVE;
            POWER_RELAY_OFF_PIN = PIN_INACTIVE;
            TimerStop(CHALET_POWER_RELAY_COIL_TIMER);
        }
    }
    
    if(IsTimerExpired(CHALET_POWER_RELAY_AUTOTURNOFF_TIMER))
    {
        ChaletPowerRelayTurnOff();
    }
}

void ChaletPowerRelayKickTimer()
{
    TimerStartSeconds(CHALET_POWER_RELAY_AUTOTURNOFF_TIMER,CHALET_OFFLINE_POWER_RELAY_RESET_TIMEOUT);
}

bool ChaletPowerRelayTurnOn()
{
    POWER_RELAY_ON_PIN = PIN_ACTIVE;
    TimerStart(CHALET_POWER_RELAY_COIL_TIMER,CHALET_POWER_RELAY_COIL_TIMEOUT);
 //   PowerRelayState = CHALET_POWER_RELAY_ON_STATE;
    return true;
}

bool ChaletPowerRelayTurnOff()
{
    POWER_RELAY_OFF_PIN = PIN_ACTIVE;
    TimerStart(CHALET_POWER_RELAY_COIL_TIMER,CHALET_POWER_RELAY_COIL_TIMEOUT);
 //   PowerRelayState = CHALET_POWER_RELAY_OFF_STATE;
    return true;
}

char GetChaletPowerRelayState()
{
    return (char)PowerRelayState;
}