// 1ms timer

#ifdef WIN32

#include "Timer.h"

// multimedia timer configuration
static TIMECAPS timecaps;
// multimedia timer handle
static MMRESULT mmtimerhandle;


/**************************************************************************
DOES:    Initializer - performs initialization
RETURNS: nothing
***************************************************************************/ 
void Timer_Init (
  void
  )
{
  // get current multimedia timer settings
  if (timeGetDevCaps(&timecaps, sizeof(TIMECAPS)) != TIMERR_NOERROR) return;

  // initialize multimedia timer
  if (timeBeginPeriod(timecaps.wPeriodMin) != TIMERR_NOERROR) return;

  // start multimedia timer with 1ms resolution
  mmtimerhandle = timeSetEvent(1, 0, NULL, 0, TIME_PERIODIC);
}

/**************************************************************************
DOES:    Close - performs cleanup
RETURNS: nothing
***************************************************************************/ 
void Timer_Close (
  void
  )
{
  // stop multimedia timer
  if (mmtimerhandle) timeKillEvent(mmtimerhandle);

  // finish with multimedia timer
  timeEndPeriod(timecaps.wPeriodMin);
}

/**************************************************************************
DOES:    Pauses execution for specified number of milliseconds
RETURNS: nothing
***************************************************************************/
void Timer_Sleep
  (
  unsigned long milliseconds                               // milliseconds to sleep
  )
{
  Sleep(milliseconds);
}

/**************************************************************************
DOES:    This function reads a 1 millisecond timer tick. The timer tick
         must be a uint16_t and must be incremented once per millisecond.
RETURNS: 1 millisecond timer tick
**************************************************************************/
uint16_t Timer_GetTime (
  void
  )
{
  return (uint16_t)(timeGetTime() & 0x0000FFFF);
}


/**************************************************************************
DOES:    This function compares a uint16_t timestamp to the internal 
         timer tick and returns 1 if the timestamp expired/passed.
RETURNS: 1 if timestamp expired/passed
         0 if timestamp is not yet reached
NOTES:   The maximum timer runtime measurable is 0x8000 (about 32 seconds).
         For the usage in MicroCANopen that is sufficient. 
**************************************************************************/
uint8_t Timer_IsTimeExpired (
  uint16_t timestamp
  )
{
uint16_t time_now;

  time_now = Timer_GetTime();
  if (time_now >= timestamp)
  {
    if ((time_now - timestamp) < 0x8000)
      return 1;
    else
      return 0;
  }
  else
  {
    if ((timestamp - time_now) >= 0x8000)
      return 1;
    else
      return 0;
  }
}

#endif // WIN32
