//
//--------------------------------
//  Library TimeRelative
//--------------------------------
//
#include "DefinitionSystem.h"
//
#if defined(DISPATCHER_SYSTEM)
//
#include "TimeRelative.h"
#include "Command.h"
#include "DispatcherSystem.h"
//
extern CCommand Command;
extern CDispatcherSystem DispatcherSystem;
//
CTimeRelative::CTimeRelative(String id, Boolean messageon)
{
  FID = id;
  FState = strZero;
  FMessageOn = messageon;
  FTimePeriodms = INIT_TIMEPERIOD_MS;
  FTimeStartms = INIT_TIMEPERIOD_MS;
}

EStateTimeRelative CTimeRelative::GetState(void)
{
  return FState;
}  

Boolean CTimeRelative::Open()
{
  FState = strZero;
  return true;
}

Boolean CTimeRelative::Close()
{
  FState = strZero;
  return true;
}
//
void CTimeRelative::SetTimeStartActual(void)
{
  FTimeStartms = (Float32)micros() / 1000.0f;
}
Float32 CTimeRelative::GetTimePeriodms(void)
{
  return FTimePeriodms;
}
Float32 CTimeRelative::GetTimeStartms(void)
{
  return FTimeStartms;
}
Float32 CTimeRelative::GetTimeActualms(void)
{
  return (Float32)micros() / 1000.0f - FTimeStartms;
}
//
UInt32 CTimeRelative::GetTimePeriodus(void)
{
  return (UInt32)(1000.0f * FTimePeriodms);  
}
UInt32 CTimeRelative::GetTimeStartus(void)
{
  return (UInt32)(1000.0f * FTimeStartms);
}
UInt32 CTimeRelative::GetTimeActualus(void)
{
  return (UInt32)(micros() - GetTimeStartus());
}
//
//-------------------------------------------------------------------------------
//  TimeRelative - Wait
//-------------------------------------------------------------------------------
//
void CTimeRelative::Wait_Start(Float32 timeperiodms)
{
  FTimePeriodms = timeperiodms;
  FState = strInit;
}

void CTimeRelative::Wait_Abort(void)
{
  FState = strZero;
}

Boolean CTimeRelative::Wait_Execute(void)
{
  switch (FState)
  {
    case strZero:
      return false;
    case strInit:
      SetTimeStartActual();
      if (FMessageOn)
      {        
        sprintf(Command.GetBuffer(), "WTR %s 1", FID.c_str());
        DispatcherSystem.WriteEvent(Command.GetBuffer());
      }
      FState = strBusy;
      return true;
    case strBusy:
      if (FTimePeriodms <= GetTimeActualms())
      {
        if (FMessageOn)
        {
          sprintf(Command.GetBuffer(), "WTR %s 0", FID.c_str());
          DispatcherSystem.WriteEvent(Command.GetBuffer());
        }
        FState = strZero;
        return false;
      }
      return true;  
  }
  return false;
}
//
#endif // DISPATCHER_SYSTEM
//