ping-pong-poll.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // SPDX-License-Identifier: MIT
  2. // SPDX-FileCopyrightText: 2022 Ivan Baidakou
  3. #include <chrono>
  4. #include <cstdio>
  5. #include <rotor-light.hpp>
  6. using Clock = std::chrono::steady_clock;
  7. using TimeUnit = std::chrono::milliseconds;
  8. namespace rl = rotor_light;
  9. rl::TimePoint get_now() {
  10. return std::chrono::duration_cast<TimeUnit>(Clock::now().time_since_epoch())
  11. .count();
  12. }
  13. namespace message {
  14. struct Ping : rl::Message {
  15. using Message::Message;
  16. static constexpr auto type_id = __LINE__;
  17. rl::MessageTypeId get_type_id() const override { return type_id; }
  18. };
  19. struct Pong : rl::Message {
  20. using Message::Message;
  21. static constexpr auto type_id = __LINE__;
  22. rl::MessageTypeId get_type_id() const override { return type_id; }
  23. };
  24. } // namespace message
  25. struct Pinger : rl::Actor<2> {
  26. using Parent = Actor<2>;
  27. void initialize() override {
  28. subscribe(&Pinger::on_pong);
  29. Parent::initialize();
  30. }
  31. void advance_start() override {
  32. Parent::advance_start();
  33. ping();
  34. }
  35. void ping() {
  36. printf("pinger -> ponger, sending ping\n");
  37. send<message::Ping>(0, ponger_id);
  38. }
  39. void on_pong(message::Pong &) {
  40. printf("pinger, pong received\n");
  41. add_event(
  42. 500, [](void *data) { static_cast<Pinger *>(data)->ping(); }, this);
  43. }
  44. rl::ActorId ponger_id;
  45. };
  46. struct Ponger : rl::Actor<2> {
  47. using Parent = Actor<2>;
  48. void initialize() override {
  49. subscribe(&Ponger::on_ping);
  50. Parent::initialize();
  51. }
  52. void on_ping(message::Ping &) {
  53. printf("ponger, ping received\n");
  54. send<message::Pong>(0, pinger_id);
  55. }
  56. rl::ActorId pinger_id;
  57. };
  58. using Supervisor =
  59. rl::Supervisor<rl::SupervisorBase::min_handlers_amount, Pinger, Ponger>;
  60. using Storage = rl::traits::MessageStorage<rl::message::ChangeState,
  61. rl::message::ChangeStateAck,
  62. message::Ping, message::Pong>;
  63. using Queue = rl::Queue<Storage, 5>; /* upto 5 messages in 1 queue */
  64. using Planner = rl::Planner<1>; /* upto 1 time event */
  65. int main(int, char **) {
  66. /* allocate */
  67. Queue queue;
  68. Planner planner;
  69. rl::Context context{&queue, &planner, &get_now};
  70. Supervisor sup;
  71. /* setup */
  72. sup.bind(context);
  73. auto pinger = sup.get_child<0>();
  74. auto ponger = sup.get_child<1>();
  75. pinger->ponger_id = ponger->get_id();
  76. ponger->pinger_id = pinger->get_id();
  77. /* let it polls timer */
  78. sup.start(true);
  79. /* main cycle */
  80. sup.process();
  81. return 0;
  82. }