//
#include "Define.h"
//
#include "Switch.h"
//
CSwitch::CSwitch(int pinswitch, bool inverted,
                 TOnStateSwitchChanged onstateswitchchanged)
{   
    FPinSwitch = pinswitch;
    FInverted = inverted;
    FOnStateSwitchChanged = onstateswitchchanged;
    FState = sswUndefined;
}
//
void CSwitch::SetState(EStateSwitch state)
{
    if (state != FState)
    {
        switch (state)
        {
            case sswOff:
                FState = sswOff;
                if (NULL != FOnStateSwitchChanged)
                {
                    FOnStateSwitchChanged(FState);
                }
                break;
            default: // slsOn - security!
                FState = sswOn;
                if (NULL != FOnStateSwitchChanged)
                {
                    FOnStateSwitchChanged(FState);
                }
                break;
        }
    }
}
//
bool CSwitch::ReadLevel(void)
{
    if (HIGH == digitalRead(FPinSwitch))
    {
        if (FInverted)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    if (FInverted)
    {
        return true;
    }
    return false;
}
//
EStateSwitch CSwitch::ReadState(void)
{
    if (DELAY_BOUNCE_MS <= (millis() - FTicksPreset))
    {
        FTicksPreset = millis();
        if (ReadLevel())
        {
            SetState(sswOn);
            return sswOn;
        }
        SetState(sswOff);
        return sswOff;
    }
    return FState;
}
//
bool CSwitch::Open(void)
{
    pinMode(FPinSwitch, INPUT);    
    return true;
}
bool CSwitch::Close(void)
{    
    pinMode(FPinSwitch, INPUT);
    return true;
}
//
void CSwitch::Execute(void)
{    
    ReadState();
}
//