Coverage Report

Created: 2026-08-13 06:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/open62541/arch/posix/clock_posix.c
Line
Count
Source
1
/* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
2
 * See http://creativecommons.org/publicdomain/zero/1.0/ for more information.
3
 *
4
 *    Copyright 2016-2017 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
5
 *    Copyright 2017 (c) Stefan Profanter, fortiss GmbH
6
 *    Copyright 2017 (c) Thomas Stalder, Blue Time Concept SA
7
 */
8
9
#include <open62541/types.h>
10
11
/* Note that the EventLoop plugin provides its own internal time source (which
12
 * is typically just the normal system time). All internal access to the time
13
 * source should be through the EventLoop. The below is therefore for developer
14
 * convenience to just use UA_DateTime_now(). */
15
16
#if defined(UA_ARCHITECTURE_POSIX)
17
18
#include <time.h>
19
#include <sys/time.h>
20
21
#if defined(__APPLE__) && defined(__MACH__)
22
# include <mach/clock.h>
23
# include <mach/mach.h>
24
#endif
25
26
0
UA_DateTime UA_DateTime_now(void) {
27
0
    struct timeval tv;
28
0
    gettimeofday(&tv, NULL);
29
0
    return (tv.tv_sec * UA_DATETIME_SEC) +
30
0
        (tv.tv_usec * UA_DATETIME_USEC) +
31
0
        UA_DATETIME_UNIX_EPOCH;
32
0
}
33
34
/* Credit to https://stackoverflow.com/questions/13804095/get-the-time-zone-gmt-offset-in-c */
35
0
UA_Int64 UA_DateTime_localTimeUtcOffset(void) {
36
0
    time_t rawtime = time(NULL);
37
0
    struct tm gbuf;
38
0
    struct tm *ptm = gmtime_r(&rawtime, &gbuf);
39
    /* Request mktime() to look up dst in timezone database */
40
0
    ptm->tm_isdst = -1;
41
0
    time_t gmt = mktime(ptm);
42
0
    return (UA_Int64) (difftime(rawtime, gmt) * UA_DATETIME_SEC);
43
0
}
44
45
0
UA_DateTime UA_DateTime_nowMonotonic(void) {
46
#if defined(__APPLE__) && defined(__MACH__)
47
    /* OS X does not have clock_gettime, use clock_get_time */
48
    clock_serv_t cclock;
49
    mach_timespec_t mts;
50
    host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
51
    clock_get_time(cclock, &mts);
52
    mach_port_deallocate(mach_task_self(), cclock);
53
    return (mts.tv_sec * UA_DATETIME_SEC) + (mts.tv_nsec / 100) + UA_DATETIME_UNIX_EPOCH;
54
#elif !defined(CLOCK_MONOTONIC_RAW)
55
    struct timespec ts;
56
    clock_gettime(CLOCK_MONOTONIC, &ts);
57
    return (ts.tv_sec * UA_DATETIME_SEC) + (ts.tv_nsec / 100) + UA_DATETIME_UNIX_EPOCH;
58
#else
59
0
    struct timespec ts;
60
0
    clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
61
0
    return (ts.tv_sec * UA_DATETIME_SEC) + (ts.tv_nsec / 100) + UA_DATETIME_UNIX_EPOCH;
62
0
#endif
63
0
}
64
65
#endif /* UA_ARCHITECTURE_POSIX */