Here is the idea, define a specific construct for implementing state machines of any kind, directly in the language. Consider an extension to the structures definition:
Code: Select all
struct sm {
state enum st {STOPPED = 0, STARTED, ERROR};
int i;
char *message;
/* other fields */
...
/* this is the new part, attaching actions to variables transitions */
transition st: STOPPED => STARTED;
activate_motor();
if (activation_failure())
st = ERROR;
transition st: STARTED => STOPPED;
stop_motor();
if (brake_failure())
st = ERROR;
transition st: @@ => ERROR;
report_error();
default:
invalid_transition();
};
sm motor1 = {STOPPED, ...};
sm = STARTED; /* starting motor */
sleep(100);
sm = STOPPED; /* stopping motor */
Two new keywords would be required: state and transition. @@ means "any state", => defines a transition. The typical use case is like in ChibiOS HAL drivers, each driver has a state machine, multiple peripherals of the same driver has a separate state machine instance. The XXXDriver structures in HAL could be implemented using this construct.
Syntax is invented and probably could be better or more elegant.
Giovanni