From a6ab1504058304012791281f9eb42c262745888f Mon Sep 17 00:00:00 2001 From: jacqueline Date: Fri, 19 May 2023 21:21:27 +1000 Subject: Add tinyfsm, start converting core functions to an FSM-based event loop --- lib/tinyfsm/examples/api/moore_machine.cpp | 64 ++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 lib/tinyfsm/examples/api/moore_machine.cpp (limited to 'lib/tinyfsm/examples/api/moore_machine.cpp') diff --git a/lib/tinyfsm/examples/api/moore_machine.cpp b/lib/tinyfsm/examples/api/moore_machine.cpp new file mode 100644 index 00000000..02a77da2 --- /dev/null +++ b/lib/tinyfsm/examples/api/moore_machine.cpp @@ -0,0 +1,64 @@ +#include +#include + +// ---------------------------------------------------------------------------- +// 1. Event Declarations +// +struct Toggle : tinyfsm::Event { }; + + +// ---------------------------------------------------------------------------- +// 2. State Machine Base Class Declaration +// +struct Switch : tinyfsm::MooreMachine +{ + /* pure virtual reaction (override required in all states) */ + virtual void react(Toggle const &) = 0; +}; + + +// ---------------------------------------------------------------------------- +// 3. State Declarations +// +struct Off; // forward declaration + +struct On : Switch +{ + void entry() override { std::cout << "* Closing ciruit (light goes ON)" << std::endl; }; + void react(Toggle const &) override { transit(); }; +}; + +struct Off : Switch +{ + void entry() override { std::cout << "* Opening ciruit (light goes OFF)" << std::endl; }; + void react(Toggle const &) override { transit(); }; +}; + +FSM_INITIAL_STATE(Switch, Off) + + +// ---------------------------------------------------------------------------- +// Main +// +int main() +{ + Switch::start(); + + std::cout << "> You are facing a light switch..." << std::endl; + while(1) + { + char c; + std::cout << std::endl << "t=Toggle, q=Quit ? "; + std::cin >> c; + switch(c) { + case 't': + std::cout << "> Toggling switch..." << std::endl; + Switch::dispatch(Toggle()); + break; + case 'q': + return 0; + default: + std::cout << "> Invalid input" << std::endl; + }; + } +} -- cgit v1.2.3