.TH gen_statem 3erl "stdlib 3.2" "Ericsson AB" "Erlang Module Definition" .SH NAME gen_statem \- Generic state machine behavior. .SH DESCRIPTION .LP This behavior module provides a state machine\&. Two \fB\fIcallback modes\fR\&\fR\& are supported: .RS 2 .TP 2 * One for finite-state machines (\fB\fIgen_fsm\fR\&\fR\& like), which requires the state to be an atom and uses that state as the name of the current callback function .LP .TP 2 * One without restriction on the state data type that uses one callback function for all states .LP .RE .LP .RS -4 .B Note: .RE This is a new behavior in Erlang/OTP 19\&.0\&. It has been thoroughly reviewed, is stable enough to be used by at least two heavy OTP applications, and is here to stay\&. Depending on user feedback, we do not expect but can find it necessary to make minor not backward compatible changes into Erlang/OTP 20\&.0\&. .LP The \fIgen_statem\fR\& behavior is intended to replace \fB\fIgen_fsm\fR\&\fR\& for new code\&. It has the same features and adds some really useful: .RS 2 .TP 2 * State code is gathered\&. .LP .TP 2 * The state can be any term\&. .LP .TP 2 * Events can be postponed\&. .LP .TP 2 * Events can be self-generated\&. .LP .TP 2 * Automatic state enter code can be called\&. .LP .TP 2 * A reply can be sent from a later state\&. .LP .TP 2 * There can be multiple \fIsys\fR\& traceable replies\&. .LP .RE .LP The callback model(s) for \fIgen_statem\fR\& differs from the one for \fB\fIgen_fsm\fR\&\fR\&, but it is still fairly easy to rewrite from \fIgen_fsm\fR\& to \fIgen_statem\fR\&\&. .LP A generic state machine process (\fIgen_statem\fR\&) implemented using this module has a standard set of interface functions and includes functionality for tracing and error reporting\&. It also fits into an OTP supervision tree\&. For more information, see \fBOTP Design Principles\fR\&\&. .LP A \fIgen_statem\fR\& assumes all specific parts to be located in a callback module exporting a predefined set of functions\&. The relationship between the behavior functions and the callback functions is as follows: .LP .nf gen_statem module Callback module ----------------- --------------- gen_statem:start gen_statem:start_link -----> Module:init/1 Server start or code change -----> Module:callback_mode/0 gen_statem:stop -----> Module:terminate/3 gen_statem:call gen_statem:cast erlang:send erlang:'!' -----> Module:StateName/3 Module:handle_event/4 - -----> Module:terminate/3 - -----> Module:code_change/4 .fi .LP Events are of different \fBtypes\fR\&, so the callback functions can know the origin of an event and how to respond\&. .LP If a callback function fails or returns a bad value, the \fIgen_statem\fR\& terminates, unless otherwise stated\&. However, an exception of class \fB\fIthrow\fR\&\fR\& is not regarded as an error but as a valid return from all callback functions\&. .LP The "\fIstate callback\fR\&" for a specific \fBstate\fR\& in a \fIgen_statem\fR\& is the callback function that is called for all events in this state\&. It is selected depending on which \fB\fIcallback mode\fR\&\fR\& that the callback module defines with the callback function \fB\fIModule:callback_mode/0\fR\&\fR\&\&. .LP When the \fB\fIcallback mode\fR\&\fR\& is \fIstate_functions\fR\&, the state must be an atom and is used as the state callback name; see \fB\fIModule:StateName/3\fR\&\fR\&\&. This gathers all code for a specific state in one function as the \fIgen_statem\fR\& engine branches depending on state name\&. Notice the fact that there is a mandatory callback function \fB\fIModule:terminate/3\fR\&\fR\& makes the state name \fIterminate\fR\& unusable in this mode\&. .LP When the \fB\fIcallback mode\fR\&\fR\& is \fIhandle_event_function\fR\&, the state can be any term and the state callback name is \fB\fIModule:handle_event/4\fR\&\fR\&\&. This makes it easy to branch depending on state or event as you desire\&. Be careful about which events you handle in which states so that you do not accidentally postpone an event forever creating an infinite busy loop\&. .LP The \fIgen_statem\fR\& enqueues incoming events in order of arrival and presents these to the \fBstate callback\fR\& in that order\&. The state callback can postpone an event so it is not retried in the current state\&. After a state change the queue restarts with the postponed events\&. .LP The \fIgen_statem\fR\& event queue model is sufficient to emulate the normal process message queue with selective receive\&. Postponing an event corresponds to not matching it in a receive statement, and changing states corresponds to entering a new receive statement\&. .LP The \fBstate callback\fR\& can insert events using the \fB\fIaction()\fR\&\fR\& \fInext_event\fR\& and such an event is inserted as the next to present to the state callback\&. That is, as if it is the oldest incoming event\&. A dedicated \fB\fIevent_type()\fR\&\fR\& \fIinternal\fR\& can be used for such events making them impossible to mistake for external events\&. .LP Inserting an event replaces the trick of calling your own state handling functions that you often would have to resort to in, for example, \fB\fIgen_fsm\fR\&\fR\& to force processing an inserted event before others\&. .LP The \fIgen_statem\fR\& engine can automatically make a specialized call to the \fBstate callback\fR\& whenever a new state is entered; see \fB\fIstate_enter()\fR\&\fR\&\&. This is for writing code common to all state entries\&. Another way to do it is to insert events at state transitions, but you have to do so everywhere it is needed\&. .LP .RS -4 .B Note: .RE If you in \fIgen_statem\fR\&, for example, postpone an event in one state and then call another state callback of yours, you have not changed states and hence the postponed event is not retried, which is logical but can be confusing\&. .LP For the details of a state transition, see type \fB\fItransition_option()\fR\&\fR\&\&. .LP A \fIgen_statem\fR\& handles system messages as described in \fB\fIsys\fR\&\fR\&\&. The \fIsys\fR\& module can be used for debugging a \fIgen_statem\fR\&\&. .LP Notice that a \fIgen_statem\fR\& does not trap exit signals automatically, this must be explicitly initiated in the callback module (by calling \fB\fIprocess_flag(trap_exit, true)\fR\&\fR\&\&. .LP Unless otherwise stated, all functions in this module fail if the specified \fIgen_statem\fR\& does not exist or if bad arguments are specified\&. .LP The \fIgen_statem\fR\& process can go into hibernation; see \fB\fIproc_lib:hibernate/3\fR\&\fR\&\&. It is done when a \fBstate callback\fR\& or \fB\fIModule:init/1\fR\&\fR\& specifies \fIhibernate\fR\& in the returned \fB\fIActions\fR\&\fR\& list\&. This feature can be useful to reclaim process heap memory while the server is expected to be idle for a long time\&. However, use this feature with care, as hibernation can be too costly to use after every event; see \fB\fIerlang:hibernate/3\fR\&\fR\&\&. .SH "EXAMPLE" .LP The following example shows a simple pushbutton model for a toggling pushbutton implemented with \fB\fIcallback mode\fR\&\fR\& \fIstate_functions\fR\&\&. You can push the button and it replies if it went on or off, and you can ask for a count of how many times it has been pushed to switch on\&. .LP The following is the complete callback module file \fIpushbutton\&.erl\fR\&: .LP .nf -module(pushbutton). -behaviour(gen_statem). -export([start/0,push/0,get_count/0,stop/0]). -export([terminate/3,code_change/4,init/1,callback_mode/0]). -export([on/3,off/3]). name() -> pushbutton_statem. % The registered server name %% API. This example uses a registered name name() %% and does not link to the caller. start() -> gen_statem:start({local,name()}, ?MODULE, [], []). push() -> gen_statem:call(name(), push). get_count() -> gen_statem:call(name(), get_count). stop() -> gen_statem:stop(name()). %% Mandatory callback functions terminate(_Reason, _State, _Data) -> void. code_change(_Vsn, State, Data, _Extra) -> {ok,State,Data}. init([]) -> %% Set the initial state + data. Data is used only as a counter. State = off, Data = 0, {ok,State,Data}. callback_mode() -> state_functions. %%% state callback(s) off({call,From}, push, Data) -> %% Go to 'on', increment count and reply %% that the resulting status is 'on' {next_state,on,Data+1,[{reply,From,on}]}; off(EventType, EventContent, Data) -> handle_event(EventType, EventContent, Data). on({call,From}, push, Data) -> %% Go to 'off' and reply that the resulting status is 'off' {next_state,off,Data,[{reply,From,off}]}; on(EventType, EventContent, Data) -> handle_event(EventType, EventContent, Data). %% Handle events common to all states handle_event({call,From}, get_count, Data) -> %% Reply with the current count {keep_state,Data,[{reply,From,Data}]}; handle_event(_, _, Data) -> %% Ignore all other events {keep_state,Data}. .fi .LP The following is a shell session when running it: .LP .nf 1> pushbutton:start(). {ok,<0.36.0>} 2> pushbutton:get_count(). 0 3> pushbutton:push(). on 4> pushbutton:get_count(). 1 5> pushbutton:push(). off 6> pushbutton:get_count(). 1 7> pushbutton:stop(). ok 8> pushbutton:push(). ** exception exit: {noproc,{gen_statem,call,[pushbutton_statem,push,infinity]}} in function gen:do_for_proc/2 (gen.erl, line 261) in call from gen_statem:call/3 (gen_statem.erl, line 386) .fi .LP To compare styles, here follows the same example using \fB\fIcallback mode\fR\&\fR\& \fIstate_functions\fR\&, or rather the code to replace after function \fIinit/1\fR\& of the \fIpushbutton\&.erl\fR\& example file above: .LP .nf callback_mode() -> handle_event_function. %%% state callback(s) handle_event({call,From}, push, off, Data) -> %% Go to 'on', increment count and reply %% that the resulting status is 'on' {next_state,on,Data+1,[{reply,From,on}]}; handle_event({call,From}, push, on, Data) -> %% Go to 'off' and reply that the resulting status is 'off' {next_state,off,Data,[{reply,From,off}]}; %% %% Event handling common to all states handle_event({call,From}, get_count, State, Data) -> %% Reply with the current count {next_state,State,Data,[{reply,From,Data}]}; handle_event(_, _, State, Data) -> %% Ignore all other events {next_state,State,Data}. .fi .SH DATA TYPES .nf \fBserver_name()\fR\& = .br {global, GlobalName :: term()} | .br {via, RegMod :: module(), Name :: term()} | .br {local, atom()} .br .fi .RS .LP Name specification to use when starting a \fIgen_statem\fR\& server\&. See \fB\fIstart_link/3\fR\&\fR\& and \fB\fIserver_ref()\fR\&\fR\& below\&. .RE .nf \fBserver_ref()\fR\& = .br pid() | .br (LocalName :: atom()) | .br {Name :: atom(), Node :: atom()} | .br {global, GlobalName :: term()} | .br {via, RegMod :: module(), ViaName :: term()} .br .fi .RS .LP Server specification to use when addressing a \fIgen_statem\fR\& server\&. See \fB\fIcall/2\fR\&\fR\& and \fB\fIserver_name()\fR\&\fR\& above\&. .LP It can be: .RS 2 .TP 2 .B \fIpid() | LocalName\fR\&: The \fIgen_statem\fR\& is locally registered\&. .TP 2 .B \fI{Name,Node}\fR\&: The \fIgen_statem\fR\& is locally registered on another node\&. .TP 2 .B \fI{global,GlobalName}\fR\&: The \fIgen_statem\fR\& is globally registered in \fB\fIglobal\fR\&\fR\&\&. .TP 2 .B \fI{via,RegMod,ViaName}\fR\&: The \fIgen_statem\fR\& is registered in an alternative process registry\&. The registry callback module \fIRegMod\fR\& is to export functions \fIregister_name/2\fR\&, \fIunregister_name/1\fR\&, \fIwhereis_name/1\fR\&, and \fIsend/2\fR\&, which are to behave like the corresponding functions in \fB\fIglobal\fR\&\fR\&\&. Thus, \fI{via,global,GlobalName}\fR\& is the same as \fI{global,GlobalName}\fR\&\&. .RE .RE .nf \fBdebug_opt()\fR\& = .br {debug, .br Dbgs :: .br [trace | log | statistics | debug | {logfile, string()}]} .br .fi .RS .LP Debug option that can be used when starting a \fIgen_statem\fR\& server through, \fB\fIenter_loop/4-6\fR\&\fR\&\&. .LP For every entry in \fIDbgs\fR\&, the corresponding function in \fB\fIsys\fR\&\fR\& is called\&. .RE .nf \fBstart_opt()\fR\& = .br \fBdebug_opt()\fR\& | .br {timeout, Time :: timeout()} | .br {spawn_opt, [\fBproc_lib:spawn_option()\fR\&]} .br .fi .RS .LP Options that can be used when starting a \fIgen_statem\fR\& server through, for example, \fB\fIstart_link/3\fR\&\fR\&\&. .RE .nf \fBstart_ret()\fR\& = {ok, pid()} | ignore | {error, term()} .br .fi .RS .LP Return value from the start functions, for example, \fB\fIstart_link/3\fR\&\fR\&\&. .RE .nf \fBfrom()\fR\& = {To :: pid(), Tag :: term()} .br .fi .RS .LP Destination to use when replying through, for example, the \fB\fIaction()\fR\&\fR\& \fI{reply,From,Reply}\fR\& to a process that has called the \fIgen_statem\fR\& server using \fB\fIcall/2\fR\&\fR\&\&. .RE .nf \fBstate()\fR\& = \fBstate_name()\fR\& | term() .br .fi .RS .LP If the \fB\fIcallback mode\fR\&\fR\& is \fIhandle_event_function\fR\&, the state can be any term\&. After a state change (\fINextState =/= State\fR\&), all postponed events are retried\&. .RE .nf \fBstate_name()\fR\& = atom() .br .fi .RS .LP If the \fB\fIcallback mode\fR\&\fR\& is \fIstate_functions\fR\&, the state must be of this type\&. After a state change (\fINextState =/= State\fR\&), all postponed events are retried\&. .RE .nf \fBdata()\fR\& = term() .br .fi .RS .LP A term in which the state machine implementation is to store any server data it needs\&. The difference between this and the \fB\fIstate()\fR\&\fR\& itself is that a change in this data does not cause postponed events to be retried\&. Hence, if a change in this data would change the set of events that are handled, then that data item is to be made a part of the state\&. .RE .nf \fBevent_type()\fR\& = .br {call, From :: \fBfrom()\fR\&} | .br cast | .br info | .br timeout | .br state_timeout | .br internal .br .fi .RS .LP External events are of three types: \fI{call,From}\fR\&, \fIcast\fR\&, or \fIinfo\fR\&\&. \fBCalls\fR\& (synchronous) and \fBcasts\fR\& originate from the corresponding API functions\&. For calls, the event contains whom to reply to\&. Type \fIinfo\fR\& originates from regular process messages sent to the \fIgen_statem\fR\&\&. Also, the state machine implementation can generate events of types \fItimeout\fR\&, \fIstate_timeout\fR\&, and \fIinternal\fR\& to itself\&. .RE .nf \fBcallback_mode_result()\fR\& = .br \fBcallback_mode()\fR\& | [\fBcallback_mode()\fR\& | \fBstate_enter()\fR\&] .br .fi .RS .LP This is the return type from \fB\fIModule:callback_mode/0\fR\&\fR\& and selects \fBcallback mode\fR\& and whether to do \fBstate enter calls\fR\&, or not\&. .RE .nf \fBcallback_mode()\fR\& = state_functions | handle_event_function .br .fi .RS .LP The \fIcallback mode\fR\& is selected when starting the \fIgen_statem\fR\& and after code change using the return value from \fB\fIModule:callback_mode/0\fR\&\fR\&\&. .RS 2 .TP 2 .B \fIstate_functions\fR\&: The state must be of type \fB\fIstate_name()\fR\&\fR\& and one callback function per state, that is, \fB\fIModule:StateName/3\fR\&\fR\&, is used\&. .TP 2 .B \fIhandle_event_function\fR\&: The state can be any term and the callback function \fB\fIModule:handle_event/4\fR\&\fR\& is used for all states\&. .RE .RE .nf \fBstate_enter()\fR\& = state_enter .br .fi .RS .LP If the state machine should use \fIstate enter calls\fR\& is selected when starting the \fIgen_statem\fR\& and after code change using the return value from \fB\fIModule:callback_mode/0\fR\&\fR\&\&. .LP If \fB\fIModule:callback_mode/0\fR\&\fR\& returns a list containing \fIstate_enter\fR\&, the \fIgen_statem\fR\& engine will, at every state change, call the \fBstate callback\fR\& with arguments \fI(enter, OldState, Data)\fR\&\&. This may look like an event but is really a call performed after the previous state callback returned and before any event is delivered to the new state callback\&. See \fB\fIModule:StateName/3\fR\&\fR\& and \fB\fIModule:handle_event/4\fR\&\fR\&\&. .LP If \fB\fIModule:callback_mode/0\fR\&\fR\& does not return such a list, no state enter calls are done\&. .LP If \fB\fIModule:code_change/4\fR\&\fR\& should transform the state to a state with a different name it is still regarded as the same state so this does not cause a state enter call\&. .LP Note that a state enter call \fIwill\fR\& be done right before entering the initial state even though this formally is not a state change\&. In this case \fIOldState\fR\& will be the same as \fIState\fR\&, which can not happen for a subsequent state change\&. .RE .nf \fBtransition_option()\fR\& = .br \fBpostpone()\fR\& | \fBhibernate()\fR\& | \fBevent_timeout()\fR\& | \fBstate_timeout()\fR\& .br .fi .RS .LP Transition options can be set by \fBactions\fR\& and they modify how the state transition is done: .RS 2 .TP 2 * If the state changes or is the initial state, and \fB\fIstate enter calls\fR\&\fR\& are used, the \fIgen_statem\fR\& calls the new state callback with arguments \fB(enter, OldState, Data)\fR\&\&. Any \fB\fIactions\fR\&\fR\& returned from this call are handled as if they were appended to the actions returned by the state callback that changed states\&. .LP .TP 2 * All \fBactions\fR\& are processed in order of appearance\&. .LP .TP 2 * If \fB\fIpostpone()\fR\&\fR\& is \fItrue\fR\&, the current event is postponed\&. .LP .TP 2 * If the state changes, the queue of incoming events is reset to start with the oldest postponed\&. .LP .TP 2 * All events stored with \fB\fIaction()\fR\&\fR\& \fInext_event\fR\& are inserted to be processed before the other queued events\&. .LP .TP 2 * Timeout timers \fB\fIstate_timeout()\fR\&\fR\& and \fB\fIevent_timeout()\fR\&\fR\& are handled\&. Time-outs with zero time are guaranteed to be delivered to the state machine before any external not yet received event so if there is such a timeout requested, the corresponding time-out zero event is enqueued as the newest event\&. .RS 2 .LP Any event cancels an \fB\fIevent_timeout()\fR\&\fR\& so a zero time event time-out is only generated if the event queue is empty\&. .RE .RS 2 .LP A state change cancels a \fB\fIstate_timeout()\fR\&\fR\& and any new transition option of this type belongs to the new state\&. .RE .LP .TP 2 * If there are enqueued events the \fBstate callback\fR\& for the possibly new state is called with the oldest enqueued event, and we start again from the top of this list\&. .LP .TP 2 * Otherwise the \fIgen_statem\fR\& goes into \fIreceive\fR\& or hibernation (if \fB\fIhibernate()\fR\&\fR\& is \fItrue\fR\&) to wait for the next message\&. In hibernation the next non-system event awakens the \fIgen_statem\fR\&, or rather the next incoming message awakens the \fIgen_statem\fR\&, but if it is a system event it goes right back into hibernation\&. When a new message arrives the \fBstate callback\fR\& is called with the corresponding event, and we start again from the top of this list\&. .LP .RE .RE .nf \fBpostpone()\fR\& = boolean() .br .fi .RS .LP If \fItrue\fR\&, postpones the current event and retries it when the state changes (\fINextState =/= State\fR\&)\&. .RE .nf \fBhibernate()\fR\& = boolean() .br .fi .RS .LP If \fItrue\fR\&, hibernates the \fIgen_statem\fR\& by calling \fB\fIproc_lib:hibernate/3\fR\&\fR\& before going into \fIreceive\fR\& to wait for a new external event\&. If there are enqueued events, to prevent receiving any new event, an \fB\fIerlang:garbage_collect/0\fR\&\fR\& is done instead to simulate that the \fIgen_statem\fR\& entered hibernation and immediately got awakened by the oldest enqueued event\&. .RE .nf \fBevent_timeout()\fR\& = timeout() .br .fi .RS .LP Generates an event of \fB\fIevent_type()\fR\&\fR\& \fItimeout\fR\& after this time (in milliseconds) unless another event arrives or has arrived in which case this time-out is cancelled\&. Note that a retried or inserted event counts as arrived\&. So does a state time-out zero event, if it was generated before this timer is requested\&. .LP If the value is \fIinfinity\fR\&, no timer is started, as it never would trigger anyway\&. .LP If the value is \fI0\fR\& no timer is actually started, instead the the time-out event is enqueued to ensure that it gets processed before any not yet received external event\&. .LP Note that it is not possible or needed to cancel this time-out, as it is cancelled automatically by any other event\&. .RE .nf \fBstate_timeout()\fR\& = timeout() .br .fi .RS .LP Generates an event of \fB\fIevent_type()\fR\&\fR\& \fIstate_timeout\fR\& after this time (in milliseconds) unless the \fIgen_statem\fR\& changes states (\fINewState =/= OldState\fR\&) which case this time-out is cancelled\&. .LP If the value is \fIinfinity\fR\&, no timer is started, as it never would trigger anyway\&. .LP If the value is \fI0\fR\& no timer is actually started, instead the the time-out event is enqueued to ensure that it gets processed before any not yet received external event\&. .LP Setting this timer while it is running will restart it with the new time-out value\&. Therefore it is possible to cancel this time-out by setting it to \fIinfinity\fR\&\&. .RE .nf \fBaction()\fR\& = .br postpone | .br {postpone, Postpone :: \fBpostpone()\fR\&} | .br {next_event, .br EventType :: \fBevent_type()\fR\&, .br EventContent :: term()} | .br \fBenter_action()\fR\& .br .fi .RS .LP These state transition actions can be invoked by returning them from the \fBstate callback\fR\& when it is called with an \fBevent\fR\&, from \fB\fIModule:init/1\fR\&\fR\& or by giving them to \fB\fIenter_loop/5,6\fR\&\fR\&\&. .LP Actions are executed in the containing list order\&. .LP Actions that set \fBtransition options\fR\& override any previous of the same type, so the last in the containing list wins\&. For example, the last \fB\fIpostpone()\fR\&\fR\& overrides any previous \fIpostpone()\fR\& in the list\&. .RS 2 .TP 2 .B \fIpostpone\fR\&: Sets the \fB\fItransition_option()\fR\&\fR\& \fB\fIpostpone()\fR\&\fR\& for this state transition\&. This action is ignored when returned from \fB\fIModule:init/1\fR\&\fR\& or given to \fB\fIenter_loop/5,6\fR\&\fR\&, as there is no event to postpone in those cases\&. .TP 2 .B \fInext_event\fR\&: Stores the specified \fIEventType\fR\& and \fIEventContent\fR\& for insertion after all actions have been executed\&. .RS 2 .LP The stored events are inserted in the queue as the next to process before any already queued events\&. The order of these stored events is preserved, so the first \fInext_event\fR\& in the containing list becomes the first to process\&. .RE .RS 2 .LP An event of type \fB\fIinternal\fR\&\fR\& is to be used when you want to reliably distinguish an event inserted this way from any external event\&. .RE .RE .RE .nf \fBenter_action()\fR\& = .br hibernate | .br {hibernate, Hibernate :: \fBhibernate()\fR\&} | .br (Timeout :: \fBevent_timeout()\fR\&) | .br {timeout, Time :: \fBevent_timeout()\fR\&, EventContent :: term()} | .br {state_timeout, .br Time :: \fBstate_timeout()\fR\&, .br EventContent :: term()} | .br \fBreply_action()\fR\& .br .fi .RS .LP These state transition actions can be invoked by returning them from the \fBstate callback\fR\&, from \fB\fIModule:init/1\fR\&\fR\& or by giving them to \fB\fIenter_loop/5,6\fR\&\fR\&\&. .LP Actions are executed in the containing list order\&. .LP Actions that set \fBtransition options\fR\& override any previous of the same type, so the last in the containing list wins\&. For example, the last \fB\fIevent_timeout()\fR\&\fR\& overrides any previous \fIevent_timeout()\fR\& in the list\&. .RS 2 .TP 2 .B \fIhibernate\fR\&: Sets the \fB\fItransition_option()\fR\&\fR\& \fB\fIhibernate()\fR\&\fR\& for this state transition\&. .TP 2 .B \fITimeout\fR\&: Short for \fI{timeout,Timeout,Timeout}\fR\&, that is, the time-out message is the time-out time\&. This form exists to make the \fBstate callback\fR\& return value \fI{next_state,NextState,NewData,Timeout}\fR\& allowed like for \fIgen_fsm\fR\&\&'s \fB\fIModule:StateName/2\fR\&\fR\&\&. .TP 2 .B \fItimeout\fR\&: Sets the \fB\fItransition_option()\fR\&\fR\& \fB\fIevent_timeout()\fR\&\fR\& to \fITime\fR\& with \fIEventContent\fR\&\&. .TP 2 .B \fIstate_timeout\fR\&: Sets the \fB\fItransition_option()\fR\&\fR\& \fB\fIstate_timeout()\fR\&\fR\& to \fITime\fR\& with \fIEventContent\fR\&\&. .RE .RE .nf \fBreply_action()\fR\& = {reply, From :: \fBfrom()\fR\&, Reply :: term()} .br .fi .RS .LP This state transition action can be invoked by returning it from the \fBstate callback\fR\&, from \fB\fIModule:init/1\fR\&\fR\& or by giving it to \fB\fIenter_loop/5,6\fR\&\fR\&\&. .LP It replies to a caller waiting for a reply in \fB\fIcall/2\fR\&\fR\&\&. \fIFrom\fR\& must be the term from argument \fB\fI{call,From}\fR\&\fR\& in a call to a \fBstate callback\fR\&\&. .LP Note that using this action from \fB\fIModule:init/1\fR\&\fR\& or \fB\fIenter_loop/5,6\fR\&\fR\& would be weird on the border of whichcraft since there has been no earlier call to a \fBstate callback\fR\& in this server\&. .RE .nf \fBstate_enter_result(State)\fR\& = .br {next_state, State, NewData :: \fBdata()\fR\&} | .br {next_state, .br State, .br NewData :: \fBdata()\fR\&, .br Actions :: [\fBenter_action()\fR\&] | \fBenter_action()\fR\&} | .br \fBstate_callback_result\fR\&(\fBenter_action()\fR\&) .br .fi .RS .LP \fIState\fR\& is the current state and it can not be changed since the state callback was called with a \fB\fIstate enter call\fR\&\fR\&\&. .RS 2 .TP 2 .B \fInext_state\fR\&: The \fIgen_statem\fR\& does a state transition to \fIState\fR\&, which has to be the current state, sets \fINewData\fR\&, and executes all \fIActions\fR\&\&. .RE .RE .nf \fBevent_handler_result(StateType)\fR\& = .br {next_state, NextState :: StateType, NewData :: \fBdata()\fR\&} | .br {next_state, .br NextState :: StateType, .br NewData :: \fBdata()\fR\&, .br Actions :: [\fBaction()\fR\&] | \fBaction()\fR\&} | .br \fBstate_callback_result\fR\&(\fBaction()\fR\&) .br .fi .RS .LP \fIStateType\fR\& is \fB\fIstate_name()\fR\&\fR\& if \fB\fIcallback mode\fR\&\fR\& is \fIstate_functions\fR\&, or \fB\fIstate()\fR\&\fR\& if \fB\fIcallback mode\fR\&\fR\& is \fIhandle_event_function\fR\&\&. .RS 2 .TP 2 .B \fInext_state\fR\&: The \fIgen_statem\fR\& does a state transition to \fINextState\fR\& (which can be the same as the current state), sets \fINewData\fR\&, and executes all \fIActions\fR\&\&. .RE .RE .nf \fBstate_callback_result(ActionType)\fR\& = .br {keep_state, NewData :: \fBdata()\fR\&} | .br {keep_state, .br NewData :: \fBdata()\fR\&, .br Actions :: [ActionType] | ActionType} | .br keep_state_and_data | .br {keep_state_and_data, Actions :: [ActionType] | ActionType} | .br stop | .br {stop, Reason :: term()} | .br {stop, Reason :: term(), NewData :: \fBdata()\fR\&} | .br {stop_and_reply, .br Reason :: term(), .br Replies :: [\fBreply_action()\fR\&] | \fBreply_action()\fR\&} | .br {stop_and_reply, .br Reason :: term(), .br Replies :: [\fBreply_action()\fR\&] | \fBreply_action()\fR\&, .br NewData :: \fBdata()\fR\&} .br .fi .RS .LP \fIActionType\fR\& is \fB\fIenter_action()\fR\&\fR\& if the state callback was called with a \fB\fIstate enter call\fR\&\fR\& and \fB\fIaction()\fR\&\fR\& if the state callback was called with an event\&. .RS 2 .TP 2 .B \fIkeep_state\fR\&: The \fIgen_statem\fR\& keeps the current state, or does a state transition to the current state if you like, sets \fINewData\fR\&, and executes all \fIActions\fR\&\&. This is the same as \fI{next_state,CurrentState,NewData,Actions}\fR\&\&. .TP 2 .B \fIkeep_state_and_data\fR\&: The \fIgen_statem\fR\& keeps the current state or does a state transition to the current state if you like, keeps the current server data, and executes all \fIActions\fR\&\&. This is the same as \fI{next_state,CurrentState,CurrentData,Actions}\fR\&\&. .TP 2 .B \fIstop\fR\&: Terminates the \fIgen_statem\fR\& by calling \fB\fIModule:terminate/3\fR\&\fR\& with \fIReason\fR\& and \fINewData\fR\&, if specified\&. .TP 2 .B \fIstop_and_reply\fR\&: Sends all \fIReplies\fR\&, then terminates the \fIgen_statem\fR\& by calling \fB\fIModule:terminate/3\fR\&\fR\& with \fIReason\fR\& and \fINewData\fR\&, if specified\&. .RE .LP All these terms are tuples or atoms and this property will hold in any future version of \fIgen_statem\fR\&\&. .RE .SH EXPORTS .LP .nf .B call(ServerRef :: server_ref(), Request :: term()) -> .B Reply :: term() .br .fi .br .nf .B call(ServerRef :: server_ref(), .B Request :: term(), .B Timeout :: .B timeout() | .B {clean_timeout, T :: timeout()} | .B {dirty_timeout, T :: timeout()}) -> .B Reply :: term() .br .fi .br .RS .LP Makes a synchronous call to the \fIgen_statem\fR\& \fB\fIServerRef\fR\&\fR\& by sending a request and waiting until its reply arrives\&. The \fIgen_statem\fR\& calls the \fBstate callback\fR\& with \fB\fIevent_type()\fR\&\fR\& \fI{call,From}\fR\& and event content \fIRequest\fR\&\&. .LP A \fIReply\fR\& is generated when a \fBstate callback\fR\& returns with \fI{reply,From,Reply}\fR\& as one \fB\fIaction()\fR\&\fR\&, and that \fIReply\fR\& becomes the return value of this function\&. .LP \fITimeout\fR\& is an integer > 0, which specifies how many milliseconds to wait for a reply, or the atom \fIinfinity\fR\& to wait indefinitely, which is the default\&. If no reply is received within the specified time, the function call fails\&. .LP .RS -4 .B Note: .RE For \fITimeout < infinity\fR\&, to avoid getting a late reply in the caller\&'s inbox if the caller should catch exceptions, this function spawns a proxy process that does the call\&. A late reply gets delivered to the dead proxy process, hence gets discarded\&. This is less efficient than using \fITimeout == infinity\fR\&\&. .LP \fITimeout\fR\& can also be a tuple \fI{clean_timeout,T}\fR\& or \fI{dirty_timeout,T}\fR\&, where \fIT\fR\& is the time-out time\&. \fI{clean_timeout,T}\fR\& works like just \fIT\fR\& described in the note above and uses a proxy process for \fIT < infinity\fR\&, while \fI{dirty_timeout,T}\fR\& bypasses the proxy process which is more lightweight\&. .LP .RS -4 .B Note: .RE If you combine catching exceptions from this function with \fI{dirty_timeout,T}\fR\& to avoid that the calling process dies when the call times out, you will have to be prepared to handle a late reply\&. So why not just allow the calling process to die? .LP The call can also fail, for example, if the \fIgen_statem\fR\& dies before or during this function call\&. .RE .LP .nf .B cast(ServerRef :: server_ref(), Msg :: term()) -> ok .br .fi .br .RS .LP Sends an asynchronous event to the \fIgen_statem\fR\& \fB\fIServerRef\fR\&\fR\& and returns \fIok\fR\& immediately, ignoring if the destination node or \fIgen_statem\fR\& does not exist\&. The \fIgen_statem\fR\& calls the \fBstate callback\fR\& with \fB\fIevent_type()\fR\&\fR\& \fIcast\fR\& and event content \fIMsg\fR\&\&. .RE .LP .nf .B enter_loop(Module :: module(), .B Opts :: [debug_opt()], .B State :: state(), .B Data :: data()) -> .B no_return() .br .fi .br .RS .LP The same as \fB\fIenter_loop/6\fR\&\fR\& with \fIActions = []\fR\& except that no \fB\fIserver_name()\fR\&\fR\& must have been registered\&. This creates an anonymous server\&. .RE .LP .nf .B enter_loop(Module :: module(), .B Opts :: [debug_opt()], .B State :: state(), .B Data :: data(), .B Server_or_Actions :: server_name() | pid() | [action()]) -> .B no_return() .br .fi .br .RS .LP If \fIServer_or_Actions\fR\& is a \fIlist()\fR\&, the same as \fB\fIenter_loop/6\fR\&\fR\& except that no \fB\fIserver_name()\fR\&\fR\& must have been registered and \fIActions = Server_or_Actions\fR\&\&. This creates an anonymous server\&. .LP Otherwise the same as \fB\fIenter_loop/6\fR\&\fR\& with \fIServer = Server_or_Actions\fR\& and \fIActions = []\fR\&\&. .RE .LP .nf .B enter_loop(Module :: module(), .B Opts :: [debug_opt()], .B State :: state(), .B Data :: data(), .B Server :: server_name() | pid(), .B Actions :: [action()] | action()) -> .B no_return() .br .fi .br .RS .LP Makes the calling process become a \fIgen_statem\fR\&\&. Does not return, instead the calling process enters the \fIgen_statem\fR\& receive loop and becomes a \fIgen_statem\fR\& server\&. The process \fImust\fR\& have been started using one of the start functions in \fB\fIproc_lib\fR\&\fR\&\&. The user is responsible for any initialization of the process, including registering a name for it\&. .LP This function is useful when a more complex initialization procedure is needed than the \fIgen_statem\fR\& behavior provides\&. .LP \fIModule\fR\&, \fIOpts\fR\& have the same meaning as when calling \fB\fIstart[_link]/3,4\fR\&\fR\&\&. .LP If \fIServer\fR\& is \fIself()\fR\& an anonymous server is created just as when using \fB\fIstart[_link]/3\fR\&\fR\&\&. If \fIServer\fR\& is a \fB\fIserver_name()\fR\&\fR\& a named server is created just as when using \fB\fIstart[_link]/4\fR\&\fR\&\&. However, the \fB\fIserver_name()\fR\&\fR\& name must have been registered accordingly \fIbefore\fR\& this function is called\&. .LP \fIState\fR\&, \fIData\fR\&, and \fIActions\fR\& have the same meanings as in the return value of \fB\fIModule:init/1\fR\&\fR\&\&. Also, the callback module does not need to export a \fB\fIModule:init/1\fR\&\fR\& function\&. .LP The function fails if the calling process was not started by a \fB\fIproc_lib\fR\&\fR\& start function, or if it is not registered according to \fB\fIserver_name()\fR\&\fR\&\&. .RE .LP .nf .B reply(Replies :: [reply_action()] | reply_action()) -> ok .br .fi .br .nf .B reply(From :: from(), Reply :: term()) -> ok .br .fi .br .RS .LP This function can be used by a \fIgen_statem\fR\& to explicitly send a reply to a process that waits in \fB\fIcall/2\fR\&\fR\& when the reply cannot be defined in the return value of a \fBstate callback\fR\&\&. .LP \fIFrom\fR\& must be the term from argument \fB\fI{call,From}\fR\&\fR\& to the \fBstate callback\fR\&\&. A reply or multiple replies canalso be sent using one or several \fB\fIreply_action()\fR\&\fR\&s from a \fBstate callback\fR\&\&. .LP .RS -4 .B Note: .RE A reply sent with this function is not visible in \fB\fIsys\fR\&\fR\& debug output\&. .RE .LP .nf .B start(Module :: module(), Args :: term(), Opts :: [start_opt()]) -> .B start_ret() .br .fi .br .nf .B start(ServerName :: server_name(), .B Module :: module(), .B Args :: term(), .B Opts :: [start_opt()]) -> .B start_ret() .br .fi .br .RS .LP Creates a standalone \fIgen_statem\fR\& process according to OTP design principles (using \fB\fIproc_lib\fR\&\fR\& primitives)\&. As it does not get linked to the calling process, this start function cannot be used by a supervisor to start a child\&. .LP For a description of arguments and return values, see \fB\fIstart_link/3,4\fR\&\fR\&\&. .RE .LP .nf .B start_link(Module :: module(), .B Args :: term(), .B Opts :: [start_opt()]) -> .B start_ret() .br .fi .br .nf .B start_link(ServerName :: server_name(), .B Module :: module(), .B Args :: term(), .B Opts :: [start_opt()]) -> .B start_ret() .br .fi .br .RS .LP Creates a \fIgen_statem\fR\& process according to OTP design principles (using \fB\fIproc_lib\fR\&\fR\& primitives) that is linked to the calling process\&. This is essential when the \fIgen_statem\fR\& must be part of a supervision tree so it gets linked to its supervisor\&. .LP The \fIgen_statem\fR\& process calls \fB\fIModule:init/1\fR\&\fR\& to initialize the server\&. To ensure a synchronized startup procedure, \fIstart_link/3,4\fR\& does not return until \fB\fIModule:init/1\fR\&\fR\& has returned\&. .LP \fIServerName\fR\& specifies the \fB\fIserver_name()\fR\&\fR\& to register for the \fIgen_statem\fR\&\&. If the \fIgen_statem\fR\& is started with \fIstart_link/3\fR\&, no \fIServerName\fR\& is provided and the \fIgen_statem\fR\& is not registered\&. .LP \fIModule\fR\& is the name of the callback module\&. .LP \fIArgs\fR\& is an arbitrary term that is passed as the argument to \fB\fIModule:init/1\fR\&\fR\&\&. .RS 2 .TP 2 * If option \fI{timeout,Time}\fR\& is present in \fIOpts\fR\&, the \fIgen_statem\fR\& is allowed to spend \fITime\fR\& milliseconds initializing or it terminates and the start function returns \fB\fI{error,timeout}\fR\&\fR\&\&. .LP .TP 2 * If option \fB\fI{debug,Dbgs}\fR\&\fR\& is present in \fIOpts\fR\&, debugging through \fB\fIsys\fR\&\fR\& is activated\&. .LP .TP 2 * If option \fI{spawn_opt,SpawnOpts}\fR\& is present in \fIOpts\fR\&, \fISpawnOpts\fR\& is passed as option list to \fB\fIerlang:spawn_opt/2\fR\&\fR\&, which is used to spawn the \fIgen_statem\fR\& process\&. .LP .RE .LP .RS -4 .B Note: .RE Using spawn option \fImonitor\fR\& is not allowed, it causes this function to fail with reason \fIbadarg\fR\&\&. .LP If the \fIgen_statem\fR\& is successfully created and initialized, this function returns \fB\fI{ok,Pid}\fR\&\fR\&, where \fIPid\fR\& is the \fIpid()\fR\& of the \fIgen_statem\fR\&\&. If a process with the specified \fIServerName\fR\& exists already, this function returns \fB\fI{error,{already_started,Pid}}\fR\&\fR\&, where \fIPid\fR\& is the \fIpid()\fR\& of that process\&. .LP If \fIModule:init/1\fR\& fails with \fIReason\fR\&, this function returns \fB\fI{error,Reason}\fR\&\fR\&\&. If \fIModule:init/1\fR\& returns \fB\fI{stop,Reason}\fR\&\fR\& or \fB\fIignore\fR\&\fR\&, the process is terminated and this function returns \fB\fI{error,Reason}\fR\&\fR\& or \fB\fIignore\fR\&\fR\&, respectively\&. .RE .LP .nf .B stop(ServerRef :: server_ref()) -> ok .br .fi .br .RS .LP The same as \fB\fIstop(ServerRef, normal, infinity)\fR\&\fR\&\&. .RE .LP .nf .B stop(ServerRef :: server_ref(), .B Reason :: term(), .B Timeout :: timeout()) -> .B ok .br .fi .br .RS .LP Orders the \fIgen_statem\fR\& \fB\fIServerRef\fR\&\fR\& to exit with the specified \fIReason\fR\& and waits for it to terminate\&. The \fIgen_statem\fR\& calls \fB\fIModule:terminate/3\fR\&\fR\& before exiting\&. .LP This function returns \fIok\fR\& if the server terminates with the expected reason\&. Any other reason than \fInormal\fR\&, \fIshutdown\fR\&, or \fI{shutdown,Term}\fR\& causes an error report to be issued through \fB\fIerror_logger:format/2\fR\&\fR\&\&. The default \fIReason\fR\& is \fInormal\fR\&\&. .LP \fITimeout\fR\& is an integer > 0, which specifies how many milliseconds to wait for the server to terminate, or the atom \fIinfinity\fR\& to wait indefinitely\&. Defaults to \fIinfinity\fR\&\&. If the server does not terminate within the specified time, a \fItimeout\fR\& exception is raised\&. .LP If the process does not exist, a \fInoproc\fR\& exception is raised\&. .RE .SH "CALLBACK FUNCTIONS" .LP The following functions are to be exported from a \fIgen_statem\fR\& callback module\&. .SH EXPORTS .LP .B Module:callback_mode() -> CallbackMode .br .RS .LP Types: .RS 3 CallbackMode = \fBcallback_mode()\fR\& | [ \fBcallback_mode()\fR\& | \fBstate_enter()\fR\& ] .br .RE .RE .RS .LP This function is called by a \fIgen_statem\fR\& when it needs to find out the \fB\fIcallback mode\fR\&\fR\& of the callback module\&. The value is cached by \fIgen_statem\fR\& for efficiency reasons, so this function is only called once after server start and after code change, but before the first \fBstate callback\fR\& in the current code version is called\&. More occasions may be added in future versions of \fIgen_statem\fR\&\&. .LP Server start happens either when \fB\fIModule:init/1\fR\&\fR\& returns or when \fB\fIenter_loop/4-6\fR\&\fR\& is called\&. Code change happens when \fB\fIModule:code_change/4\fR\&\fR\& returns\&. .LP The \fICallbackMode\fR\& is either just \fB\fIcallback_mode()\fR\&\fR\& or a list containing \fB\fIcallback_mode()\fR\&\fR\& and possibly the atom \fB\fIstate_enter\fR\&\fR\&\&. .LP .RS -4 .B Note: .RE If this function\&'s body does not return an inline constant value the callback module is doing something strange\&. .RE .LP .B Module:code_change(OldVsn, OldState, OldData, Extra) -> Result .br .RS .LP Types: .RS 3 OldVsn = Vsn | {down,Vsn} .br Vsn = term() .br OldState = NewState = term() .br Extra = term() .br Result = {ok,NewState,NewData} | Reason .br OldState = NewState = \fBstate()\fR\& .br OldData = NewData = \fBdata()\fR\& .br Reason = term() .br .RE .RE .RS .LP This function is called by a \fIgen_statem\fR\& when it is to update its internal state during a release upgrade/downgrade, that is, when the instruction \fI{update,Module,Change,\&.\&.\&.}\fR\&, where \fIChange={advanced,Extra}\fR\&, is specified in the \fB\fIappup\fR\&\fR\& file\&. For more information, see \fBOTP Design Principles\fR\&\&. .LP For an upgrade, \fIOldVsn\fR\& is \fIVsn\fR\&, and for a downgrade, \fIOldVsn\fR\& is \fI{down,Vsn}\fR\&\&. \fIVsn\fR\& is defined by the \fIvsn\fR\& attribute(s) of the old version of the callback module \fIModule\fR\&\&. If no such attribute is defined, the version is the checksum of the Beam file\&. .LP \fIOldState\fR\& and \fIOldData\fR\& is the internal state of the \fIgen_statem\fR\&\&. .LP \fIExtra\fR\& is passed "as is" from the \fI{advanced,Extra}\fR\& part of the update instruction\&. .LP If successful, the function must return the updated internal state in an \fI{ok,NewState,NewData}\fR\& tuple\&. .LP If the function returns a failure \fIReason\fR\&, the ongoing upgrade fails and rolls back to the old release\&. Note that \fIReason\fR\& can not be an \fI{ok,_,_}\fR\& tuple since that will be regarded as a \fI{ok,NewState,NewData}\fR\& tuple, and that a tuple matching \fI{ok,_}\fR\& is an also invalid failure \fIReason\fR\&\&. It is recommended to use an atom as \fIReason\fR\& since it will be wrapped in an \fI{error,Reason}\fR\& tuple\&. .RE .LP .B Module:init(Args) -> Result .br .RS .LP Types: .RS 3 Args = term() .br Result = {ok,State,Data} .br | {ok,State,Data,Actions} .br | {stop,Reason} | ignore .br State = \fBstate()\fR\& .br Data = \fBdata()\fR\& .br Actions = [\fBaction()\fR\&] | \fBaction()\fR\& .br Reason = term() .br .RE .RE .RS .LP Whenever a \fIgen_statem\fR\& is started using \fB\fIstart_link/3,4\fR\&\fR\& or \fB\fIstart/3,4\fR\&\fR\&, this optional function is called by the new process to initialize the implementation state and server data\&. .LP \fIArgs\fR\& is the \fIArgs\fR\& argument provided to the start function\&. .LP If the initialization is successful, the function is to return \fI{ok,State,Data}\fR\& or \fI{ok,State,Data,Actions}\fR\&\&. \fIState\fR\& is the initial \fB\fIstate()\fR\&\fR\& and \fIData\fR\& the initial server \fB\fIdata()\fR\&\fR\&\&. .LP The \fB\fIActions\fR\&\fR\& are executed when entering the first \fBstate\fR\& just as for a \fBstate callback\fR\&\&. .LP If the initialization fails, the function is to return \fI{stop,Reason}\fR\& or \fIignore\fR\&; see \fB\fIstart_link/3,4\fR\&\fR\&\&. .LP .RS -4 .B Note: .RE This callback is optional, so a callback module does not need to export it, but most do\&. If this function is not exported, the \fIgen_statem\fR\& should be started through \fB\fIproc_lib\fR\&\fR\& and \fB\fIenter_loop/4-6\fR\&\fR\&\&. .RE .LP .B Module:format_status(Opt, [PDict,State,Data]) -> Status .br .RS .LP Types: .RS 3 Opt = normal | terminate .br PDict = [{Key, Value}] .br State = \fBstate()\fR\& .br Data = \fBdata()\fR\& .br Key = term() .br Value = term() .br Status = term() .br .RE .RE .RS .LP .RS -4 .B Note: .RE This callback is optional, so a callback module does not need to export it\&. The \fIgen_statem\fR\& module provides a default implementation of this function that returns \fI{State,Data}\fR\&\&. .LP If this callback is exported but fails, to hide possibly sensitive data, the default function will instead return \fI{State,Info}\fR\&, where \fIInfo\fR\& says nothing but the fact that \fIformat_status/2\fR\& has crashed\&. .LP This function is called by a \fIgen_statem\fR\& process when any of the following apply: .RS 2 .TP 2 * One of \fB\fIsys:get_status/1,2\fR\&\fR\& is invoked to get the \fIgen_statem\fR\& status\&. \fIOpt\fR\& is set to the atom \fInormal\fR\& for this case\&. .LP .TP 2 * The \fIgen_statem\fR\& terminates abnormally and logs an error\&. \fIOpt\fR\& is set to the atom \fIterminate\fR\& for this case\&. .LP .RE .LP This function is useful for changing the form and appearance of the \fIgen_statem\fR\& status for these cases\&. A callback module wishing to change the \fB\fIsys:get_status/1,2\fR\&\fR\& return value and how its status appears in termination error logs exports an instance of \fIformat_status/2\fR\&, which returns a term describing the current status of the \fIgen_statem\fR\&\&. .LP \fIPDict\fR\& is the current value of the process dictionary of the \fIgen_statem\fR\&\&. .LP \fB\fIState\fR\&\fR\& is the internal state of the \fIgen_statem\fR\&\&. .LP \fB\fIData\fR\&\fR\& is the internal server data of the \fIgen_statem\fR\&\&. .LP The function is to return \fIStatus\fR\&, a term that contains the appropriate details of the current state and status of the \fIgen_statem\fR\&\&. There are no restrictions on the form \fIStatus\fR\& can take, but for the \fB\fIsys:get_status/1,2\fR\&\fR\& case (when \fIOpt\fR\& is \fInormal\fR\&), the recommended form for the \fIStatus\fR\& value is \fI[{data, [{"State", Term}]}]\fR\&, where \fITerm\fR\& provides relevant details of the \fIgen_statem\fR\& state\&. Following this recommendation is not required, but it makes the callback module status consistent with the rest of the \fB\fIsys:get_status/1,2\fR\&\fR\& return value\&. .LP One use for this function is to return compact alternative state representations to avoid having large state terms printed in log files\&. Another use is to hide sensitive data from being written to the error log\&. .RE .LP .B Module:StateName(enter, OldState, Data) -> StateEnterResult(StateName) .br .B Module:StateName(EventType, EventContent, Data) -> StateFunctionResult .br .B Module:handle_event(enter, OldState, State, Data) -> StateEnterResult(State) .br .B Module:handle_event(EventType, EventContent, State, Data) -> HandleEventResult .br .RS .LP Types: .RS 3 EventType = \fBevent_type()\fR\& .br EventContent = term() .br State = \fBstate()\fR\& .br Data = NewData = \fBdata()\fR\& .br StateEnterResult(StateName) = \fBstate_enter_result(StateName)\fR\& .br StateFunctionResult = \fBevent_handler_result\fR\&(\fBstate_name()\fR\&) .br StateEnterResult(State) = \fBstate_enter_result(State)\fR\& .br HandleEventResult = \fBevent_handler_result\fR\&(\fBstate()\fR\&) .br .RE .RE .RS .LP Whenever a \fIgen_statem\fR\& receives an event from \fB\fIcall/2\fR\&\fR\&, \fB\fIcast/2\fR\&\fR\&, or as a normal process message, one of these functions is called\&. If \fB\fIcallback mode\fR\&\fR\& is \fIstate_functions\fR\&, \fIModule:StateName/3\fR\& is called, and if it is \fIhandle_event_function\fR\&, \fIModule:handle_event/4\fR\& is called\&. .LP If \fIEventType\fR\& is \fB\fI{call,From}\fR\&\fR\&, the caller waits for a reply\&. The reply can be sent from this or from any other \fBstate callback\fR\& by returning with \fI{reply,From,Reply}\fR\& in \fB\fIActions\fR\&\fR\&, in \fB\fIReplies\fR\&\fR\&, or by calling \fB\fIreply(From, Reply)\fR\&\fR\&\&. .LP If this function returns with a next state that does not match equal (\fI=/=\fR\&) to the current state, all postponed events are retried in the next state\&. .LP The only difference between \fIStateFunctionResult\fR\& and \fIHandleEventResult\fR\& is that for \fIStateFunctionResult\fR\& the next state must be an atom, but for \fIHandleEventResult\fR\& there is no restriction on the next state\&. .LP For options that can be set and actions that can be done by \fIgen_statem\fR\& after returning from this function, see \fB\fIaction()\fR\&\fR\&\&. .LP When the \fIgen_statem\fR\& runs with \fBstate enter calls\fR\&, these functions are also called with arguments \fI(enter, OldState, \&.\&.\&.)\fR\& whenever the state changes\&. In this case there are some restrictions on the \fBactions\fR\& that may be returned: \fB\fIpostpone()\fR\&\fR\& and \fB\fI{next_event,_,_}\fR\&\fR\& are not allowed\&. You may also not change states from this call\&. Should you return \fI{next_state,NextState, \&.\&.\&.}\fR\& with \fINextState =/= State\fR\& the \fIgen_statem\fR\& crashes\&. You are advised to use \fI{keep_state,\&.\&.\&.}\fR\& or \fIkeep_state_and_data\fR\&\&. .LP Note the fact that you can use \fB\fIthrow\fR\&\fR\& to return the result, which can be useful\&. For example to bail out with \fIthrow(keep_state_and_data)\fR\& from deep within complex code that is in no position to return \fI{next_state,State,Data}\fR\&\&. .RE .LP .B Module:terminate(Reason, State, Data) -> Ignored .br .RS .LP Types: .RS 3 Reason = normal | shutdown | {shutdown,term()} | term() .br State = \fBstate()\fR\& .br Data = \fBdata()\fR\& .br Ignored = term() .br .RE .RE .RS .LP This function is called by a \fIgen_statem\fR\& when it is about to terminate\&. It is to be the opposite of \fB\fIModule:init/1\fR\&\fR\& and do any necessary cleaning up\&. When it returns, the \fIgen_statem\fR\& terminates with \fIReason\fR\&\&. The return value is ignored\&. .LP \fIReason\fR\& is a term denoting the stop reason and \fB\fIState\fR\&\fR\& is the internal state of the \fIgen_statem\fR\&\&. .LP \fIReason\fR\& depends on why the \fIgen_statem\fR\& is terminating\&. If it is because another callback function has returned, a stop tuple \fI{stop,Reason}\fR\& in \fB\fIActions\fR\&\fR\&, \fIReason\fR\& has the value specified in that tuple\&. If it is because of a failure, \fIReason\fR\& is the error reason\&. .LP If the \fIgen_statem\fR\& is part of a supervision tree and is ordered by its supervisor to terminate, this function is called with \fIReason = shutdown\fR\& if both the following conditions apply: .RS 2 .TP 2 * The \fIgen_statem\fR\& has been set to trap exit signals\&. .LP .TP 2 * The shutdown strategy as defined in the supervisor\&'s child specification is an integer time-out value, not \fIbrutal_kill\fR\&\&. .LP .RE .LP Even if the \fIgen_statem\fR\& is \fInot\fR\& part of a supervision tree, this function is called if it receives an \fI\&'EXIT\&'\fR\& message from its parent\&. \fIReason\fR\& is the same as in the \fI\&'EXIT\&'\fR\& message\&. .LP Otherwise, the \fIgen_statem\fR\& is immediately terminated\&. .LP Notice that for any other reason than \fInormal\fR\&, \fIshutdown\fR\&, or \fI{shutdown,Term}\fR\&, the \fIgen_statem\fR\& is assumed to terminate because of an error and an error report is issued using \fB\fIerror_logger:format/2\fR\&\fR\&\&. .RE .SH "SEE ALSO" .LP \fB\fIgen_event(3erl)\fR\&\fR\&, \fB\fIgen_fsm(3erl)\fR\&\fR\&, \fB\fIgen_server(3erl)\fR\&\fR\&, \fB\fIproc_lib(3erl)\fR\&\fR\&, \fB\fIsupervisor(3erl)\fR\&\fR\&, \fB\fIsys(3erl)\fR\&\fR\&\&.