xref: /openbmc/sdeventplus/example/heartbeat.cpp (revision ba04ffb5)
1 #include <chrono>
2 #include <cstdio>
3 #include <sdeventplus/clock.hpp>
4 #include <sdeventplus/event.hpp>
5 #include <sdeventplus/source/time.hpp>
6 #include <string>
7 #include <utility>
8 
9 using sdeventplus::Event;
10 using sdeventplus::source::Enabled;
11 
12 constexpr auto clockId = sdeventplus::ClockId::RealTime;
13 using Clock = sdeventplus::Clock<clockId>;
14 using Time = sdeventplus::source::Time<clockId>;
15 
16 int main(int argc, char* argv[])
17 {
18     if (argc != 2)
19     {
20         fprintf(stderr, "Usage: %s [seconds]\n", argv[0]);
21         return 1;
22     }
23 
24     unsigned interval = std::stoul(argv[1]);
25     fprintf(stderr, "Beating every %u seconds\n", interval);
26 
27     auto event = Event::get_default();
28     auto hbFunc = [interval](Time& source, Time::TimePoint time) {
29         printf("Beat\n");
30 
31         // Time sources are oneshot and are based on an absolute time
32         // we need to reconfigure the time source to go off again after the
33         // configured interval and re-enable it.
34         source.set_time(time + std::chrono::seconds{interval});
35         source.set_enabled(Enabled::OneShot);
36     };
37     Time time(event, Clock(event).now(), std::chrono::seconds{1},
38               std::move(hbFunc));
39     return event.loop();
40 }
41