ping-pong-poll.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // SPDX-License-Identifier: MIT
  2. // SPDX-FileCopyrightText: 2022 Ivan Baidakou
  3. #include "board.h"
  4. namespace rl = rotor_light;
  5. namespace message {
  6. struct Ping : rl::Message {
  7. using Message::Message;
  8. static constexpr auto type_id = __LINE__;
  9. };
  10. struct Pong : rl::Message {
  11. using Message::Message;
  12. static constexpr auto type_id = __LINE__;
  13. };
  14. } // namespace message
  15. struct Pinger : rl::Actor<2> {
  16. using Parent = Actor<2>;
  17. void initialize() override {
  18. subscribe(&Pinger::on_pong);
  19. Parent::initialize();
  20. }
  21. void advance_start() override {
  22. Parent::advance_start();
  23. ping();
  24. }
  25. void ping() {
  26. Board::toggle_led();
  27. send<rl::ctx::thread, message::Ping>(0, ponger_id);
  28. }
  29. void on_pong(message::Pong &) {
  30. add_event<rl::ctx::thread>(
  31. 500000, [](void *data) { static_cast<Pinger *>(data)->ping(); }, this);
  32. }
  33. rl::ActorId ponger_id;
  34. };
  35. struct Ponger : rl::Actor<2> {
  36. using Parent = Actor<2>;
  37. void initialize() override {
  38. subscribe(&Ponger::on_ping);
  39. Parent::initialize();
  40. }
  41. void on_ping(message::Ping &) {
  42. send<rl::ctx::thread, message::Pong>(0, pinger_id);
  43. }
  44. rl::ActorId pinger_id;
  45. };
  46. using Supervisor =
  47. rl::Supervisor<rl::SupervisorBase::min_handlers_amount, Pinger, Ponger>;
  48. using Storage = rl::traits::MessageStorage<rl::message::ChangeState,
  49. rl::message::ChangeStateAck,
  50. message::Ping, message::Pong>;
  51. using Queue = rl::Queue<Storage, 5>; /* upto 5 messages in 1 queue */
  52. using Planner = rl::Planner<1>; /* upto 1 time event */
  53. Supervisor sup;
  54. int main(int, char **) {
  55. Board::init_start();
  56. Board::enable_timer();
  57. /* setup */
  58. Queue queue;
  59. Planner planner;
  60. rl::Context context{&queue, &planner, &Board::get_now};
  61. sup.bind(context);
  62. auto pinger = sup.get_child<0>();
  63. auto ponger = sup.get_child<1>();
  64. pinger->ponger_id = ponger->get_id();
  65. ponger->pinger_id = pinger->get_id();
  66. /* let it polls timer */
  67. sup.start(true);
  68. /* main cycle */
  69. sup.process();
  70. return 0;
  71. }