diff options
| author | jacqueline <me@jacqueline.id.au> | 2023-05-19 21:21:27 +1000 |
|---|---|---|
| committer | jacqueline <me@jacqueline.id.au> | 2023-05-19 21:21:27 +1000 |
| commit | a6ab1504058304012791281f9eb42c262745888f (patch) | |
| tree | f82379cd1e66a8ae2f1afbae5cf083a8ab7acc53 /lib/tinyfsm/examples/api/mealy_machine.cpp | |
| parent | b320a6a863cf1c10dc79254af41f573730935564 (diff) | |
| download | tangara-fw-a6ab1504058304012791281f9eb42c262745888f.tar.gz | |
Add tinyfsm, start converting core functions to an FSM-based event loop
Diffstat (limited to 'lib/tinyfsm/examples/api/mealy_machine.cpp')
| -rw-r--r-- | lib/tinyfsm/examples/api/mealy_machine.cpp | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/lib/tinyfsm/examples/api/mealy_machine.cpp b/lib/tinyfsm/examples/api/mealy_machine.cpp new file mode 100644 index 00000000..a4fadff6 --- /dev/null +++ b/lib/tinyfsm/examples/api/mealy_machine.cpp @@ -0,0 +1,70 @@ +#include <tinyfsm.hpp> +#include <iostream> + +// ---------------------------------------------------------------------------- +// 1. Event Declarations +// +struct Toggle : tinyfsm::Event { }; + + +// ---------------------------------------------------------------------------- +// 2. State Machine Base Class Declaration +// +struct Switch : tinyfsm::MealyMachine<Switch> +{ + /* pure virtual reaction (override required in all states) */ + virtual void react(Toggle const &) = 0; + + /* transition actions */ + static void OpenCircuit() { + std::cout << "* Opening ciruit (light goes OFF)" << std::endl; + } + static void CloseCircuit() { + std::cout << "* Closing ciruit (light goes ON)" << std::endl; + } +}; + + +// ---------------------------------------------------------------------------- +// 3. State Declarations +// +struct Off; // forward declaration + +struct On : Switch +{ + void react(Toggle const &) override { transit<Off>(OpenCircuit); }; +}; + +struct Off : Switch +{ + void react(Toggle const &) override { transit<On>(CloseCircuit); }; +}; + +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; + }; + } +} |
