Skip to content

Instantly share code, notes, and snippets.

@wesbillman
Created January 21, 2010 18:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wesbillman/283046 to your computer and use it in GitHub Desktop.
Save wesbillman/283046 to your computer and use it in GitHub Desktop.
#include "sm.h"
static state_e current_state;
static void state_a_entry(void);
static void state_a_exit(void);
static void message_a_handler(void);
static void message_b_handler(void);
static void message_c_handler(void);
static const state_t state_list[] =
{
//STATE_A
{
.state = STATE_A,
.name = "A",
.messages = {{MSG_A, message_a_handler},
{MSG_B, message_b_handler}},
.transitions = {STATE_B, STATE_C},
.entry_action = state_a_entry,
.exit_action = state_a_exit
},
//STATE_B
{
.state = STATE_B,
.name = "B",
.messages = {{MSG_A, message_a_handler},
{MSG_B, message_b_handler}},
.transitions = {STATE_A, STATE_C},
.entry_action = NULL,
.exit_action = NULL
},
//STATE_C
{
.state = STATE_C,
.name = "C",
.messages = {{MSG_A, message_a_handler},
{MSG_C, message_c_handler}},
.transitions = {STATE_A, STATE_B},
.entry_action = NULL,
.exit_action = NULL
}
};
static void power_on(void)
{
//do power_on stuff
}
static void state_a_entry(void)
{
//do state_a entry actions
}
static void state_a_exit(void)
{
//do state_a exit
}
static void message_a_handler(void)
{
}
static void message_b_handler(void)
{
}
static void message_c_handler(void)
{
}
static void main_thread(void)
{
while(1)
{
state_e new_state = current_state;
if(state_list[current_state].entry_action != NULL)
state_list[current_state].entry_action();
while(new_state == current_state)
{
//receive some message
}
if(state_list[current_state].exit_action != NULL)
state_list[current_state].exit_action();
}
}
static void main_init(void)
{
current_state = STATE_A;
}
/*
* File: sm.h
* Author: wes.billman
*
* Created on January 21, 2010, 9:54 AM
*/
#ifndef _SM_H
#define _SM_H
#ifdef __cplusplus
extern "C" {
#endif
typedef void (*message_handler)(void);
typedef void (*transition_handler)(void);
typedef enum{
MSG_A,
MSG_B,
MSG_C,
MSG_COUNT
} message_e;
typedef enum{
STATE_A,
STATE_B,
STATE_C,
STATE_COUNT
} state_e;
typedef struct{
message_e message;
message_handler msg_cbf;
} state_message_t;
typedef struct{
state_e state;
char * name;
state_message_t messages[sizeof(message_e)];
state_e transitions[sizeof(state_e)];
transition_handler entry_action;
transition_handler exit_action;
} state_t;
#ifdef __cplusplus
}
#endif
#endif /* _SM_H */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment