35-broadcasting.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // SPDX-License-Identifier: MIT
  2. // SPDX-FileCopyrightText: 2022 Ivan Baidakou
  3. #if defined(__ANDROID__)
  4. #undef __ANDROID__
  5. #endif
  6. #include "catch.hpp"
  7. #include "rotor-light/planner.hpp"
  8. #include "rotor-light/queue.hpp"
  9. #include "rotor-light/supervisor.hpp"
  10. #include <string>
  11. using namespace rotor_light;
  12. struct Signal : Message {
  13. using Message::Message;
  14. };
  15. using MessageStorage = traits::MessageStorage<message::ChangeState,
  16. message::ChangeStateAck, Signal>;
  17. using AppQueue = Queue<MessageStorage, 5>;
  18. using AppPlanner = Planner<1>;
  19. struct A : Actor<2> {
  20. using Parent = Actor<2>;
  21. using Parent::Parent;
  22. void initialize() override {
  23. Parent::initialize();
  24. subscribe(&A::on_signal);
  25. }
  26. void on_signal(Signal &) { ++count; }
  27. int count = 0;
  28. };
  29. struct S : Supervisor<4, A, A> {
  30. using Parent = Supervisor<4, A, A>;
  31. using Parent::Parent;
  32. void initialize() override {
  33. Parent::initialize();
  34. subscribe(&S::on_signal);
  35. }
  36. void on_signal(Signal &) { ++count; }
  37. void advance_start() override {
  38. Parent::advance_start();
  39. send_signal();
  40. }
  41. void send_signal() { send<Signal>(0, broadcast); }
  42. int count = 0;
  43. };
  44. TEST_CASE("broadcasting example", "[sup]") {
  45. AppQueue queue;
  46. AppPlanner planner;
  47. Context context{&queue, &planner, nullptr};
  48. S sup;
  49. sup.bind(context);
  50. auto act1 = sup.get_child<0>();
  51. auto act2 = sup.get_child<1>();
  52. sup.start();
  53. sup.process();
  54. REQUIRE(sup.get_state() == State::operational);
  55. REQUIRE(act1->get_state() == State::operational);
  56. REQUIRE(act2->get_state() == State::operational);
  57. CHECK(sup.count == 1);
  58. CHECK(act1->count == 1);
  59. CHECK(act2->count == 1);
  60. act2->stop();
  61. sup.process();
  62. REQUIRE(act2->get_state() == State::off);
  63. sup.send_signal();
  64. sup.process();
  65. CHECK(sup.count == 2);
  66. CHECK(act1->count == 2);
  67. CHECK(act2->count == 1);
  68. sup.stop();
  69. sup.process();
  70. CHECK(sup.get_state() == State::off);
  71. CHECK(act1->get_state() == State::off);
  72. CHECK(act2->get_state() == State::off);
  73. }