Also named Finite State Automaton (FSA)
A way to depict an FSM:
A PC needs to send text messages to another PC. The two PCs are connected by a link with the following properties:
Every message is formatted as follows:
Possible FSM waiting for a full message:
A possible implementation:
current_state = WAIT_STX;
while (true) {
c = get_character();
switch (current_state) {
case WAIT_STX:
if (c == STX) {
body_length = 0
current_state = WAIT_ETX;
break;
}
// At this stage, other character, stay in this state.
break;
case WAIT_ETX:
if (c != ETX) {
if (body_length < 255) {
// TODO: store received byte.
body_length++;
// Stay in same state.
break;
}
// At this stage, body_length >= 255.
// TODO: signal error.
current_state = WAIT_STX;
break;
}
// At this stage, ETX.
current_state = WAIT_STX;
break;
default:
signal_error(UNKNOWN_STATE);
current_state = WAIT_STX;
}
}