|
|
# WIP
|
|
|
A **finite state machine** is a model that can simulate some logic or computer program.
|
|
|
This abstraction is very useful when designing an algorithm since it can be translated to code almost for free.
|
|
|
|
|
|
## Implementation
|
|
|
In *skyward-boardcore* implementation, the **FSM** class extends the [EventHandler](EventHandler) class. This means that the main communication method use by FSMs are events: state machines can receive events, handle them and react according to the received event. If an [EventBroker](EventBroker) is used, the FSM can subscribe only to the required topics, in order to "filter" the events it will receive.
|
|
|
|
|
|
The machine states are defined by the class methods, for example:
|
|
|
```cpp
|
|
|
void state_myState(const Event& ev)
|
|
|
{
|
|
|
...
|
|
|
|
|
|
switch(ev.sig)
|
|
|
{
|
|
|
case EV_1:
|
|
|
...
|
|
|
case EV_2:
|
|
|
...
|
|
|
default:
|
|
|
...
|
|
|
}
|
|
|
|
|
|
...
|
|
|
}
|
|
|
```
|
|
|
In the constructor we can specify the initial one.
|
|
|
The FSM maintains the current state by means of a pointer to one of the class methods.
|
|
|
Then, whenever a new events in received, *handleEvent()* dereferences the current state pointer, calling the relative method (and passing the event as parameter):
|
|
|
```cpp
|
|
|
void handleEvent(const Event& e) override
|
|
|
{
|
|
|
(static_cast<T*>(this)->*state)(e);
|
|
|
}
|
|
|
```
|
|
|
|
|
|
According to what explained here above, the FSM class is defined as a template class:
|
|
|
```cpp
|
|
|
template <class T>
|
|
|
class FSM : public EventHandler
|
|
|
{
|
|
|
...
|
|
|
};
|
|
|
```
|
|
|
|
|
|
Finite state machine, handles events using the current state's handler.
|
|
|
#### Methods
|
|
|
Available public methods are:
|
|
|
- **void transition(void (T::\*nextState)(const Event&))**: perform a transition from the current state to the state that is specified as a parameter.
|
|
|
- **bool testState(void (T::\*test_state)(const Event&))**: test is the state machines is in a specific state (that is passed as a parameter).
|
|
|
|
|
|
#### Standard Events
|
|
|
`EV_ENTRY` and `EV_EXIT` are automatically posted when entering or exiting a state.
|
|
|
In fact when the *transition()* method is called, the FSM itself handles `EV_EXIT` according to the current state, performs the state transition and then handles `EV_ENTRY` according to the new state.
|
|
|
By handling these two events, actions to be performed on entry/exit from a state can be specified.
|
|
|
|
|
|
You can find the complete implementation of the FSM class in `src/shared/events/FSM.h`.
|
|
|
|
|
|
## Example
|
|
|
This example implements the following very simple finite state machine behavior:
|
... | ... | |