/***************************************************************
 * PrUtility.cpp
 *
 * This is an implementation of utility methods.
 *
 ****************************************************************/

/*
 * modification history
 *----------------------
 *
 * 02/16/03: Weyn Ong: Version for QNX 6
 * 11/02/97: K.C. Chang: created.
 */

#include "PrUtility.h"

#include <time.h>
#include <sys/neutrino.h>

// set the timer resolution for QNX
double PrUtility::resolution(double period)
{
    /* Set the resolution */
/* MIG4NTO     qnx_ticksize Use ClockPeriod() instead.  It behaves like */
/* MIG4NTO                  qnx_ticksize() with the _TICKSIZE_CLOSEST flag. */
//    qnx_ticksize( (long)(period*PR_BILLION), _TICKSIZE_CLOSEST );
    struct _clockperiod clockPeriod;
    clockPeriod.nsec = (long) (period*PR_BILLION);
    clockPeriod.fract = 0;
    ClockPeriod( CLOCK_REALTIME, &clockPeriod, NULL, 0 ); 

    struct timespec res;
    
    if (clock_getres(CLOCK_REALTIME, &res) == -1) 
      {
	printf ("resolution(): Unable to get clock resolution\n");
	return 0.0;
      }
    else
      {
	//	printf("%f sec\n", res.tv_sec + res.tv_nsec/(double)PR_BILLION);
	return res.tv_sec + res.tv_nsec/(double)PR_BILLION;
      }
}

// returns the global time in sec since 1/1/1970
double PrUtility::time()
{
    struct timespec t;

    if (clock_gettime(CLOCK_REALTIME, &t) == -1) 
      printf("time(): Unable to get clock time\n");

    return (t.tv_sec + t.tv_nsec/(double)PR_BILLION);
}

// blocks current process for miliSec
int PrUtility::miliBlock(long miliSec)
{
    struct timespec rqtp;
    rqtp.tv_sec= miliSec/PR_THOUSAND;
    rqtp.tv_nsec=(miliSec - rqtp.tv_sec*PR_THOUSAND)*PR_MILLION;

    if (nanosleep(&rqtp,NULL) == -1)
      return PR_UTILITY_ERROR;

    return PR_UTILITY_OK;
}

// blocks current process for microSec
int PrUtility::microBlock(long microSec)
{
    struct timespec rqtp;
    rqtp.tv_sec= microSec/PR_MILLION;
    rqtp.tv_nsec=(microSec - rqtp.tv_sec*PR_MILLION)*PR_THOUSAND;

    if (nanosleep(&rqtp,NULL) == -1)
      return PR_UTILITY_ERROR;

    return PR_UTILITY_OK;
}

// blocks current process for nanoSec
int PrUtility::nanoBlock(long nanoSec)
{
    struct timespec rqtp;
    rqtp.tv_sec= nanoSec/PR_BILLION;
    rqtp.tv_nsec=(nanoSec - rqtp.tv_sec*PR_BILLION);

    if (nanosleep(&rqtp,NULL) == -1)
      return PR_UTILITY_ERROR;

    return PR_UTILITY_OK;
}
