Erlang Central

Difference between revisions of "Cascading Behaviours"

From ErlangCentral Wiki

(Restored missing content from older version)
(24 intermediate revisions by 10 users not shown)
Line 1:Line 1:
==1. Introduction==
+
==Author==
 +
Vance Shipley
 +
 
 +
==Introduction==
  
 
===Behaviours===  
 
===Behaviours===  
Line 5:Line 8:
 
Behaviour modules encapsulate some certain functionality for reuse by other modules. The definition of a behaviour includes not only it's exported functions but a list of functions which a callback module must implement. OTP includes several behaviour modules with the most common being gen_server and gen_fsm.
 
Behaviour modules encapsulate some certain functionality for reuse by other modules. The definition of a behaviour includes not only it's exported functions but a list of functions which a callback module must implement. OTP includes several behaviour modules with the most common being gen_server and gen_fsm.
  
==2. Using gen_fsm==
+
==Using gen_fsm==
  
 
===Behaviour===
 
===Behaviour===
Line 11:Line 14:
 
To declare your module as a behaviour callback module you include the -behaviour attribute.
 
To declare your module as a behaviour callback module you include the -behaviour attribute.
  
Code listing 2.1: Behaviour Attribute
+
<code caption="Code listing 2.1: Behaviour Attribute">
  
<code>-behaviour(gen_fsm).</code>
+
-behaviour(gen_fsm).
  
Note: All this really does is to enable compilation time checking that you have exported the required callbacks.
+
</code>
 +
<table class="ncontent" width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td bgcolor="#bbffbb"><p class="note"><b>Note: </b>All this really does is to enable compilation time checking that
 +
you have exported the required callbacks.</p></td></tr></table>
  
 
===Exports===
 
===Exports===
Line 21:Line 26:
 
A module which uses the gen_fsm behaviour must export the callbacks which the gen_fsm module calls to handle events. These include handlers for common gen_fsm events as well as the handlers for your user defined states.
 
A module which uses the gen_fsm behaviour must export the callbacks which the gen_fsm module calls to handle events. These include handlers for common gen_fsm events as well as the handlers for your user defined states.
  
Code listing 2.2: Required gen_fsm Callbacks
+
<table class="ntable" width="100%" cellspacing="0" cellpadding="0" border="0">
  
<code>-export([init/1, handle_event/3, handle_sync_event/4,
+
<code caption="Code listing 2.2: Required gen_fsm Callbacks">
        handle_info/3, terminate/3, code_change/4]).</code>
+
  
Code listing 2.3: State Handler Callbacks
+
-export([init/1, handle_event/3, handle_sync_event/4,
 +
        handle_info/3, terminate/3, code_change/4]).
  
<code>-export([idle/2, busy/2]).</code>
+
</code>
  
 +
<code caption="Code listing 2.3: State Handler Callbacks">
 +
 +
-export([idle/2, busy/2]).
 +
 +
</code>
  
 
===Startup===  
 
===Startup===  
Line 35:Line 45:
 
To start a process implemented in a module as a gen_fsm behaviour you may call gen_fsm:start/3. In response this function will call the init/1 callback in your module. After your init/1 function returns a result gen_fsm:start_link/3 will return the appropriate result to the calling process. Normally the result is to create a new process where the gen_fsm module is running it's internal main loop function waiting for messages to arrive.
 
To start a process implemented in a module as a gen_fsm behaviour you may call gen_fsm:start/3. In response this function will call the init/1 callback in your module. After your init/1 function returns a result gen_fsm:start_link/3 will return the appropriate result to the calling process. Normally the result is to create a new process where the gen_fsm module is running it's internal main loop function waiting for messages to arrive.
  
Code listing 2.4: Starting a Finite State Machine
+
<code caption="Code listing 2.4: Starting a Finite State Machine">
  
2> {ok, FSM} = gen_fsm:start(simple_fsm, [], []).
+
2&gt; {ok, FSM} = gen_fsm:start(simple_fsm, [], []).
{ok,<0.36.0>}
+
{ok,&lt;0.36.0&gt;}
 +
 
 +
</code>
  
 
===Events===  
 
===Events===  
Line 44:Line 56:
 
To send an event to your finite state machine process you may call gen_fsm:send_event/2.
 
To send an event to your finite state machine process you may call gen_fsm:send_event/2.
  
Code listing 2.5: Sending an Event
+
<code caption="Code listing 2.5: Sending an Event">
 +
 
 +
2&gt; gen_fsm:send_event(FSM, foo).
  
2> gen_fsm:send_event(FSM, foo).
 
 
ok
 
ok
 +
</code>
  
 
The result is that a message is sent to your FSM process tagged so that the gen_fsm module may recognize it as a gen_fsm generated event. When the main loop function in gen_fsm receives this message it will call the state handler callback in your module corresponding to the current state the FSM process is in.
 
The result is that a message is sent to your FSM process tagged so that the gen_fsm module may recognize it as a gen_fsm generated event. When the main loop function in gen_fsm receives this message it will call the state handler callback in your module corresponding to the current state the FSM process is in.
  
==3. An Example FSM==
+
==An Example FSM==
  
 
===The Module===  
 
===The Module===  
Line 57:Line 71:
 
Below is a very simple example of a module implemented with a gen_fsm behaviour. In this module we will implement just one state and the only thing it will really do is to be chatty about what is going on.
 
Below is a very simple example of a module implemented with a gen_fsm behaviour. In this module we will implement just one state and the only thing it will really do is to be chatty about what is going on.
  
Code listing 3.1: A Chatty gen_fsm Callback Module
+
<code caption="Code listing 3.1: A Chatty gen_fsm Callback Module">
  
 
-module(chatty_fsm).
 
-module(chatty_fsm).
Line 69:Line 83:
 
-record(state, {}).
 
-record(state, {}).
  
