Shylock Hg

My own blog powered by Hugo and Ivy.

Implement FSM by c language in a special apply

2018-01-23


1.Arch of AD602_G1S1 project.

Top-of-AD602

2.FSM description

2.1Behavior abstract

In this project,I abstract program to [states,events] matrix.So the main work of program is handle various events in states.

2.2Top map of FSM

There is a simple top map of states switch below.

fsm-of-ad602

3.Implement by c language.

3.1 FSM arch definition

/*!**********  state id enum  ***********/
typedef enum state_id {
	STATE_0_0,
	STATE_0_1,
//!< more state id reserved

} state_id_t;

/*!**********  state struct def ***********/
t ypedef const struct state {
	const state_id_t idx;
	const struct state * next;
	const struct state * back;
	const struct state * ex0;
	const struct state * ex1;
	void (*handler)(events_user_t * e_user, events_server_t * e_server);
} state_t;

3.2 Main loop

while(1){
/*! **********  back-end handler ***********/
	handle_wifi();  //!< receive events from wifi
	wdt_feed();

/*! **********  front-end handler ***********/
	update_event();  //!< receive events from usr[button,touch,scan]
	current_state->handler(event_user, event_server);  //!< current state handler callback
	ui_update_widget();  //!< update & display widget in time
}

3.3 Handler callback for each state

So,now we can construct diff callback functions for each state to handle events,like below.

/*!**********  handler description ***********/
/*! event-loop */
static void _state_xxx_handler(events_user_t * e_user, events_server_t * e_server){
	//!< \TODO -- display to usr
	//!< \TODO -- handle events&sync
	//!< \TODO -- schedule to next state
}

4. Summary

So,we can abstract a complex works flow to a stratified FSM.Then implement it by language.In this way,we can easy program application to complete complex works schedule.