blob: fc0f247522f8f5ea94e0b60d5aa597fcc4cc0d7e [file] [log] [blame]
Brian3afd6fc2014-04-02 20:41:49 -07001#ifndef AOS_COMMON_UTIL_PHASED_LOOP_H_
2#define AOS_COMMON_UTIL_PHASED_LOOP_H_
brians343bc112013-02-10 01:53:46 +00003
Brian Silvermandcaa3f72015-11-29 05:32:08 +00004#include "aos/common/time.h"
5
6#include "aos/common/logging/logging.h"
brians343bc112013-02-10 01:53:46 +00007
8namespace aos {
9namespace time {
10
11// Will not be accurate if ms isn't a factor of 1000.
12// offset is in us.
Brian Silvermandcaa3f72015-11-29 05:32:08 +000013// DEPRECATED(Brian): Use PhasedLoop instead.
brians343bc112013-02-10 01:53:46 +000014void PhasedLoopXMS(int ms, int offset);
brians343bc112013-02-10 01:53:46 +000015
Brian Silvermandcaa3f72015-11-29 05:32:08 +000016// Handles sleeping until a fixed offset from some time interval.
17class PhasedLoop {
18 public:
19 // For example, with interval = 1s and offset = 0.1s this will fire at:
20 // 0.1s
21 // 1.1s
22 // ...
23 // 10000.1s
24 // offset must be >= Time::kZero and < interval.
25 PhasedLoop(const Time &interval, const Time &offset = Time::kZero)
26 : interval_(interval), offset_(offset), last_time_(offset) {
27 CHECK_GE(offset, Time::kZero);
28 CHECK_GT(interval, Time::kZero);
29 CHECK_LT(offset, interval);
30 Reset();
31 }
32
33 // Resets the count of skipped iterations.
34 // Iterate(now) will return 1 and set sleep_time() to something within
35 // interval of now.
36 void Reset(const Time &now = Time::Now()) { Iterate(now - interval_); }
37
38 // Calculates the next time to run after now.
39 // The result can be retrieved with sleep_time().
40 // Returns the number of iterations which have passed (1 if this is called
41 // often enough). This can be < 1 iff now goes backwards between calls.
42 int Iterate(const Time &now = Time::Now());
43
44 // Sleeps until the next time and returns the number of iterations which have
45 // passed.
46 int SleepUntilNext() {
47 const int r = Iterate(Time::Now());
48 SleepUntil(sleep_time());
49 return r;
50 }
51
52 const Time &sleep_time() const { return last_time_; }
53
54 private:
55 const Time interval_, offset_;
56
57 // The time we most recently slept until.
58 Time last_time_ = Time::kZero;
59};
60
brians343bc112013-02-10 01:53:46 +000061} // namespace time
62} // namespace aos
63
Brian3afd6fc2014-04-02 20:41:49 -070064#endif // AOS_COMMON_UTIL_PHASED_LOOP_H_