init(Args) ->
+
init(Args) -&gt;
 
     process_flag(trap_exit, true),
 
     process_flag(trap_exit, true),
 
     io:fwrite("gen_fsm called ~w:init(~w)~n", [?MODULE, Args]),
 
     io:fwrite("gen_fsm called ~w:init(~w)~n", [?MODULE, Args]),
 
     {ok, idle, #state{}}.
 
     {ok, idle, #state{}}.
  
idle(Event, StateData) ->
+
idle(Event, StateData) -&gt;
 
     io:fwrite("gen_fsm called ~w:idle(~w, ~w)~n",  
 
     io:fwrite("gen_fsm called ~w:idle(~w, ~w)~n",  
 
         [?MODULE, Event, StateData]),
 
         [?MODULE, Event, StateData]),
 
     {next_state, idle, StateData}.
 
     {next_state, idle, StateData}.
  
handle_event(Event, StateName, StateData) ->
+
handle_event(Event, StateName, StateData) -&gt;
 
     io:fwrite("gen_fsm called ~w:handle_event(~w, ~w, ~w)~n",
 
     io:fwrite("gen_fsm called ~w:handle_event(~w, ~w, ~w)~n",
 
         [?MODULE, Event, StateName, StateData]),
 
         [?MODULE, Event, StateName, StateData]),
 
     {next_state, StateName, StateData}.
 
     {next_state, StateName, StateData}.
  
handle_sync_event(Event, From, StateName, StateData) ->
+
handle_sync_event(Event, From, StateName, StateData) -&gt;
 
     io:fwrite("gen_fsm called ~w:handle_sync_event(~w, ~w, ~w, ~w)~n",
 
     io:fwrite("gen_fsm called ~w:handle_sync_event(~w, ~w, ~w, ~w)~n",
 
         [?MODULE, Event, From, StateName, StateData]),
 
         [?MODULE, Event, From, StateName, StateData]),
 
     {next_state, StateName, StateData}.
 
     {next_state, StateName, StateData}.
  
handle_info(Info, StateName, StateData) ->
+
handle_info(Info, StateName, StateData) -&gt;
 
     io:fwrite("gen_fsm called ~w:handle_info(~w, ~w, ~w)~n",
 
     io:fwrite("gen_fsm called ~w:handle_info(~w, ~w, ~w)~n",
 
         [?MODULE, Info, StateName, StateData]),
 
         [?MODULE, Info, StateName, StateData]),
 
     {next_state, StateName, StateData}.
 
     {next_state, StateName, StateData}.
  
terminate(Reason, StateName, StateData) ->
+
terminate(Reason, StateName, StateData) -&gt;
 +
 
 
     io:fwrite("gen_fsm called ~w:terminate(~w, ~w, ~w)~n",
 
     io:fwrite("gen_fsm called ~w:terminate(~w, ~w, ~w)~n",
 
         [?MODULE, Reason, StateName, StateData]).
 
         [?MODULE, Reason, StateName, StateData]).
  
code_change(OldVsn, StateName, StateData, Extra) ->
+
code_change(OldVsn, StateName, StateData, Extra) -&gt;
 
     io:fwrite("gen_fsm called ~w:code_change(~w, ~w, ~w, ~w)~n",
 
     io:fwrite("gen_fsm called ~w:code_change(~w, ~w, ~w, ~w)~n",
 
         [?MODULE, OldVsn, StateName, StateData, Extra]),
 
         [?MODULE, OldVsn, StateName, StateData, Extra]),
 
     {ok, StateName, StateData}.
 
     {ok, StateName, StateData}.
  
Running the Chatty FSM  
+
</code>
 +
 
 +
===Running the Chatty FSM===
  
 
When we start this module and send it an event as above we will see the functions in our callback module being called.
 
When we start this module and send it an event as above we will see the functions in our callback module being called.
  
Code listing 3.2: Starting the Chatty FSM
+
<code caption="Code listing 3.2: Starting the Chatty FSM">
  
1> {ok, FSM} = gen_fsm:start(chatty_fsm, [], []).
+
1&gt; {ok, FSM} = gen_fsm:start(chatty_fsm, [], []).
 
gen_fsm called chatty_fsm:init([])
 
gen_fsm called chatty_fsm:init([])
{ok,<0.31.0>}
+
{ok,&lt;0.31.0&gt;}
  
Code listing 3.3: Sending the Chatty FSM an Event
+
</code>
 +
 
 +
<code caption="Code listing 3.3: Sending the Chatty FSM an Event">
 +
 
 +
2&gt; gen_fsm:send_event(FSM, foo).
  
2> gen_fsm:send_event(FSM, foo).
 
 
gen_fsm called chatty_fsm:idle(foo, {state})
 
gen_fsm called chatty_fsm:idle(foo, {state})
 
ok
 
ok
  
==4. Creating a New Behaviour==
+
</code>
 +
 
 +
==Creating a New Behaviour==
  
 
===A Chatty FSM Behaviour===  
 
===A Chatty FSM Behaviour===  
Line 127:Line 149:
 
===The Module===  
 
===The Module===  
  
Note: It is not suggested that this module performs a useful purpose as it is. There are better solutions to add event tracing including passing the gen_fsm start function the {debug, [trace]} option. The intent is to demonstrate an enhanced behaviour.
+
<table class="ncontent" width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td bgcolor="#bbffbb"><p class="note"><b>Note: </b>
 +
It is not suggested that this module performs a useful purpose as it is.
 +
There are better solutions to add event tracing including passing the
 +
gen_fsm start function the {debug, [trace]} option. The intent is to
 +
demonstrate an enhanced behaviour.
 +
</p></td></tr></table>
  
Code listing 4.1: A Chatty FSM Behaviour Module
+
<code caption="Code listing 4.1: A Chatty FSM Behaviour Module">
  
 
-module(chatty_fsm).
 
-module(chatty_fsm).
Line 148:Line 175:
 
-export([behaviour_info/1]).
 
-export([behaviour_info/1]).
  
behaviour_info(callbacks) ->
+
behaviour_info(callbacks) -&gt;
 +
 
 
     [{init,1},{handle_event,3},{handle_sync_event,4},
 
     [{init,1},{handle_event,3},{handle_sync_event,4},
 
         {handle_info,3}, {terminate,3},{code_change,4}];
 
         {handle_info,3}, {terminate,3},{code_change,4}];
behaviour_info(_Other) ->
+
behaviour_info(_Other) -&gt;
 
     undefined.
 
     undefined.
  
Line 163:Line 191:
 
%% We add the user's module name to the arguments and call
 
%% We add the user's module name to the arguments and call
 
%% gen_fsm's start function with our module name instead.
 
%% gen_fsm's start function with our module name instead.
start(Mod, Args, Options) ->
+
 
 +
start(Mod, Args, Options) -&gt;
 
     gen_fsm:start(?MODULE, [Mod, Args], Options).
 
     gen_fsm:start(?MODULE, [Mod, Args], Options).
  
start(Name, Mod, Args, Options) ->
+
start(Name, Mod, Args, Options) -&gt;
 
     gen_fsm:start(Name, ?MODULE, [Mod, Args], Options).
 
     gen_fsm:start(Name, ?MODULE, [Mod, Args], Options).
  
start_link(Mod, Args, Options) ->
+
start_link(Mod, Args, Options) -&gt;
 
     gen_fsm:start_link(?MODULE, [Mod, Args], Options).
 
     gen_fsm:start_link(?MODULE, [Mod, Args], Options).
  
start_link(Name, Mod, Args, Options) ->
+
start_link(Name, Mod, Args, Options) -&gt;
 
     gen_fsm:start_link(Name, ?MODULE, [Mod, Args], Options).
 
     gen_fsm:start_link(Name, ?MODULE, [Mod, Args], Options).
  
Line 178:Line 207:
 
%% They are included for completeness only.
 
%% They are included for completeness only.
  
send_event(Name, Event) ->
+
send_event(Name, Event) -&gt;
 
     gen_fsm:send_event(Name, Event).
 
     gen_fsm:send_event(Name, Event).
  
sync_send_event(Name, Event) ->
+
sync_send_event(Name, Event) -&gt;
 
     gen_fsm:sync_send_event(Name, Event).
 
     gen_fsm:sync_send_event(Name, Event).
  
sync_send_event(Name, Event, Timeout) ->
+
sync_send_event(Name, Event, Timeout) -&gt;
 
     gen_fsm:sync_send_event(Name, Event, Timeout).
 
     gen_fsm:sync_send_event(Name, Event, Timeout).
  
send_all_state_event(Name, Event) ->
+
send_all_state_event(Name, Event) -&gt;
 
     gen_fsm:send_all_state_event(Name, Event).
 
     gen_fsm:send_all_state_event(Name, Event).
  
sync_send_all_state_event(Name, Event) ->
+
sync_send_all_state_event(Name, Event) -&gt;
 
     gen_fsm:sync_send_all_state_event(Name, Event).
 
     gen_fsm:sync_send_all_state_event(Name, Event).
  
sync_send_all_state_event(Name, Event, Timeout) ->
+
sync_send_all_state_event(Name, Event, Timeout) -&gt;
 +
 
 
     gen_fsm:sync_send_all_state_event(Name, Event, Timeout).
 
     gen_fsm:sync_send_all_state_event(Name, Event, Timeout).
  
start_timer(Time, Msg) ->
+
start_timer(Time, Msg) -&gt;
 
     gen_fsm:start_timer(Time, Msg).
 
     gen_fsm:start_timer(Time, Msg).
  
send_event_after(Time, Event) ->
+
send_event_after(Time, Event) -&gt;
 
     gen_fsm:send_event_after(Time, Event).
 
     gen_fsm:send_event_after(Time, Event).
  
cancel_timer(Ref) ->
+
cancel_timer(Ref) -&gt;
 
     gen_fsm:cancel_timer(Ref).
 
     gen_fsm:cancel_timer(Ref).
  
reply(Caller, Reply) ->
+
reply(Caller, Reply) -&gt;
 
     gen_fsm:reply(Caller, Reply).
 
     gen_fsm:reply(Caller, Reply).
  
 
%% Our start function above added the user's module name
 
%% Our start function above added the user's module name
 
%% to the arguments.  We store this in our state data record.
 
%% to the arguments.  We store this in our state data record.
 +
 
%% After performing our chattyness we run the user's init/1
 
%% After performing our chattyness we run the user's init/1
 
%% and store the user's next state name and state data in
 
%% and store the user's next state name and state data in
 
%% our internal state data record for later reference.
 
%% our internal state data record for later reference.
init([Mod, Args]) ->
+
init([Mod, Args]) -&gt;
     io:fwrite("~w:init(~w) -> ", [Mod, Args]),
+
     io:fwrite("~w:init(~w) -&gt; ", [Mod, Args]),
 
     case Mod:init(Args) of
 
     case Mod:init(Args) of
         {ok, ExtStateName, ExtStateData} ->
+
         {ok, ExtStateName, ExtStateData} -&gt;
 
             io:fwrite("    {ok, ~w, ~w}~n", [ExtStateName, ExtStateData]),
 
             io:fwrite("    {ok, ~w, ~w}~n", [ExtStateName, ExtStateData]),
 
             StateData = #state{module = Mod, state = ExtStateName,
 
             StateData = #state{module = Mod, state = ExtStateName,
 
                 data = ExtStateData},
 
                 data = ExtStateData},
 
             {ok, state, StateData};
 
             {ok, state, StateData};
         {ok, ExtStateName, ExtStateData, Timeout} ->
