Untitled
unknown
c_cpp
a year ago
2.1 kB
4
Indexable
#include "tinyfsm.hpp"
#include <iostream>
#include <unordered_map>
// Define the events
struct Event0 : tinyfsm::Event {};
struct Event1 : tinyfsm::Event {};
struct Event2 : tinyfsm::Event {};
// Define the states
struct State1;
struct State2;
struct State3;
// Define the Mealy machine
struct MyMealyMachine : tinyfsm::MealyMachine<MyMealyMachine> {
using StateInputMap = std::unordered_map<std::pair<std::string, char>, std::string>;
// Transition logic for State1
void react(Event0 const &) { std::cout << "Output: O1" << std::endl; transit<State2>(); }
void react(Event1 const &) { std::cout << "Output: O2" << std::endl; transit<State3>(); }
void react(Event2 const &) { std::cout << "Output: O3" << std::endl; transit<State1>(); }
// Dispatch event based on input character
void dispatch_input(char input) {
auto currentState = current_state_name();
auto nextState = state_map[{currentState, input}];
transit(nextState);
}
// Map of current state and input to the next state
static StateInputMap state_map;
};
// Define the states
struct State1 : MyMealyMachine {
void entry() override { std::cout << "Entering State1" << std::endl; };
};
struct State2 : MyMealyMachine {
void entry() override{ std::cout << "Entering State2" << std::endl; };
};
struct State3 : MyMealyMachine {
void entry() override{ std::cout << "Entering State3" << std::endl; };
};
// Define the initial state
FSM_INITIAL_STATE(MyMealyMachine, State1)
// Initialize the state map
MyMealyMachine::StateInputMap MyMealyMachine::state_map = {
{{"State1", '0'}, "State2"},
{{"State2", '1'}, "State3"},
// Add more mappings as needed
};
int main() {
MyMealyMachine my_machine; // Create an object of the MyMealyMachine class
my_machine.start(); // Start the state machine
// Simulate input based on characters
char input;
std::cout << "Enter input characters (0, 1, 2): ";
while (std::cin >> input) {
my_machine.dispatch_input(input);
std::cout << "Enter input characters (0, 1, 2): ";
}
return 0;
}
Editor is loading...
Leave a Comment