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