+
         {ok, ExtStateName, ExtStateData, Timeout} -&gt;
 +
 
 
             io:fwrite("    {ok, ~w, ~w, ~w}~n",
 
             io:fwrite("    {ok, ~w, ~w, ~w}~n",
 
                 [ExtStateName, ExtStateData, Timeout]),
 
                 [ExtStateName, ExtStateData, Timeout]),
Line 227:Line 259:
 
                 data = ExtStateData},
 
                 data = ExtStateData},
 
             {ok, state, StateData, Timeout};
 
             {ok, state, StateData, Timeout};
         {stop, Reason} ->
+
         {stop, Reason} -&gt;
 
             io:fwrite("    {stop, ~w}~n", [Reason]),
 
             io:fwrite("    {stop, ~w}~n", [Reason]),
 
             {stop, Reason};
 
             {stop, Reason};
         Other ->
+
         Other -&gt;
 
             io:fwrite("    ~w~n", [Other]),
 
             io:fwrite("    ~w~n", [Other]),
 
             Other
 
             Other
Line 239:Line 271:
 
%% name and call that handler with the current event
 
%% name and call that handler with the current event
 
%% and the user's state data.
 
%% and the user's state data.
state(Event, StateData) ->
+
 
 +
state(Event, StateData) -&gt;
 
     Mod = StateData#state.module,
 
     Mod = StateData#state.module,
 
     ExtStateName = StateData#state.state,
 
     ExtStateName = StateData#state.state,
 
     ExtStateData = StateData#state.data,
 
     ExtStateData = StateData#state.data,
     io:fwrite("~w:~w(~w, ~w) ->~n",
+
     io:fwrite("~w:~w(~w, ~w) -&gt;~n",
 
         [Mod, ExtStateName, Event, ExtStateData]),
 
         [Mod, ExtStateName, Event, ExtStateData]),
 
     Result = Mod:ExtStateName(Event, ExtStateData),
 
     Result = Mod:ExtStateName(Event, ExtStateData),
