QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
MonotonicClock.h
Go to the documentation of this file.
1#pragma once
2
3#include <chrono>
4#include <cstdint>
5#include <optional>
6
9namespace MonotonicClock {
10inline uint64_t nowUs()
11{
12 return static_cast<uint64_t>(
13 std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now().time_since_epoch())
14 .count());
15}
16
18template <typename Rep, typename Period>
19constexpr std::optional<std::chrono::duration<Rep, Period>> age(std::chrono::duration<Rep, Period> timestamp,
20 std::chrono::duration<Rep, Period> now)
21{
22 if (timestamp <= timestamp.zero() || timestamp > now) {
23 return std::nullopt;
24 }
25 return now - timestamp;
26}
27
28constexpr std::optional<std::chrono::microseconds> age(uint64_t timestampUs, uint64_t nowUs)
29{
30 return age(std::chrono::microseconds(timestampUs), std::chrono::microseconds(nowUs));
31}
32
34constexpr std::chrono::microseconds remaining(uint64_t timestampUs, uint64_t nowUs, std::chrono::microseconds lifetime)
35{
36 const auto receiptAge = age(timestampUs, nowUs);
37 if (!receiptAge || *receiptAge >= lifetime) {
38 return std::chrono::microseconds::zero();
39 }
40 return lifetime - *receiptAge;
41}
42
44constexpr bool fresh(uint64_t timestampUs, uint64_t nowUs, std::chrono::microseconds lifetime)
45{
46 return remaining(timestampUs, nowUs, lifetime) > std::chrono::microseconds::zero();
47}
48
50constexpr bool withinAge(uint64_t timestampUs, uint64_t nowUs, std::chrono::microseconds maximumAge)
51{
52 const auto receiptAge = age(timestampUs, nowUs);
53 return receiptAge && *receiptAge <= maximumAge;
54}
55} // namespace MonotonicClock
constexpr std::optional< std::chrono::duration< Rep, Period > > age(std::chrono::duration< Rep, Period > timestamp, std::chrono::duration< Rep, Period > now)
Age of timestamp at now, both in the same unit; empty for a missing or future timestamp.
constexpr bool withinAge(uint64_t timestampUs, uint64_t nowUs, std::chrono::microseconds maximumAge)
Whether a receipt is at most maximumAge old, its limit included.
constexpr bool fresh(uint64_t timestampUs, uint64_t nowUs, std::chrono::microseconds lifetime)
Whether a receipt is younger than lifetime.
uint64_t nowUs()
constexpr std::chrono::microseconds remaining(uint64_t timestampUs, uint64_t nowUs, std::chrono::microseconds lifetime)
Time left before a receipt reaches lifetime; zero for a missing, future or expired one.