diff --git a/hal/inc/hal_time.h b/hal/inc/hal_time.h index 0e57d338..8944aa19 100644 --- a/hal/inc/hal_time.h +++ b/hal/inc/hal_time.h @@ -1,7 +1,7 @@ /* * time.c * - * Copyright 2013, 2014 Michael Zillgith + * Copyright 2013-2020 Michael Zillgith * * This file is part of libIEC61850. * @@ -46,6 +46,9 @@ extern "C" { * @{ */ +typedef uint64_t nsSinceEpoch; +typedef uint64_t msSinceEpoch; + /** * Get the system time in milliseconds. * @@ -54,9 +57,23 @@ extern "C" { * * \return the system time with millisecond resolution. */ -PAL_API uint64_t +PAL_API msSinceEpoch Hal_getTimeInMs(void); +/** + * Get the system time in nanoseconds. + * + * The time value returned as 64-bit unsigned integer should represent the nanoseconds + * since the UNIX epoch (1970/01/01 00:00 UTC). + * + * \return the system time with nanosecond resolution. + */ +PAL_API nsSinceEpoch +Hal_getTimeInNs(); + +PAL_API bool +Hal_setTimeInNs(nsSinceEpoch nsTime); + /*! @} */ /*! @} */ diff --git a/hal/time/unix/time.c b/hal/time/unix/time.c index f7951fde..6565da33 100644 --- a/hal/time/unix/time.c +++ b/hal/time/unix/time.c @@ -39,7 +39,7 @@ Hal_getTimeInMs() #include -uint64_t +msSinceEpoch Hal_getTimeInMs() { struct timeval now; @@ -49,5 +49,34 @@ Hal_getTimeInMs() return ((uint64_t) now.tv_sec * 1000LL) + (now.tv_usec / 1000); } +nsSinceEpoch +Hal_getTimeInNs() +{ + struct timespec now; + + clock_gettime(CLOCK_REALTIME, &now); + + nsSinceEpoch nsTime = now.tv_sec * 1000000000UL; + nsTime += now.tv_nsec; + + return nsTime; +} + +bool +Hal_setTimeInNs(nsSinceEpoch nsTime) +{ + struct timespec tv; + + tv.tv_sec = nsTime / 1000000000UL; + tv.tv_nsec = nsTime % 1000000000UL; + + if (clock_settime(CLOCK_REALTIME, &tv) < 0) { + return false; + } + + return true; +} + + #endif