Line 250:Line 283:
 
%% The other gen_fsm callbacks are handled the same as above.
 
%% The other gen_fsm callbacks are handled the same as above.
  
handle_event(Event, StateName, StateData) ->
+
handle_event(Event, StateName, StateData) -&gt;
 
     Mod = StateData#state.module,
 
     Mod = StateData#state.module,
 
     ExtStateName = StateData#state.state,
 
     ExtStateName = StateData#state.state,
 
     ExtStateData = StateData#state.data,
 
     ExtStateData = StateData#state.data,
     io:fwrite("~w:handle_event(~w, ~w, ~w) ->~n",
+
     io:fwrite("~w:handle_event(~w, ~w, ~w) -&gt;~n",
 
         [Mod, Event, ExtStateName, ExtStateData]),
 
         [Mod, Event, ExtStateName, ExtStateData]),
 
     Result = Mod:handle_event(Event, ExtStateName, ExtStateData),
 
     Result = Mod:handle_event(Event, ExtStateName, ExtStateData),
 
     handle_result(Result, StateName, StateData).
 
     handle_result(Result, StateName, StateData).
  
handle_sync_event(Event, From, StateName, StateData) ->
+
handle_sync_event(Event, From, StateName, StateData) -&gt;
 
     Mod = StateData#state.module,
 
     Mod = StateData#state.module,
 
     ExtStateName = StateData#state.state,
 
     ExtStateName = StateData#state.state,
 
     ExtStateData = StateData#state.data,
 
     ExtStateData = StateData#state.data,
     io:fwrite("~w:handle_sync_event(~w, ~w, ~w, ~w) ->~n",
+
     io:fwrite("~w:handle_sync_event(~w, ~w, ~w, ~w) -&gt;~n",
 
         [Mod, Event, From, ExtStateName, ExtStateData]),
 
         [Mod, Event, From, ExtStateName, ExtStateData]),
 
     Result = Mod:handle_sync_event(Event, From, ExtStateName, ExtStateData),
 
     Result = Mod:handle_sync_event(Event, From, ExtStateName, ExtStateData),
 
     handle_result(Result, StateName, StateData).
 
     handle_result(Result, StateName, StateData).
  
handle_info(Info, StateName, StateData) ->
+
handle_info(Info, StateName, StateData) -&gt;
 +
 
 
     Mod = StateData#state.module,
 
     Mod = StateData#state.module,
 
     ExtStateName = StateData#state.state,
 
     ExtStateName = StateData#state.state,
 
     ExtStateData = StateData#state.data,
 
     ExtStateData = StateData#state.data,
     io:fwrite("~w:handle_info(~w, ~w, ~w) ->~n",
+
     io:fwrite("~w:handle_info(~w, ~w, ~w) -&gt;~n",
 
         [Mod, Info, ExtStateName, ExtStateData]),
 
         [Mod, Info, ExtStateName, ExtStateData]),
 
     Result = Mod:handle_info(Info, ExtStateName, ExtStateData),
 
     Result = Mod:handle_info(Info, ExtStateName, ExtStateData),
 
     handle_result(Result, StateName, StateData).
 
     handle_result(Result, StateName, StateData).
  
terminate(Reason, _StateName, StateData) ->
+
terminate(Reason, _StateName, StateData) -&gt;
 
     Mod = StateData#state.module,
 
     Mod = StateData#state.module,
 
     ExtStateName = StateData#state.state,
 
     ExtStateName = StateData#state.state,
 
     ExtStateData = StateData#state.data,
 
     ExtStateData = StateData#state.data,
     io:fwrite("~w:terminate(~w, ~w, ~w) ->~n",
+
     io:fwrite("~w:terminate(~w, ~w, ~w) -&gt;~n",
 
         [Mod, Reason, ExtStateName, ExtStateData]),
 
         [Mod, Reason, ExtStateName, ExtStateData]),
 
     Mod:terminate(Reason, ExtStateName, ExtStateData).
 
     Mod:terminate(Reason, ExtStateName, ExtStateData).
  
code_change(OldVsn, StateName, StateData, Extra) ->
+
code_change(OldVsn, StateName, StateData, Extra) -&gt;
 
     Mod = StateData#state.module,
 
     Mod = StateData#state.module,
 
     ExtStateName = StateData#state.state,
 
     ExtStateName = StateData#state.state,
 
     ExtStateData = StateData#state.data,
 
     ExtStateData = StateData#state.data,
     io:fwrite("~w:code_change(~w, ~w, ~w, ~w) ->~n",
+
     io:fwrite("~w:code_change(~w, ~w, ~w, ~w) -&gt;~n",
 
         [Mod, OldVsn, ExtStateName, ExtStateData, Extra]),
 
         [Mod, OldVsn, ExtStateName, ExtStateData, Extra]),
 
     case Mod:code_change(OldVsn, ExtStateName, ExtStateData, Extra) of
 
     case Mod:code_change(OldVsn, ExtStateName, ExtStateData, Extra) of
         {ok, NewExtStateName, NewExtStateData} ->
