ping-pong-poll.cpp 2.2 KB

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