owlps/owlps-positioning/timestamp.cc

137 lines
2.1 KiB
C++

#include "timestamp.hh"
/* *** Constructors *** */
Timestamp::Timestamp()
{
timestamp.tv_sec = 0 ;
timestamp.tv_nsec = 0 ;
}
Timestamp::Timestamp(const struct timespec &source)
{
set_timestamp(source) ;
round_to_ms() ;
}
Timestamp::Timestamp(const uint64_t source_ms)
{
set_timestamp_ms(source_ms) ;
}
Timestamp::Timestamp(const Timestamp &source)
{
timestamp.tv_sec = source.timestamp.tv_sec ;
timestamp.tv_nsec = source.timestamp.tv_nsec ;
}
/* *** Read accessors *** */
uint64_t Timestamp::get_timestamp_ms(void) const
{
return timestamp.tv_sec * 1000 + timestamp.tv_nsec / 1000000 ;
}
/* *** Write accessors *** */
void Timestamp::set_timestamp_ms(const uint64_t source_ms)
{
timestamp.tv_sec = source_ms / 1000 ;
timestamp.tv_nsec = (source_ms - timestamp.tv_sec * 1000) * 1000000 ;
}
/* *** Operations *** */
bool Timestamp::now_ns()
{
if (clock_gettime(CLOCK_REALTIME, &timestamp))
return false ;
return true ;
}
/**
* #timestamp nanosecond field precision is set to ms, but the value
* is still in ns.
*/
void Timestamp::round_to_ms()
{
timestamp.tv_nsec = timestamp.tv_nsec / 1000000 * 1000000 ;
}
bool Timestamp::now()
{
if (! now_ns())
return false ;
round_to_ms() ;
return true ;
}
/* *** Operators *** */
const Timestamp& Timestamp::operator=(const Timestamp &source)
{
if (this == &source)
return *this ;
timestamp.tv_sec = source.timestamp.tv_sec ;
timestamp.tv_nsec = source.timestamp.tv_nsec ;
return *this ;
}
bool Timestamp::operator==(const Timestamp &source) const
{
if (this == &source)
return true ;
return
timestamp.tv_sec == source.timestamp.tv_sec &&
timestamp.tv_nsec == source.timestamp.tv_nsec ;
}
bool Timestamp::operator<(const Timestamp &source) const
{
if (timestamp.tv_sec < source.timestamp.tv_sec)
return true ;
if (timestamp.tv_sec > source.timestamp.tv_sec)
return false ;
// Second values are equal
if (timestamp.tv_nsec < source.timestamp.tv_nsec)
return true ;
return false ;
}
std::ostream& operator<<(std::ostream &os, const Timestamp &t)
{
os << t.get_timestamp_ms() ;
return os ;
}