+
         {ok, NewExtStateName, NewExtStateData} -&gt;
 
             io:fwrite("    {ok, ~w, ~w}~n",
 
             io:fwrite("    {ok, ~w, ~w}~n",
 
                 NewExtStateName, NewExtStateData),
 
                 NewExtStateName, NewExtStateData),
Line 298:Line 332:
 
                 data = NewExtStateData},
 
                 data = NewExtStateData},
 
             {ok, StateName, NewStateData};
 
             {ok, StateName, NewStateData};
         Else ->
+
         Else -&gt;
 
             Else
 
             Else
 
     end.
 
     end.
  
 
%% This function handles the common result set of callbacks.
 
%% This function handles the common result set of callbacks.
 +
 
handle_result({next_state, NewExtStateName, NewExtStateData},
 
handle_result({next_state, NewExtStateName, NewExtStateData},
         StateName, StateData) ->
+
         StateName, StateData) -&gt;
 
     io:fwrite("    {next_state, ~w, ~w}~n",
 
     io:fwrite("    {next_state, ~w, ~w}~n",
 
         [NewExtStateName, NewExtStateData]),
 
         [NewExtStateName, NewExtStateData]),
Line 311:Line 346:
 
     {next_state, StateName, NewStateData};
 
     {next_state, StateName, NewStateData};
 
handle_result({next_state, NewExtStateName, NewExtStateData, Timeout},
 
handle_result({next_state, NewExtStateName, NewExtStateData, Timeout},
         StateName, StateData) ->
+
         StateName, StateData) -&gt;
 
     io:fwrite("    {next_state, ~w, ~w, ~w}~n",
 
     io:fwrite("    {next_state, ~w, ~w, ~w}~n",
 
         [NewExtStateName, NewExtStateData, Timeout]),
 
         [NewExtStateName, NewExtStateData, Timeout]),
Line 318:Line 353:
 
     {next_state, StateName, NewStateData, Timeout};
 
     {next_state, StateName, NewStateData, Timeout};
 
handle_result({reply, Reply, NewExtStateName, NewExtStateData},
 
handle_result({reply, Reply, NewExtStateName, NewExtStateData},
         StateName, StateData) ->
+
         StateName, StateData) -&gt;
 
     io:fwrite("    {reply, ~w, ~w, ~w}~n",
 
     io:fwrite("    {reply, ~w, ~w, ~w}~n",
 
         [Reply, NewExtStateName, NewExtStateData]),
 
         [Reply, NewExtStateName, NewExtStateData]),
Line 325:Line 360:
 
     {reply, Reply, StateName, NewStateData};
 
     {reply, Reply, StateName, NewStateData};
 
handle_result({reply, Reply, NewExtStateName, NewExtStateData, Timeout},
 
handle_result({reply, Reply, NewExtStateName, NewExtStateData, Timeout},
         StateName, StateData) ->
+
         StateName, StateData) -&gt;
 
     io:fwrite("    {reply, ~w, ~w, ~w, ~w}~n",
 
     io:fwrite("    {reply, ~w, ~w, ~w, ~w}~n",
 
         [Reply, NewExtStateName, NewExtStateData, Timeout]),
 
         [Reply, NewExtStateName, NewExtStateData, Timeout]),
Line 331:Line 366:
 
         data = NewExtStateData},
 
         data = NewExtStateData},
 
     {reply, Reply, StateName, NewStateData, Timeout};
 
     {reply, Reply, StateName, NewStateData, Timeout};
handle_result({stop, Reason, NewExtStateData}, _StateName, StateData) ->
+
handle_result({stop, Reason, NewExtStateData}, _StateName, StateData) -&gt;
 
     io:fwrite("    {stop, ~w, ~w}~n", [Reason, NewExtStateData]),
 
     io:fwrite("    {stop, ~w, ~w}~n", [Reason, NewExtStateData]),
 
     NewStateData = StateData#state{data = NewExtStateData},
 
     NewStateData = StateData#state{data = NewExtStateData},
 
     {stop, Reason, NewStateData};
 
     {stop, Reason, NewStateData};
 
handle_result({stop, Reason, Reply, NewExtStateData},
 
handle_result({stop, Reason, Reply, NewExtStateData},
         _StateName, StateData) ->
+
         _StateName, StateData) -&gt;
 +
 
 
     io:fwrite("    {stop, ~w, ~w, ~w}~n",
 
     io:fwrite("    {stop, ~w, ~w, ~w}~n",
 
         [Reason, Reply, NewExtStateData]),
 
         [Reason, Reply, NewExtStateData]),
 
     NewStateData = StateData#state{data = NewExtStateData},
 
     NewStateData = StateData#state{data = NewExtStateData},
 
     {stop, Reason, Reply, NewStateData};
 
     {stop, Reason, Reply, NewStateData};
handle_result(Other, _StateName, _StateData) ->
+
handle_result(Other, _StateName, _StateData) -&gt;
 
     io:fwrite("    ~w~n", [Other]),
 
     io:fwrite("    ~w~n", [Other]),
 
     Other.
 
     Other.
 +
</code>
  
==5. Using the New Behaviour==
+
==Using the New Behaviour==
  
 
===Module===  
 
===Module===  
Line 351:Line 388:
 
You write a callback module for chatty_fsm behaviours exactly as you would for gen_fsm.
 
You write a callback module for chatty_fsm behaviours exactly as you would for gen_fsm.
  
Code listing 5.1: Behaviour Attribute
+
<code caption="Code listing 5.1: Behaviour Attribute">
  
 
-behaviour(chatty_fsm).
 
-behaviour(chatty_fsm).
  
Code listing 5.2: Required chatty_fsm Callbacks
+
</code>
 +
 
 +
<code caption="Code listing 5.2: Required chatty_fsm Callbacks">
  
 
-export([init/1, handle_event/3, handle_sync_event/4,
 
-export([init/1, handle_event/3, handle_sync_event/4,
 
         handle_info/3, terminate/3, code_change/4]).
 
         handle_info/3, terminate/3, code_change/4]).
 
