blob: 1e520b1586efc08d451fb58a6a368e91abd37835 [file] [log] [blame]
John Park33858a32018-09-28 23:05:48 -07001#include "aos/util/phased_loop.h"
brians343bc112013-02-10 01:53:46 +00002
Austin Schuhf257f3c2019-10-27 21:00:43 -07003#include "glog/logging.h"
4
brians343bc112013-02-10 01:53:46 +00005namespace aos {
6namespace time {
7
Austin Schuhf257f3c2019-10-27 21:00:43 -07008PhasedLoop::PhasedLoop(const monotonic_clock::duration interval,
9 const monotonic_clock::time_point monotonic_now,
10 const monotonic_clock::duration offset)
11 : interval_(interval), offset_(offset), last_time_(offset) {
12 CHECK(offset >= monotonic_clock::duration(0));
13 CHECK(interval > monotonic_clock::duration(0));
14 CHECK(offset < interval);
15 Reset(monotonic_now);
16}
17
18void PhasedLoop::set_interval_and_offset(
19 const monotonic_clock::duration interval,
20 const monotonic_clock::duration offset) {
21 interval_ = interval;
22 offset_ = offset;
23 CHECK(offset_ >= monotonic_clock::duration(0));
24 CHECK(interval_ > monotonic_clock::duration(0));
25 CHECK(offset_ < interval_);
26}
27
28monotonic_clock::duration PhasedLoop::OffsetFromIntervalAndTime(
29 const monotonic_clock::duration interval,
30 const monotonic_clock::time_point monotonic_trigger) {
31 CHECK(interval > monotonic_clock::duration(0));
32 return monotonic_trigger.time_since_epoch() -
33 (monotonic_trigger.time_since_epoch() / interval) * interval +
34 ((monotonic_trigger.time_since_epoch() >= monotonic_clock::zero())
35 ? monotonic_clock::zero()
36 : interval);
37}
38
Austin Schuh8aec1ed2016-05-01 13:29:20 -070039int PhasedLoop::Iterate(const monotonic_clock::time_point now) {
Brian Silverman8babd8f2020-06-23 16:38:50 -070040 auto next_time = monotonic_clock::epoch();
41 // Round up to the next whole interval, ignoring offset_.
42 {
43 const auto offset_now = (now - offset_).time_since_epoch();
44 monotonic_clock::duration prerounding;
45 if (now.time_since_epoch() >= offset_) {
46 // We're above 0, so rounding up means away from 0.
47 prerounding = offset_now + interval_;
48 } else {
49 // We're below 0, so rounding up means towards 0.
50 prerounding = offset_now + monotonic_clock::duration(1);
51 }
52 next_time += (prerounding / interval_) * interval_;
53 }
54 // Add offset_ back in.
55 next_time += offset_;
Brian Silvermandcaa3f72015-11-29 05:32:08 +000056
Austin Schuh8aec1ed2016-05-01 13:29:20 -070057 const monotonic_clock::duration difference = next_time - last_time_;
58 const int result = difference / interval_;
Austin Schuh8aec1ed2016-05-01 13:29:20 -070059 CHECK_EQ(
60 0, (next_time - offset_).time_since_epoch().count() % interval_.count());
Brian Silverman8babd8f2020-06-23 16:38:50 -070061 CHECK(next_time > now);
Austin Schuhf257f3c2019-10-27 21:00:43 -070062 CHECK(next_time - now <= interval_);
Brian Silvermandcaa3f72015-11-29 05:32:08 +000063 last_time_ = next_time;
64 return result;
65}
66
brians343bc112013-02-10 01:53:46 +000067} // namespace timing
68} // namespace aos