/src/libiec61850/hal/time/unix/time.c
Line | Count | Source |
1 | | /* |
2 | | * time.c |
3 | | * |
4 | | * Copyright 2013-2024 Michael Zillgith |
5 | | * |
6 | | * This file is part of Platform Abstraction Layer (libpal) |
7 | | * for libiec61850, libmms, and lib60870. |
8 | | */ |
9 | | |
10 | | #include "hal_time.h" |
11 | | #include <time.h> |
12 | | #include <sys/time.h> |
13 | | |
14 | | msSinceEpoch |
15 | | Hal_getTimeInMs() |
16 | 650 | { |
17 | 650 | struct timeval now; |
18 | | |
19 | 650 | gettimeofday(&now, NULL); |
20 | | |
21 | 650 | return ((uint64_t) now.tv_sec * 1000LL) + (now.tv_usec / 1000); |
22 | 650 | } |
23 | | |
24 | | nsSinceEpoch |
25 | | Hal_getTimeInNs() |
26 | 0 | { |
27 | 0 | struct timespec now; |
28 | |
|
29 | 0 | clock_gettime(CLOCK_REALTIME, &now); |
30 | |
|
31 | 0 | nsSinceEpoch nsTime = (nsSinceEpoch)(now.tv_sec) * 1000000000UL; |
32 | 0 | nsTime += (nsSinceEpoch)(now.tv_nsec); |
33 | |
|
34 | 0 | return nsTime; |
35 | 0 | } |
36 | | |
37 | | bool |
38 | | Hal_setTimeInNs(nsSinceEpoch nsTime) |
39 | 0 | { |
40 | 0 | struct timespec tv; |
41 | |
|
42 | 0 | tv.tv_sec = nsTime / 1000000000UL; |
43 | 0 | tv.tv_nsec = nsTime % 1000000000UL; |
44 | |
|
45 | 0 | if (clock_settime(CLOCK_REALTIME, &tv) < 0) { |
46 | 0 | return false; |
47 | 0 | } |
48 | | |
49 | 0 | return true; |
50 | 0 | } |
51 | | |
52 | | msSinceEpoch |
53 | | Hal_getMonotonicTimeInMs() |
54 | 574 | { |
55 | 574 | uint64_t timeVal = 0; |
56 | | |
57 | 574 | struct timespec ts; |
58 | | |
59 | 574 | if (clock_gettime (CLOCK_MONOTONIC, &ts) == 0) |
60 | 574 | { |
61 | 574 | timeVal = ((uint64_t)ts.tv_sec * 1000LL) + (ts.tv_nsec / 1000000); |
62 | 574 | } |
63 | | |
64 | 574 | return timeVal; |
65 | 574 | } |
66 | | |
67 | | nsSinceEpoch |
68 | | Hal_getMonotonicTimeInNs() |
69 | 0 | { |
70 | 0 | uint64_t nsTime = 0; |
71 | |
|
72 | 0 | struct timespec ts; |
73 | |
|
74 | 0 | if (clock_gettime(CLOCK_REALTIME, &ts) == 0) |
75 | 0 | { |
76 | 0 | nsTime = ts.tv_sec * 1000000000UL; |
77 | 0 | nsTime += ts.tv_nsec; |
78 | 0 | } |
79 | |
|
80 | 0 | return nsTime; |
81 | 0 | } |