+
</code>
Note: In this example we export an identical interface to the callback module as imported from gen_fsm. In another example we might have defined a different list of required callbacks.
+
<table class="ncontent" width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td bgcolor="#bbffbb"><p class="note"><b>Note: </b>In this example we export an identical interface to the callback
 
+
module as imported from gen_fsm. In another example we might have defined
Code listing 5.3: State Handler Callbacks
+
a different list of required callbacks.</p></td></tr></table>
 +
<code caption="Code listing 5.3: State Handler Callbacks">
  
 
-export([idle/2, busy/2]).
 
-export([idle/2, busy/2]).
 
+
</code>
 
===Startup===  
 
===Startup===  
  
 
We can now use chatty_fsm anywhere we would use gen_fsm. It exports the same API as gen_fsm and behaves identically only it adds chattyness.
 
We can now use chatty_fsm anywhere we would use gen_fsm. It exports the same API as gen_fsm and behaves identically only it adds chattyness.
  
Code listing 5.4: Starting a chatty_fsm FSM
+
<code caption="Code listing 5.4: Starting a chatty_fsm FSM">
  
1> {ok, FSM} = chatty_fsm:start(simple_fsm, [], []).
+
1&gt; {ok, FSM} = chatty_fsm:start(simple_fsm, [], []).
simple_fsm:init([]) ->
+
simple_fsm:init([]) -&gt;
 
     {ok, idle, {state}}
 
     {ok, idle, {state}}
{ok,<0.31.0>}
+
{ok,&lt;0.31.0&gt;}
  
Code listing 5.5: Sending an Event
+
</code>
  
2> chatty_fsm:send_event(FSM, foo).
+
<code caption="Code listing 5.5: Sending an Event">
simple_fsm:idle(foo, {state}) ->
+
 
 +
2&gt; chatty_fsm:send_event(FSM, foo).
 +
simple_fsm:idle(foo, {state}) -&gt;
 
ok    {next_state, idle, {state}}
 
ok    {next_state, idle, {state}}
 +
 +
</code>
  
 
You could write a simliar behaviour to do much more interesting things.
 
You could write a simliar behaviour to do much more interesting things.
  
==6. Conclusion==
+
==Conclusion==
  
 
===Cascading Behaviours===  
 
===Cascading Behaviours===  
Line 392:Line 436:
  
 
An interesting example would be a complex finite state machine implemented in several behaviour modules such that the outermost had only a few states. Some of these states might be implemented as FSMs in inner behaviour modules.
 
An interesting example would be a complex finite state machine implemented in several behaviour modules such that the outermost had only a few states. Some of these states might be implemented as FSMs in inner behaviour modules.
 +
 +
==Download xml==
 +
