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