[http://wiki.trapexit.erlang-consulting.com/upload/howto/cascading_behaviours.xml cascading_behaviours.xml]
 +
 +
[[Category:HowTo]]

Revision as of 18:08, 15 June 2007

Contents

Author

Vance Shipley

Introduction

Behaviours

Behaviour modules encapsulate some certain functionality for reuse by other modules. The definition of a behaviour includes not only it's exported functions but a list of functions which a callback module must implement. OTP includes several behaviour modules with the most common being gen_server and gen_fsm.

Using gen_fsm

Behaviour

To declare your module as a behaviour callback module you include the -behaviour attribute.


-behaviour(gen_fsm).

Note: All this really does is to enable compilation time checking that you have exported the required callbacks.

Exports

A module which uses the gen_fsm behaviour must export the callbacks which the gen_fsm module calls to handle events. These include handlers for common gen_fsm events as well as the handlers for your user defined states.


-export([init/1, handle_event/3, handle_sync_event/4,
         handle_info/3, terminate/3, code_change/4]).


-export([idle/2, busy/2]).

Startup

To start a process implemented in a module as a gen_fsm behaviour you may call gen_fsm:start/3. In response this function will call the init/1 callback in your module. After your init/1 function returns a result gen_fsm:start_link/3 will return the appropriate result to the calling process. Normally the result is to create a new process where the gen_fsm module is running it's internal main loop function waiting for messages to arrive.


2> {ok, FSM} = gen_fsm:start(simple_fsm, [], []).
{ok,<0.36.0>}

Events

To send an event to your finite state machine process you may call gen_fsm:send_event/2.


2> gen_fsm:send_event(FSM, foo).

ok

The result is that a message is sent to your FSM process tagged so that the gen_fsm module may recognize it as a gen_fsm generated event. When the main loop function in gen_fsm receives this message it will call the state handler callback in your module corresponding to the current state the FSM process is in.

An Example FSM

The Module

Below is a very simple example of a module implemented with a gen_fsm behaviour. In this module we will implement just one state and the only thing it will really do is to be chatty about what is going on.


-module(chatty_fsm).

-export([init/1, handle_event/3, handle_sync_event/4,
         handle_info/3, terminate/3, code_change/4]).
-export([idle/2]).

-behaviour(gen_fsm).

-record(state, {}).

init(Args) ->
    process_flag(trap_exit, true),
    io:fwrite("gen_fsm called ~w:init(~w)~n", [?MODULE, Args]),
    {ok, idle, #state{}}.

idle(Event, StateData) ->
    io:fwrite("gen_fsm called ~w:idle(~w, ~w)~n", 
        [?MODULE, Event, StateData]),
    {next_state, idle, StateData}.

handle_event(Event, StateName, StateData) ->
    io:fwrite("gen_fsm called ~w:handle_event(~w, ~w, ~w)~n",
        [?MODULE, Event, StateName, StateData]),
    {next_state, StateName, StateData}.

handle_sync_event(Event, From, StateName, StateData) ->
    io:fwrite("gen_fsm called ~w:handle_sync_event(~w, ~w, ~w, ~w)~n",
        [?MODULE, Event, From, StateName, StateData]),
    {next_state, StateName, StateData}.

handle_info(Info, StateName, StateData) ->
    io:fwrite("gen_fsm called ~w:handle_info(~w, ~w, ~w)~n",
        [?MODULE, Info, StateName, StateData]),
    {next_state, StateName, StateData}.

terminate(Reason, StateName, StateData) ->

    io:fwrite("gen_fsm called ~w:terminate(~w, ~w, ~w)~n",
        [?MODULE, Reason, StateName, StateData]).

code_change(OldVsn, StateName, StateData, Extra) ->
    io:fwrite("gen_fsm called ~w:code_change(~w, ~w, ~w, ~w)~n",
        [?MODULE, OldVsn, StateName, StateData, Extra]),
    {ok, StateName, StateData}.

Running the Chatty FSM

When we start this module and send it an event as above we will see the functions in our callback module being called.


1> {ok, FSM} = gen_fsm:start(chatty_fsm, [], []).
gen_fsm called chatty_fsm:init([])
{ok,<0.31.0>}


2> gen_fsm:send_event(FSM, foo).

gen_fsm called chatty_fsm:idle(foo, {state})
ok

Creating a New Behaviour

A Chatty FSM Behaviour

Now we may decide that a chatty FSM is a useful thing in a very general way. If we want to make other FSMs chatty we can put this functionality into a behaviour which our FSM modules may behave to. The basic idea is that we will implement the callbacks which the gen_fsm module will call as pass through functions to the callbacks in the user's module. These pass through functions will simply perform the chattyness and then call the FSM module's identical callbacks.

The Module

Note:

It is not suggested that this module performs a useful purpose as it is. There are better solutions to add event tracing including passing the gen_fsm start function the {debug, [trace]} option. The intent is to demonstrate an enhanced behaviour.


-module(chatty_fsm).

%% Export the same API as gen_fsm.
-export([start/3, start/4, start_link/3, start_link/4,
         send_event/2, sync_send_event/2, sync_send_event/3,
         send_all_state_event/2, sync_send_all_state_event/2,
         sync_send_all_state_event/3, reply/2, start_timer/2,
         send_event_after/2,cancel_timer/1]).

%% Export the callbacks gen_fsm expects.
-export([init/1, handle_event/3, handle_sync_event/4,
         handle_info/3, terminate/3, code_change/4]).
-export([state/2]).

%% Define the behaviour's required callbacks.
-export([behaviour_info/1]).

behaviour_info(callbacks) ->

    [{init,1},{handle_event,3},{handle_sync_event,4},
        {handle_info,3}, {terminate,3},{code_change,4}];
behaviour_info(_Other) ->
    undefined.

%% Define this module as a gen_fsm callback module.
-behaviour(gen_fsm).

%% State data record.
-record(state, {module, state, data}).

%% Users will use these start functions instead of gen_fsm's.
%% We add the user's module name to the arguments and call
%% gen_fsm's start function with our module name instead.

start(Mod, Args, Options) ->
    gen_fsm:start(?MODULE, [Mod, Args], Options).

start(Name, Mod, Args, Options) ->
    gen_fsm:start(Name, ?MODULE, [Mod, Args], Options).

start_link(Mod, Args, Options) ->
    gen_fsm:start_link(?MODULE, [Mod, Args], Options).

start_link(Name, Mod, Args, Options) ->
    gen_fsm:start_link(Name, ?MODULE, [Mod, Args], Options).

%% These functions are just pass through to gen_fsm.
%% They are included for completeness only.

send_event(Name, Event) ->
    gen_fsm:send_event(Name, Event).

sync_send_event(Name, Event) ->
    gen_fsm:sync_send_event(Name, Event).

sync_send_event(Name, Event, Timeout) ->
    gen_fsm:sync_send_event(Name, Event, Timeout).

send_all_state_event(Name, Event) ->
    gen_fsm:send_all_state_event(Name, Event).

sync_send_all_state_event(Name, Event) ->
    gen_fsm:sync_send_all_state_event(Name, Event).

sync_send_all_state_event(Name, Event, Timeout) ->

    gen_fsm:sync_send_all_state_event(Name, Event, Timeout).

start_timer(Time, Msg) ->
    gen_fsm:start_timer(Time, Msg).

send_event_after(Time, Event) ->
    gen_fsm:send_event_after(Time, Event).

cancel_timer(Ref) ->
    gen_fsm:cancel_timer(Ref).

reply(Caller, Reply) ->
    gen_fsm:reply(Caller, Reply).

%% Our start function above added the user's module name
%% to the arguments.  We store this in our state data record.

%% After performing our chattyness we run the user's init/1
%% and store the user's next state name and state data in
%% our internal state data record for later reference.
init([Mod, Args]) ->
    io:fwrite("~w:init(~w) -> ", [Mod, Args]),
    case Mod:init(Args) of
        {ok, ExtStateName, ExtStateData} -> 
            io:fwrite("    {ok, ~w, ~w}~n", [ExtStateName, ExtStateData]),
            StateData = #state{module = Mod, state = ExtStateName,
                data = ExtStateData},
            {ok, state, StateData};
        {ok, ExtStateName, ExtStateData, Timeout} ->

            io:fwrite("    {ok, ~w, ~w, ~w}~n",
                [ExtStateName, ExtStateData, Timeout]),
            StateData = #state{module = Mod, state = ExtStateName,
                data = ExtStateData},
            {ok, state, StateData, Timeout};
        {stop, Reason} ->
            io:fwrite("    {stop, ~w}~n", [Reason]),
            {stop, Reason};
        Other ->
            io:fwrite("    ~w~n", [Other]),
            Other
    end.

%% We use only one state handler for this module.
%% After being chatty we look up the user's current state
%% name and call that handler with the current event
%% and the user's state data.

state(Event, StateData) ->
    Mod = StateData#state.module,
    ExtStateName = StateData#state.state,
    ExtStateData = StateData#state.data,
    io:fwrite("~w:~w(~w, ~w) ->~n",
        [Mod, ExtStateName, Event, ExtStateData]),
    Result = Mod:ExtStateName(Event, ExtStateData),
    handle_result(Result, state, StateData).

%% The other gen_fsm callbacks are handled the same as above.

handle_event(Event, StateName, StateData) ->
    Mod = StateData#state.module,
    ExtStateName = StateData#state.state,
    ExtStateData = StateData#state.data,
    io:fwrite("~w:handle_event(~w, ~w, ~w) ->~n",
        [Mod, Event, ExtStateName, ExtStateData]),
    Result = Mod:handle_event(Event, ExtStateName, ExtStateData),
    handle_result(Result, StateName, StateData).

handle_sync_event(Event, From, StateName, StateData) ->
    Mod = StateData#state.module,
    ExtStateName = StateData#state.state,
    ExtStateData = StateData#state.data,
    io:fwrite("~w:handle_sync_event(~w, ~w, ~w, ~w) ->~n",
        [Mod, Event, From, ExtStateName, ExtStateData]),
    Result = Mod:handle_sync_event(Event, From, ExtStateName, ExtStateData),
    handle_result(Result, StateName, StateData).

handle_info(Info, StateName, StateData) ->

    Mod = StateData#state.module,
    ExtStateName = StateData#state.state,
    ExtStateData = StateData#state.data,
    io:fwrite("~w:handle_info(~w, ~w, ~w) ->~n",
        [Mod, Info, ExtStateName, ExtStateData]),
    Result = Mod:handle_info(Info, ExtStateName, ExtStateData),
    handle_result(Result, StateName, StateData).

terminate(Reason, _StateName, StateData) ->
    Mod = StateData#state.module,
    ExtStateName = StateData#state.state,
    ExtStateData = StateData#state.data,
    io:fwrite("~w:terminate(~w, ~w, ~w) ->~n",
        [Mod, Reason, ExtStateName, ExtStateData]),
    Mod:terminate(Reason, ExtStateName, ExtStateData).

code_change(OldVsn, StateName, StateData, Extra) ->
    Mod = StateData#state.module,
    ExtStateName = StateData#state.state,
    ExtStateData = StateData#state.data,
    io:fwrite("~w:code_change(~w, ~w, ~w, ~w) ->~n",
        [Mod, OldVsn, ExtStateName, ExtStateData, Extra]),
    case Mod:code_change(OldVsn, ExtStateName, ExtStateData, Extra) of
        {ok, NewExtStateName, NewExtStateData} ->
            io:fwrite("    {ok, ~w, ~w}~n",
                NewExtStateName, NewExtStateData),
            NewStateData = StateData#state{state = NewExtStateName,
                data = NewExtStateData},
            {ok, StateName, NewStateData};
        Else ->
            Else
    end.

%% This function handles the common result set of callbacks.

handle_result({next_state, NewExtStateName, NewExtStateData},
        StateName, StateData) ->
    io:fwrite("    {next_state, ~w, ~w}~n",
        [NewExtStateName, NewExtStateData]),
    NewStateData = StateData#state{state = NewExtStateName,
        data = NewExtStateData},
    {next_state, StateName, NewStateData};
handle_result({next_state, NewExtStateName, NewExtStateData, Timeout},
        StateName, StateData) ->
    io:fwrite("    {next_state, ~w, ~w, ~w}~n",
        [NewExtStateName, NewExtStateData, Timeout]),
    NewStateData = StateData#state{state = NewExtStateName,
        data = NewExtStateData},
    {next_state, StateName, NewStateData, Timeout};
handle_result({reply, Reply, NewExtStateName, NewExtStateData},
        StateName, StateData) ->
    io:fwrite("    {reply, ~w, ~w, ~w}~n",
        [Reply, NewExtStateName, NewExtStateData]),
    NewStateData = StateData#state{state = NewExtStateName,
        data = NewExtStateData},
    {reply, Reply, StateName, NewStateData};
handle_result({reply, Reply, NewExtStateName, NewExtStateData, Timeout},
        StateName, StateData) ->
    io:fwrite("    {reply, ~w, ~w, ~w, ~w}~n",
        [Reply, NewExtStateName, NewExtStateData, Timeout]),
    NewStateData = StateData#state{state = NewExtStateName,
        data = NewExtStateData},
    {reply, Reply, StateName, NewStateData, Timeout};
handle_result({stop, Reason, NewExtStateData}, _StateName, StateData) ->
    io:fwrite("    {stop, ~w, ~w}~n", [Reason, NewExtStateData]),
    NewStateData = StateData#state{data = NewExtStateData},
    {stop, Reason, NewStateData};
handle_result({stop, Reason, Reply, NewExtStateData},
        _StateName, StateData) ->

    io:fwrite("    {stop, ~w, ~w, ~w}~n",
        [Reason, Reply, NewExtStateData]),
    NewStateData = StateData#state{data = NewExtStateData},
    {stop, Reason, Reply, NewStateData};
handle_result(Other, _StateName, _StateData) ->
    io:fwrite("    ~w~n", [Other]),
    Other.

Using the New Behaviour

Module

You write a callback module for chatty_fsm behaviours exactly as you would for gen_fsm.


-behaviour(chatty_fsm).


-export([init/1, handle_event/3, handle_sync_event/4,
         handle_info/3, terminate/3, code_change/4]).

Note: In this example we export an identical interface to the callback

module as imported from gen_fsm. In another example we might have defined

a different list of required callbacks.


-export([idle/2, busy/2]).

Startup

We can now use chatty_fsm anywhere we would use gen_fsm. It exports the same API as gen_fsm and behaves identically only it adds chattyness.


1> {ok, FSM} = chatty_fsm:start(simple_fsm, [], []).
simple_fsm:init([]) ->
    {ok, idle, {state}}
{ok,<0.31.0>}


2> chatty_fsm:send_event(FSM, foo).
simple_fsm:idle(foo, {state}) ->
ok    {next_state, idle, {state}}

You could write a simliar behaviour to do much more interesting things.

Conclusion

Cascading Behaviours

It has been shown that behaviour callback modules may also be behaviour modules. You may create a chain of callbacks of indefinite length.

An interesting example would be a complex finite state machine implemented in several behaviour modules such that the outermost had only a few states. Some of these states might be implemented as FSMs in inner behaviour modules.

Download xml

cascading_behaviours.xml