.TH gen_statem 3erl "stdlib 3.14" "Ericsson AB" "Erlang Module Definition" .SH NAME gen_statem \- Generic state machine behavior. .SH DESCRIPTION .LP \fIgen_statem\fR\& provides a generic state machine behaviour that for new code replaces its predecessor \fIgen_fsm\fR\& since Erlang/OTP 20\&.0\&. The \fIgen_fsm\fR\& behaviour remains in OTP "as is"\&. .LP .RS -4 .B Note: .RE If you are new to \fIgen_statem\fR\& and want an overview of concepts and operation the section \fIgen_statem\fR\& Behaviour located in the User\&'s Guide OTP Design Principles is recommended to read before this reference manual, possibly after the Description section you are reading here\&. .LP This reference manual contains type descriptions generated from types in the \fIgen_statem\fR\& source code, so they are correct\&. However, the generated descriptions also reflect the type hierarchy, which sometimes makes it hard to get a good overview\&. If so, see the section \fIgen_statem\fR\& Behaviour in the OTP Design Principles User\&'s Guide\&. .LP .RS -4 .B Note: .RE .RS 2 .TP 2 * This behavior appeared in Erlang/OTP 19\&.0\&. .LP .TP 2 * In OTP 19\&.1 a backwards incompatible change of the return tuple from \fIModule:init/1\fR\& was made and the mandatory callback function \fIModule:callback_mode/0\fR\& was introduced\&. .LP .TP 2 * In OTP 20\&.0 generic time-outs were added\&. .LP .TP 2 * In OTP 22\&.1 time-out content \fIupdate\fR\& and explicit time-out \fIcancel\fR\& were added\&. .LP .TP 2 * In OTP 22\&.3 the possibility to change the callback module with actions \fIchange_callback_module\fR\&, \fIpush_callback_module\fR\& and \fIpop_callback_module\fR\&, was added\&. .LP .RE .LP \fIgen_statem\fR\& has got the same features that \fIgen_fsm\fR\& had and adds some really useful: .RS 2 .TP 2 * Co-located state code .LP .TP 2 * Arbitrary term state .LP .TP 2 * Event postponing .LP .TP 2 * Self-generated events .LP .TP 2 * State time-out .LP .TP 2 * Multiple generic named time-outs .LP .TP 2 * Absolute time-out time .LP .TP 2 * Automatic state enter calls .LP .TP 2 * Reply from other state than the request, \fIsys\fR\& traceable .LP .TP 2 * Multiple \fIsys\fR\& traceable replies .LP .TP 2 * Changing the callback module .LP .RE .LP Two \fIcallback modes\fR\& are supported: .RS 2 .TP 2 * One for finite-state machines (\fIgen_fsm\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 that allows the state to be any term and that uses one callback function for all states\&. .LP .RE .LP The callback model(s) for \fIgen_statem\fR\& differs from the one for \fIgen_fsm\fR\&, but it is still fairly easy to rewrite from \fIgen_fsm\fR\& to \fIgen_statem\fR\&\&. .LP A generic state machine server 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 OTP Design Principles\&. .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_monitor 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 gen_statem:send_request erlang:send erlang:'!' -----> Module:StateName/3 Module:handle_event/4 - -----> Module:terminate/3 - -----> Module:code_change/4 .fi .LP Events are of different types, 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 \fIthrow\fR\& is not regarded as an error but as a valid return from all callback functions\&. .LP The \fIstate callback\fR\& for a specific state in a \fIgen_statem\fR\& is the callback function that is called for all events in this state\&. It is selected depending on which \fIcallback mode\fR\& that the callback module defines with the callback function \fIModule:callback_mode/0\fR\&\&. .LP When the \fIcallback mode\fR\& is \fIstate_functions\fR\&, the state must be an atom and is used as the \fIstate callback\fR\& name; see \fIModule:StateName/3\fR\&\&. This co-locates all code for a specific state in one function as the \fIgen_statem\fR\& engine branches depending on state name\&. Note the fact that the callback function \fIModule:terminate/3\fR\& makes the state name \fIterminate\fR\& unusable in this mode\&. .LP When the \fIcallback mode\fR\& is \fIhandle_event_function\fR\&, the state can be any term and the \fIstate callback\fR\& name is \fIModule:handle_event/4\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 When \fIgen_statem\fR\& receives a process message it is converted into an event and the \fIstate callback\fR\& is called with the event as two arguments: type and content\&. When the \fIstate callback\fR\& has processed the event it returns to \fIgen_statem\fR\& which does a \fIstate transition\fR\&\&. If this \fIstate transition\fR\& is to a different state, that is: \fINextState =/= State\fR\&, it is a \fIstate change\fR\&\&. .LP The \fIstate callback\fR\& may return \fItransition actions\fR\& for \fIgen_statem\fR\& to execute during the \fIstate transition\fR\&, for example to reply to a \fIgen_statem:call/2,3\fR\&\&. .LP One of the possible \fItransition actions\fR\& is to postpone the current event\&. Then it is not retried in the current state\&. The \fIgen_statem\fR\& engine keeps a queue of events divided into the postponed events and the events still to process\&. After a \fIstate change\fR\& 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 \fIstate callback\fR\& can insert events using the \fItransition actions\fR\& \fInext_event\fR\& and such an event is inserted in the event queue as the next to call the \fIstate callback\fR\& with\&. That is, as if it is the oldest incoming event\&. A dedicated \fIevent_type()\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, \fIgen_fsm\fR\& to force processing an inserted event before others\&. .LP The \fIgen_statem\fR\& engine can automatically make a specialized call to the \fIstate callback\fR\& whenever a new state is entered; see \fIstate_enter()\fR\&\&. This is for writing code common to all state entries\&. Another way to do it is to explicitly insert an event at the \fIstate transition\fR\&, and/or to use a dedicated \fIstate transition\fR\& function, but that is something you will have to remember at every \fIstate transition\fR\& to the state(s) that need it\&. .LP .RS -4 .B Note: .RE If you in \fIgen_statem\fR\&, for example, postpone an event in one state and then call another \fIstate callback\fR\& of yours, you have not done a \fIstate change\fR\& and hence the postponed event is not retried, which is logical but can be confusing\&. .LP For the details of a \fIstate transition\fR\&, see type \fItransition_option()\fR\&\&. .LP A \fIgen_statem\fR\& handles system messages as described in \fIsys\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 \fIprocess_flag(trap_exit, true)\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 \fIproc_lib:hibernate/3\fR\&\&. It is done when a \fIstate callback\fR\& or \fIModule:init/1\fR\& specifies \fIhibernate\fR\& in the returned \fIActions\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 \fIerlang:hibernate/3\fR\&\&. .LP There is also a server start option \fI{hibernate_after, Timeout}\fR\& for \fIstart/3,4\fR\&, \fIstart_monitor/3,4\fR\&, \fIstart_link/3,4\fR\& or \fIenter_loop/4,5,6\fR\&, that may be used to automatically hibernate the server\&. .SH "EXAMPLE" .LP The following example shows a simple pushbutton model for a toggling pushbutton implemented with \fIcallback mode\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 \fIcallback mode\fR\& \fIhandle_event_function\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 \fIstart_link/3\fR\& and \fIserver_ref()\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 \fIcall/2\fR\& and \fIserver_name()\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 \fIglobal\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 \fIglobal\fR\&\&. Thus, \fI{via,global,GlobalName}\fR\& is the same as \fI{global,GlobalName}\fR\&\&. .RE .RE .nf \fBstart_opt()\fR\& = .br {timeout, Time :: timeout()} | .br {spawn_opt, [proc_lib:start_spawn_option()]} | .br enter_loop_opt() .br .fi .RS .LP Options that can be used when starting a \fIgen_statem\fR\& server through, for example, \fIstart_link/3\fR\&\&. .RE .nf \fBstart_ret()\fR\& = {ok, pid()} | ignore | {error, term()} .br .fi .RS .LP Return value from the \fIstart()\fR\& and \fIstart_link()\fR\& functions, for example, \fIstart_link/3\fR\&\&. .RE .nf \fBstart_mon_ret()\fR\& = .br {ok, {pid(), reference()}} | ignore | {error, term()} .br .fi .RS .LP Return value from the \fIstart_monitor()\fR\& functions\&. .RE .nf \fBenter_loop_opt()\fR\& = .br {hibernate_after, HibernateAfterTimeout :: timeout()} | .br {debug, Dbgs :: [sys:debug_option()]} .br .fi .RS .LP Options that can be used when starting a \fIgen_statem\fR\& server through, \fIenter_loop/4-6\fR\&\&. .RS 2 .TP 2 .B \fIhibernate_after\fR\&: \fIHibernateAfterTimeout\fR\& specifies that the \fIgen_statem\fR\& process awaits any message for \fIHibernateAfterTimeout\fR\& milliseconds and if no message is received, the process goes into hibernation automatically (by calling \fIproc_lib:hibernate/3\fR\&)\&. .TP 2 .B \fIdebug\fR\&: For every entry in \fIDbgs\fR\&, the corresponding function in \fIsys\fR\& is called\&. .RE .RE .nf \fBfrom()\fR\& = {To :: pid(), Tag :: term()} .br .fi .RS .LP Destination to use when replying through, for example, the \fIaction()\fR\& \fI{reply,From,Reply}\fR\& to a process that has called the \fIgen_statem\fR\& server using \fIcall/2\fR\&\&. .RE .nf \fBstate()\fR\& = state_name() | term() .br .fi .RS .LP If the \fIcallback mode\fR\& is \fIhandle_event_function\fR\&, the state can be any term\&. After a \fIstate change\fR\& (\fINextState =/= State\fR\&), all postponed events are retried\&. .RE .nf \fBstate_name()\fR\& = atom() .br .fi .RS .LP If the \fIcallback mode\fR\& is \fIstate_functions\fR\&, the state must be an atom\&. After a \fIstate change\fR\& (\fINextState =/= State\fR\&), all postponed events are retried\&. Note that the state \fIterminate\fR\& is not possible to use since it would collide with the optional callback function \fIModule:terminate/3\fR\&\&. .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 \fIstate()\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 external_event_type() | timeout_event_type() | internal .br .fi .RS .LP There are 3 categories of events: external, timeout, and \fIinternal\fR\&\&. .LP \fIinternal\fR\& events can only be generated by the state machine itself through the \fItransition action\fR\& \fInext_event\fR\&\&. .RE .nf \fBexternal_event_type()\fR\& = {call, From :: from()} | cast | info .br .fi .RS .LP External events are of 3 types: \fI{call,From}\fR\&, \fIcast\fR\&, or \fIinfo\fR\&\&. Type \fIcall\fR\& originates from the API functions \fIcall/2\fR\& and \fIsend_request/2\fR\&\&. For calls, the event contains whom to reply to\&. Type \fIcast\fR\& originates from the API function \fIcast/2\fR\&\&. Type \fIinfo\fR\& originates from regular process messages sent to the \fIgen_statem\fR\&\&. .RE .nf \fBtimeout_event_type()\fR\& = .br timeout | {timeout, Name :: term()} | state_timeout .br .fi .RS .LP There are 3 types of time-out events that the state machine can generate for itself with the corresponding timeout_action()s\&. .RE .nf \fBcallback_mode_result()\fR\& = .br callback_mode() | [callback_mode() | state_enter()] .br .fi .RS .LP This is the return type from \fIModule:callback_mode/0\fR\& and selects \fIcallback mode\fR\& and whether to do \fIstate 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 with the return value from \fIModule:callback_mode/0\fR\&: .RS 2 .TP 2 .B \fIstate_functions\fR\&: The state must be of type \fIstate_name()\fR\& and one callback function per state, that is, \fIModule:StateName/3\fR\&, is used\&. .TP 2 .B \fIhandle_event_function\fR\&: The state can be any term and the callback function \fIModule:handle_event/4\fR\& is used for all states\&. .RE .LP The function \fIModule:callback_mode/0\fR\& is called when starting the \fIgen_statem\fR\&, after code change and after changing the callback module with any of the actions \fIchange_callback_module\fR\&, \fIpush_callback_module\fR\& or \fIpop_callback_module\fR\&\&. The result is cached for subsequent calls to state callbacks\&. .RE .nf \fBstate_enter()\fR\& = state_enter .br .fi .RS .LP Whether the state machine should use \fIstate enter calls\fR\& or not is selected when starting the \fIgen_statem\fR\& and after code change using the return value from \fIModule:callback_mode/0\fR\&\&. .LP If \fIModule:callback_mode/0\fR\& returns a list containing \fIstate_enter\fR\&, the \fIgen_statem\fR\& engine will, at every \fIstate change\fR\&, call the state callback with arguments \fI(enter, OldState, Data)\fR\& or \fI(enter, OldState, State, Data)\fR\&, depending on the \fIcallback mode\fR\&\&. This may look like an event but is really a call performed after the previous \fIstate callback\fR\& returned and before any event is delivered to the new \fIstate callback\fR\&\&. See \fIModule:StateName/3\fR\& and \fIModule:handle_event/4\fR\&\&. Such a call can be repeated by returning a \fIrepeat_state\fR\& or \fIrepeat_state_and_data\fR\& tuple from the \fIstate callback\fR\&\&. .LP If \fIModule:callback_mode/0\fR\& does not return such a list, no \fIstate enter calls\fR\& are done\&. .LP If \fIModule:code_change/4\fR\& should transform the state, it is regarded as a state rename and not a \fIstate change\fR\&, which will not cause a \fIstate enter call\fR\&\&. .LP Note that a \fIstate enter call\fR\& \fIwill\fR\& be done right before entering the initial state even though this actually is not a \fIstate change\fR\&\&. In this case \fIOldState =:= State\fR\&, which cannot happen for a subsequent state change, but will happen when repeating the \fIstate enter call\fR\&\&. .RE .nf \fBtransition_option()\fR\& = .br postpone() | .br hibernate() | .br event_timeout() | .br generic_timeout() | .br state_timeout() .br .fi .RS .LP Transition options can be set by actions and modify the \fIstate transition\fR\&\&. The \fIstate transition\fR\& takes place when the \fIstate callback\fR\& has processed an event and returns\&. Here are the sequence of steps for a \fIstate transition\fR\&: .RS 2 .TP 2 * All returned actions are processed in order of appearance\&. In this step all replies generated by any \fIreply_action()\fR\& are sent\&. Other actions set \fItransition_option()\fR\&s that come into play in subsequent steps\&. .LP .TP 2 * If \fIstate enter calls\fR\& are used, and either it is the initial state or one of the callback results \fIrepeat_state_and_data\fR\& or \fIrepeat_state_and_data\fR\& is used the \fIgen_statem\fR\& engine calls the current state callback with arguments \fI(enter, State, Data)\fR\& or \fI(enter, State, State, Data)\fR\& (depending on \fIcallback mode\fR\&) and when it returns starts again from the top of this sequence\&. .RS 2 .LP If \fIstate enter calls\fR\& are used, and the state changes the \fIgen_statem\fR\& engine calls the new state callback with arguments \fI(enter, OldState, Data)\fR\& or \fI(enter, OldState, State, Data)\fR\& (depending on \fIcallback mode\fR\&) and when it returns starts again from the top of this sequence\&. .RE .LP .TP 2 * If \fIpostpone()\fR\& is \fItrue\fR\&, the current event is postponed\&. .LP .TP 2 * If this is a \fIstate change\fR\&, the queue of incoming events is reset to start with the oldest postponed\&. .LP .TP 2 * All events stored with \fIaction()\fR\& \fInext_event\fR\& are inserted to be processed before previously queued events\&. .LP .TP 2 * Time-out timers \fIevent_timeout()\fR\&, \fIgeneric_timeout()\fR\& and \fIstate_timeout()\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 time-out requested, the corresponding time-out zero event is enqueued as the newest received event; that is after already queued events such as inserted and postponed events\&. .RS 2 .LP Any event cancels an \fIevent_timeout()\fR\& so a zero time event time-out is only generated if the event queue is empty\&. .RE .RS 2 .LP A \fIstate change\fR\& cancels a \fIstate_timeout()\fR\& and any new transition option of this type belongs to the new state, that is; a \fIstate_timeout()\fR\& applies to the state the state machine enters\&. .RE .LP .TP 2 * If there are enqueued events the \fIstate callback\fR\& for the possibly new state is called with the oldest enqueued event, and we start again from the top of this sequence\&. .LP .TP 2 * Otherwise the \fIgen_statem\fR\& goes into \fIreceive\fR\& or hibernation (if \fIhibernate()\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 \fIstate callback\fR\& is called with the corresponding event, and we start again from the top of this sequence\&. .LP .RE .RE .nf \fBpostpone()\fR\& = boolean() .br .fi .RS .LP If \fItrue\fR\&, postpones the current event and retries it after a \fIstate change\fR\& (\fINextState =/= State\fR\&)\&. .RE .nf \fBhibernate()\fR\& = boolean() .br .fi .RS .LP If \fItrue\fR\&, hibernates the \fIgen_statem\fR\& by calling \fIproc_lib:hibernate/3\fR\& before going into \fIreceive\fR\& to wait for a new external event\&. .LP .RS -4 .B Note: .RE If there are enqueued events to process when hibrnation is requested, this is optimized by not hibernating but instead calling \fIerlang:garbage_collect/0\fR\& to simulate that the \fIgen_statem\fR\& entered hibernation and immediately got awakened by an enqueued event\&. .RE .nf \fBevent_timeout()\fR\& = timeout() | integer() .br .fi .RS .LP Starts a timer set by \fIenter_action()\fR\& \fItimeout\fR\&\&. When the timer expires an event of \fIevent_type()\fR\& \fItimeout\fR\& will be generated\&. See \fIerlang:start_timer/4\fR\& for how \fITime\fR\& and \fIOptions\fR\& are interpreted\&. Future \fIerlang:start_timer/4\fR\& \fIOptions\fR\& will not necessarily be supported\&. .LP Any event that arrives cancels this time-out\&. Note that a retried or inserted event counts as arrived\&. So does a state time-out zero event, if it was generated before this time-out is requested\&. .LP If \fITime\fR\& is \fIinfinity\fR\&, no timer is started, as it never would expire anyway\&. .LP If \fITime\fR\& is relative and \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, but after already queued events\&. .LP Note that it is not possible nor needed to cancel this time-out, as it is cancelled automatically by any other event\&. .RE .nf \fBgeneric_timeout()\fR\& = timeout() | integer() .br .fi .RS .LP Starts a timer set by \fIenter_action()\fR\& \fI{timeout,Name}\fR\&\&. When the timer expires an event of \fIevent_type()\fR\& \fI{timeout,Name}\fR\& will be generated\&. See \fIerlang:start_timer/4\fR\& for how \fITime\fR\& and \fIOptions\fR\& are interpreted\&. Future \fIerlang:start_timer/4\fR\& \fIOptions\fR\& will not necessarily be supported\&. .LP If \fITime\fR\& is \fIinfinity\fR\&, no timer is started, as it never would expire anyway\&. .LP If \fITime\fR\& is relative and \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 a timer with the same \fIName\fR\& while it is running will restart it with the new time-out value\&. Therefore it is possible to cancel a specific time-out by setting it to \fIinfinity\fR\&\&. .RE .nf \fBstate_timeout()\fR\& = timeout() | integer() .br .fi .RS .LP Starts a timer set by \fIenter_action()\fR\& \fIstate_timeout\fR\&\&. When the timer expires an event of \fIevent_type()\fR\& \fIstate_timeout\fR\& will be generated\&. See \fIerlang:start_timer/4\fR\& for how \fITime\fR\& and \fIOptions\fR\& are interpreted\&. Future \fIerlang:start_timer/4\fR\& \fIOptions\fR\& will not necessarily be supported\&. .LP If \fITime\fR\& is \fIinfinity\fR\&, no timer is started, as it never would expire anyway\&. .LP If \fITime\fR\& is relative and \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 \fBtimeout_option()\fR\& = {abs, Abs :: boolean()} .br .fi .RS .LP If \fIAbs\fR\& is \fItrue\fR\& an absolute timer is started, and if it is \fIfalse\fR\& a relative, which is the default\&. See \fIerlang:start_timer/4\fR\& for details\&. .LP .RE .nf \fBaction()\fR\& = .br postpone | .br {postpone, Postpone :: postpone()} | .br {next_event, .br EventType :: event_type(), .br EventContent :: term()} | .br {change_callback_module, NewModule :: module()} | .br {push_callback_module, NewModule :: module()} | .br pop_callback_module | .br enter_action() .br .fi .RS .LP These \fItransition actions\fR\& can be invoked by returning them from the \fIstate callback\fR\& when it is called with an event, from \fIModule:init/1\fR\& or by giving them to \fIenter_loop/5,6\fR\&\&. .LP Actions are executed in the containing list order\&. .LP Actions that set transition options override any previous of the same type, so the last in the containing list wins\&. For example, the last \fIpostpone()\fR\& overrides any previous \fIpostpone()\fR\& in the list\&. .RS 2 .TP 2 .B \fIpostpone\fR\&: Sets the \fItransition_option()\fR\& \fIpostpone()\fR\& for this \fIstate transition\fR\&\&. This action is ignored when returned from \fIModule:init/1\fR\& or given to \fIenter_loop/5,6\fR\&, as there is no event to postpone in those cases\&. .TP 2 .B \fInext_event\fR\&: This action does not set any \fItransition_option()\fR\& but instead 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 \fIinternal\fR\& is to be used when you want to reliably distinguish an event inserted this way from any external event\&. .RE .TP 2 .B \fIchange_callback_module\fR\&: Changes the callback module to \fINewModule\fR\& which will be used when calling all subsequent state callbacks\&. .RS 2 .LP The \fIgen_statem\fR\& engine will find out the \fIcallback mode\fR\& of \fINewModule\fR\& by calling \fINewModule:callback_mode/0\fR\& before the next state callback\&. .RE .RS 2 .LP Changing the callback module does not affect the \fIstate transition\fR\& in any way, it only changes which module that handles the events\&. Be aware that all relevant callback functions in \fINewModule\fR\& such as the state callback, \fINewModule:code_change/4\fR\&, \fINewModule:format_status/2\fR\& and \fINewModule:terminate/3\fR\& must be able to handle the state and data from the old module\&. .RE .TP 2 .B \fIpush_callback_module\fR\&: Pushes the current callback module to the top of an internal stack of callback modules and changes the callback module to \fINewModule\fR\&\&. Otherwise like \fI{change_callback_module, NewModule}\fR\& above\&. .TP 2 .B \fIpop_callback_module\fR\&: Pops the top module from the internal stack of callback modules and changes the callback module to be the popped module\&. If the stack is empty the server fails\&. Otherwise like \fI{change_callback_module, NewModule}\fR\& above\&. .RE .RE .nf \fBenter_action()\fR\& = .br hibernate | .br {hibernate, Hibernate :: hibernate()} | .br timeout_action() | .br reply_action() .br .fi .RS .LP These \fItransition actions\fR\& can be invoked by returning them from the \fIstate callback\fR\&, from \fIModule:init/1\fR\& or by giving them to \fIenter_loop/5,6\fR\&\&. .LP Actions are executed in the containing list order\&. .LP Actions that set transition options override any previous of the same type, so the last in the containing list wins\&. For example, the last \fIevent_timeout()\fR\& overrides any previous \fIevent_timeout()\fR\& in the list\&. .RS 2 .TP 2 .B \fIhibernate\fR\&: Sets the \fItransition_option()\fR\& \fIhibernate()\fR\& for this \fIstate transition\fR\&\&. .RE .RE .nf \fBtimeout_action()\fR\& = .br (Time :: event_timeout()) | .br {timeout, Time :: event_timeout(), EventContent :: term()} | .br {timeout, .br Time :: event_timeout(), .br EventContent :: term(), .br Options :: timeout_option() | [timeout_option()]} | .br {{timeout, Name :: term()}, .br Time :: generic_timeout(), .br EventContent :: term()} | .br {{timeout, Name :: term()}, .br Time :: generic_timeout(), .br EventContent :: term(), .br Options :: timeout_option() | [timeout_option()]} | .br {state_timeout, .br Time :: state_timeout(), .br EventContent :: term()} | .br {state_timeout, .br Time :: state_timeout(), .br EventContent :: term(), .br Options :: timeout_option() | [timeout_option()]} | .br timeout_cancel_action() | .br timeout_update_action() .br .fi .RS .LP These \fItransition actions\fR\& can be invoked by returning them from the \fIstate callback\fR\&, from \fIModule:init/1\fR\& or by giving them to \fIenter_loop/5,6\fR\&\&. .LP These time-out actions sets time-out transition options\&. .RS 2 .TP 2 .B \fITime\fR\&: Short for \fI{timeout,Time,Time}\fR\&, that is, the time-out message is the time-out time\&. This form exists to make the \fIstate callback\fR\& return value \fI{next_state,NextState,NewData,Time}\fR\& allowed like for \fIgen_fsm\fR\&\&. .TP 2 .B \fItimeout\fR\&: Sets the \fItransition_option()\fR\& \fIevent_timeout()\fR\& to \fITime\fR\& with \fIEventContent\fR\& and time-out options \fIOptions\fR\&\&. .TP 2 .B \fI{timeout,Name}\fR\&: Sets the \fItransition_option()\fR\& \fIgeneric_timeout()\fR\& to \fITime\fR\& for \fIName\fR\& with \fIEventContent\fR\& and time-out options \fIOptions\fR\&\&. .TP 2 .B \fIstate_timeout\fR\&: Sets the \fItransition_option()\fR\& \fIstate_timeout()\fR\& to \fITime\fR\& with \fIEventContent\fR\& and time-out options \fIOptions\fR\&\&. .RE .RE .nf \fBtimeout_cancel_action()\fR\& = .br {timeout, cancel} | .br {{timeout, Name :: term()}, cancel} | .br {state_timeout, cancel} .br .fi .RS .LP This is a shorter and clearer form of timeout_action() with \fITime = infinity\fR\& which cancels a time-out\&. .RE .nf \fBtimeout_update_action()\fR\& = .br {timeout, update, EventContent :: term()} | .br {{timeout, Name :: term()}, update, EventContent :: term()} | .br {state_timeout, update, EventContent :: term()} .br .fi .RS .LP Updates a time-out with a new \fIEventContent\fR\&\&. See timeout_action() for how to start a time-out\&. .LP If no time-out of the same type is active instead insert the time-out event just like when starting a time-out with relative \fITime = 0\fR\&\&. .RE .nf \fBreply_action()\fR\& = {reply, From :: from(), Reply :: term()} .br .fi .RS .LP This \fItransition action\fR\& can be invoked by returning it from the \fIstate callback\fR\&, from \fIModule:init/1\fR\& or by giving it to \fIenter_loop/5,6\fR\&\&. .LP It does not set any \fItransition_option()\fR\& but instead replies to a caller waiting for a reply in \fIcall/2\fR\&\&. \fIFrom\fR\& must be the term from argument \fI{call,From}\fR\& in a call to a \fIstate callback\fR\&\&. .LP Note that using this action from \fIModule:init/1\fR\& or \fIenter_loop/5,6\fR\& would be weird on the border of witchcraft since there has been no earlier call to a \fIstate callback\fR\& in this server\&. .RE .nf \fBinit_result(StateType)\fR\& = .br {ok, State :: StateType, Data :: data()} | .br {ok, .br State :: StateType, .br Data :: data(), .br Actions :: [action()] | action()} | .br ignore | .br {stop, Reason :: term()} .br .fi .RS .LP For a succesful initialization, \fIState\fR\& is the initial \fIstate()\fR\& and \fIData\fR\& the initial server \fIdata()\fR\& of the \fIgen_statem\fR\&\&. .LP The \fIActions\fR\& are executed when entering the first state just as for a \fIstate callback\fR\&, except that the action \fIpostpone\fR\& is forced to \fIfalse\fR\& since there is no event to postpone\&. .LP For an unsuccesful initialization, \fI{stop,Reason}\fR\& or \fIignore\fR\& should be used; see \fIstart_link/3,4\fR\&\&. .RE .nf \fBstate_enter_result(State)\fR\& = .br {next_state, State, NewData :: data()} | .br {next_state, State, .br NewData :: data(), .br Actions :: [enter_action()] | enter_action()} | .br state_callback_result(enter_action()) .br .fi .RS .LP \fIState\fR\& is the current state and it cannot be changed since the state callback was called with a \fIstate enter call\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 :: data()} | .br {next_state, .br NextState :: StateType, .br NewData :: data(), .br Actions :: [action()] | action()} | .br state_callback_result(action()) .br .fi .RS .LP \fIStateType\fR\& is \fIstate_name()\fR\& if \fIcallback mode\fR\& is \fIstate_functions\fR\&, or \fIstate()\fR\& if \fIcallback mode\fR\& is \fIhandle_event_function\fR\&\&. .RS 2 .TP 2 .B \fInext_state\fR\&: The \fIgen_statem\fR\& does a \fIstate transition\fR\& to \fINextState\fR\& (which can be the same as the current state), sets \fINewData\fR\&, and executes all \fIActions\fR\&\&. If \fINextState =/= CurrentState\fR\& the \fIstate transition\fR\& is a \fIstate change\fR\&\&. .RE .RE .nf \fBstate_callback_result(ActionType)\fR\& = .br {keep_state, NewData :: data()} | .br {keep_state, .br NewData :: data(), .br Actions :: [ActionType] | ActionType} | .br keep_state_and_data | .br {keep_state_and_data, Actions :: [ActionType] | ActionType} | .br {repeat_state, NewData :: data()} | .br {repeat_state, .br NewData :: data(), .br Actions :: [ActionType] | ActionType} | .br repeat_state_and_data | .br {repeat_state_and_data, Actions :: [ActionType] | ActionType} | .br stop | .br {stop, Reason :: term()} | .br {stop, Reason :: term(), NewData :: data()} | .br {stop_and_reply, .br Reason :: term(), .br Replies :: [reply_action()] | reply_action()} | .br {stop_and_reply, .br Reason :: term(), .br Replies :: [reply_action()] | reply_action(), .br NewData :: data()} .br .fi .RS .LP \fIActionType\fR\& is \fIenter_action()\fR\& if the state callback was called with a \fIstate enter call\fR\& and \fIaction()\fR\& if the state callback was called with an event\&. .RS 2 .TP 2 .B \fIkeep_state\fR\&: The same as \fI{next_state,CurrentState,NewData,Actions}\fR\&\&. .TP 2 .B \fIkeep_state_and_data\fR\&: The same as \fI{keep_state,CurrentData,Actions}\fR\&\&. .TP 2 .B \fIrepeat_state\fR\&: If the \fIgen_statem\fR\& runs with \fIstate enter calls\fR\&, the \fIstate enter call\fR\& is repeated, see type \fItransition_option()\fR\&, other than that \fIrepeat_state\fR\& is the same as \fIkeep_state\fR\&\&. .TP 2 .B \fIrepeat_state_and_data\fR\&: The same as \fI{repeat_state,CurrentData,Actions}\fR\&\&. .TP 2 .B \fIstop\fR\&: Terminates the \fIgen_statem\fR\& by calling \fIModule:terminate/3\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 \fIModule:terminate/3\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 .nf \fBrequest_id()\fR\& = term() .br .fi .RS .LP A request handle, see \fIsend_request/2\fR\& for details\&. .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\& \fIServerRef\fR\& by sending a request and waiting until its reply arrives\&. The \fIgen_statem\fR\& calls the \fIstate callback\fR\& with \fIevent_type()\fR\& \fI{call,From}\fR\& and event content \fIRequest\fR\&\&. .LP A \fIReply\fR\& is generated when a \fIstate callback\fR\& returns with \fI{reply,From,Reply}\fR\& as one \fIaction()\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 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\&. Note that there is an odd chance to get a late reply even with \fI{dirty_timeout,infinity}\fR\& or \fIinfinity\fR\& for example in the event of network problems\&. So why not just let the calling process die by not catching the exception? .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\& \fIServerRef\fR\& and returns \fIok\fR\& immediately, ignoring if the destination node or \fIgen_statem\fR\& does not exist\&. The \fIgen_statem\fR\& calls the \fIstate callback\fR\& with \fIevent_type()\fR\& \fIcast\fR\& and event content \fIMsg\fR\&\&. .RE .LP .nf .B check_response(Msg :: term(), RequestId :: request_id()) -> .B {reply, Reply :: term()} | .B no_reply | .B {error, {term(), server_ref()}} .br .fi .br .RS .LP This function is used to check if a previously received message, for example by \fIreceive\fR\& or \fIhandle_info/2\fR\&, is a result of a request made with \fIsend_request/2\fR\&\&. If \fIMsg\fR\& is a reply to the handle \fIRequestId\fR\& the result of the request is returned in \fIReply\fR\&\&. Otherwise returns \fIno_reply\fR\& and no cleanup is done, and thus the function shall be invoked repeatedly until a reply is returned\&. .LP The return value \fIReply\fR\& is generated when a \fIstate callback\fR\& returns with \fI{reply,From,Reply}\fR\& as one \fIaction()\fR\&, and that \fIReply\fR\& becomes the return value of this function\&. .LP The function returns an error if the \fIgen_statem\fR\& dies before or during this request\&. .RE .LP .nf .B enter_loop(Module :: module(), .B Opts :: [enter_loop_opt()], .B State :: state(), .B Data :: data()) -> .B no_return() .br .fi .br .RS .LP The same as \fIenter_loop/6\fR\& with \fIActions = []\fR\& except that no \fIserver_name()\fR\& must have been registered\&. This creates an anonymous server\&. .RE .LP .nf .B enter_loop(Module :: module(), .B Opts :: [enter_loop_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 \fIenter_loop/6\fR\& except that no \fIserver_name()\fR\& must have been registered and \fIActions = Server_or_Actions\fR\&\&. This creates an anonymous server\&. .LP Otherwise the same as \fIenter_loop/6\fR\& with \fIServer = Server_or_Actions\fR\& and \fIActions = []\fR\&\&. .RE .LP .nf .B enter_loop(Module :: module(), .B Opts :: [enter_loop_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 \fIproc_lib\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 \fIstart[_link|_monitor]/3,4\fR\&\&. .LP If \fIServer\fR\& is \fIself()\fR\& an anonymous server is created just as when using \fIstart[_link|_monitor]/3\fR\&\&. If \fIServer\fR\& is a \fIserver_name()\fR\& a named server is created just as when using \fIstart[_link|_monitor]/4\fR\&\&. However, the \fIserver_name()\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 \fIModule:init/1\fR\&\&. Also, the callback module does not need to export a \fIModule:init/1\fR\& function\&. .LP The function fails if the calling process was not started by a \fIproc_lib\fR\& start function, or if it is not registered according to \fIserver_name()\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 \fIcall/2\fR\& when the reply cannot be defined in the return value of a \fIstate callback\fR\&\&. .LP \fIFrom\fR\& must be the term from argument \fI{call,From}\fR\& to the \fIstate callback\fR\&\&. A reply or multiple replies canalso be sent using one or several \fIreply_action()\fR\&s from a \fIstate callback\fR\&\&. .LP .RS -4 .B Note: .RE A reply sent with this function is not visible in \fIsys\fR\& debug output\&. .RE .LP .nf .B send_request(ServerRef :: server_ref(), Request :: term()) -> .B RequestId :: request_id() .br .fi .br .RS .LP Sends a request to the \fIgen_statem\fR\& \fIServerRef\fR\& and returns a handle \fIRequestId\fR\&\&. .LP The return value \fIRequestId\fR\& shall later be used with \fIwait_response/1,2\fR\& or \fIcheck_response/2\fR\& to fetch the actual result of the request\&. .LP The call \fIgen_statem:wait_response(gen_statem:send_request(ServerRef,Request), Timeout)\fR\& can be seen as equivalent to \fIgen_statem:call(Server,Request,Timeout)\fR\&, ignoring the error handling\&. .LP The \fIgen_statem\fR\& calls the \fIstate callback\fR\& with \fIevent_type()\fR\& \fI{call,From}\fR\& and event content \fIRequest\fR\&\&. .LP A \fIReply\fR\& is generated when a \fIstate callback\fR\& returns with \fI{reply,From,Reply}\fR\& as one \fIaction()\fR\&, and that \fIReply\fR\& becomes the return value of \fIwait_response/1,2\fR\& or \fIcheck_response/2\fR\& function\&. .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 \fIproc_lib\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 \fIstart_link/3,4\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 \fIproc_lib\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 \fIModule:init/1\fR\& to initialize the server\&. To ensure a synchronized startup procedure, \fIstart_link/3,4\fR\& does not return until \fIModule:init/1\fR\& has returned\&. .LP \fIServerName\fR\& specifies the \fIserver_name()\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 \fIModule:init/1\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 \fI{error,timeout}\fR\&\&. .LP .TP 2 * If option \fI{hibernate_after,HibernateAfterTimeout}\fR\& is present, the \fIgen_statem\fR\& process awaits any message for \fIHibernateAfterTimeout\fR\& milliseconds and if no message is received, the process goes into hibernation automatically (by calling \fIproc_lib:hibernate/3\fR\&)\&. .LP .TP 2 * If option \fI{debug,Dbgs}\fR\& is present in \fIOpts\fR\&, debugging through \fIsys\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 \fIerlang:spawn_opt/2\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 \fI{ok,Pid}\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 \fI{error,{already_started,Pid}}\fR\&, where \fIPid\fR\& is the \fIpid()\fR\& of that process\&. .LP If \fIModule:init/1\fR\& fails with \fIReason\fR\&, this function returns \fI{error,Reason}\fR\&\&. If \fIModule:init/1\fR\& returns \fI{stop,Reason}\fR\& or \fIignore\fR\&, the process is terminated and this function returns \fI{error,Reason}\fR\& or \fIignore\fR\&, respectively\&. .RE .LP .nf .B start_monitor(Module :: module(), .B Args :: term(), .B Opts :: [start_opt()]) -> .B start_mon_ret() .br .fi .br .nf .B start_monitor(ServerName :: server_name(), .B Module :: module(), .B Args :: term(), .B Opts :: [start_opt()]) -> .B start_mon_ret() .br .fi .br .RS .LP Creates a standalone \fIgen_statem\fR\& process according to OTP design principles (using \fIproc_lib\fR\& primitives) and atomically sets up a monitor to the newly created process\&. 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 \fIstart_link/3,4\fR\&\&. Note that the return value on successful start differs from \fIstart_link/3,4\fR\&\&. \fIstart_monitor/3,4\fR\& will return \fI{ok,{Pid,Mon}}\fR\& where \fIPid\fR\& is the process identifier of the process, and \fIMon\fR\& is a reference to the monitor set up to monitor the process\&. If the start is not successful, the caller will be blocked until the \fIDOWN\fR\& message has been received and removed from the message queue\&. .RE .LP .nf .B stop(ServerRef :: server_ref()) -> ok .br .fi .br .RS .LP The same as \fIstop(ServerRef, normal, infinity)\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\& \fIServerRef\fR\& to exit with the specified \fIReason\fR\& and waits for it to terminate\&. The \fIgen_statem\fR\& calls \fIModule:terminate/3\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 \fIlogger(3erl)\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 .LP .nf .B wait_response(RequestId :: request_id()) -> .B {reply, Reply :: term()} | .B {error, {term(), server_ref()}} .br .fi .br .nf .B wait_response(RequestId :: request_id(), Timeout :: timeout()) -> .B {reply, Reply :: term()} | .B timeout | .B {error, {term(), server_ref()}} .br .fi .br .RS .LP This function is used to wait for a reply of a request made with \fIsend_request/2\fR\& from the \fIgen_statem\fR\& process\&. This function must be called from the same process from which \fIsend_request/2\fR\& was made\&. .LP \fITimeout\fR\& is an integer greater then or equal to zero that specifies how many milliseconds to wait for an reply, or the atom \fIinfinity\fR\& to wait indefinitely\&. Defaults to \fIinfinity\fR\&\&. If no reply is received within the specified time, the function returns \fItimeout\fR\& and no cleanup is done, and thus the function can be invoked repeatedly until a reply is returned\&. .LP The return value \fIReply\fR\& is generated when a \fIstate callback\fR\& returns with \fI{reply,From,Reply}\fR\& as one \fIaction()\fR\&, and that \fIReply\fR\& becomes the return value of this function\&. .LP The function returns an error if the \fIgen_statem\fR\& dies before or during this function call\&. .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 = callback_mode() | [ callback_mode() | state_enter() ] .br .RE .RE .RS .LP This function is called by a \fIgen_statem\fR\& when it needs to find out the \fIcallback mode\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, after code change, and after changing the callback module, but before the first \fIstate callback\fR\& in the current callback module\&'s code version is called\&. More occasions may be added in future versions of \fIgen_statem\fR\&\&. .LP Server start happens either when \fIModule:init/1\fR\& returns or when \fIenter_loop/4-6\fR\& is called\&. Code change happens when \fIModule:code_change/4\fR\& returns\&. A change of the callback module happens when a \fIstate callback\fR\& returns any of the actions \fIchange_callback_module\fR\&, \fIpush_callback_module\fR\& or \fIpop_callback_module\fR\&\&. .LP The \fICallbackMode\fR\& is either just \fIcallback_mode()\fR\& or a list containing \fIcallback_mode()\fR\& and possibly the atom \fIstate_enter\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 = state() .br OldData = NewData = data() .br Reason = term() .br .RE .RE .RS .LP .RS -4 .B Note: .RE This callback is optional, so callback modules need not export it\&. If a release upgrade/downgrade with \fIChange = {advanced,Extra}\fR\& specified in the \fI\&.appup\fR\& file is made when \fIcode_change/4\fR\& is not implemented the process will crash with exit reason \fIundef\fR\&\&. .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 \fIappup\fR\& file\&. For more information, see OTP Design Principles\&. .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\& cannot 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\&. .LP Also note when upgrading a \fIgen_statem\fR\&, this function and hence the \fIChange = {advanced,Extra}\fR\& parameter in the \fIappup\fR\& file is not only needed to update the internal state or to act on the \fIExtra\fR\& argument\&. It is also needed if an upgrade or downgrade should change \fIcallback mode\fR\&, or else the \fIcallback mode\fR\& after the code change will not be honoured, most probably causing a server crash\&. .LP If the server changes callback module using any of the actions \fIchange_callback_module\fR\&, \fIpush_callback_module\fR\& or \fIpop_callback_module\fR\&, be aware that it is always the current callback module that will get this callback call\&. That the current callback module handles the current state and data update should be no surprise, but it must be able to handle even parts of the state and data that it is not familiar with, somehow\&. .LP In the supervisor child specification there is a list of modules which is recommended to contain only the callback module\&. For a \fIgen_statem\fR\& with multiple callback modules there is no real need to list all of them, it may not even be possible since the list could change after code upgrade\&. If this list would contain only the start callback module, as recommended, what is important is to upgrade \fIthat\fR\& module whenever a \fIsynchronized code replacement\fR\& is done\&. Then the release handler concludes that an upgrade that upgrades \fIthat\fR\& module needs to suspend, code change, and resume any server whose child specification declares that it is using \fIthat\fR\& module\&. And again; the \fIcurrent\fR\& callback module will get the \fIModule:code_change/4\fR\& call\&. .RE .LP .B Module:init(Args) -> Result(StateType) .br .RS .LP Types: .RS 3 Args = term() .br Result(StateType) = init_result(StateType) .br .RE .RE .RS .LP Whenever a \fIgen_statem\fR\& is started using \fIstart_link/3,4\fR\&, \fIstart_monitor/3,4\fR\&, or \fIstart/3,4\fR\&, this 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 that start function\&. .LP .RS -4 .B Note: .RE Note that if the \fIgen_statem\fR\& is started through \fIproc_lib\fR\& and \fIenter_loop/4-6\fR\&, this callback will never be called\&. Since this callback is not optional it can in that case be implemented as: .LP .nf init(Args) -> erlang:error(not_implemented, [Args]). .fi .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 = state() .br Data = data() .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 \fIsys:get_status/1,2\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 \fIsys:get_status/1,2\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 \fIState\fR\& is the internal state of the \fIgen_statem\fR\&\&. .LP \fIData\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 \fIsys:get_status/1,2\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 \fIsys:get_status/1,2\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 = event_type() .br EventContent = term() .br State = state() .br Data = NewData = data() .br StateEnterResult(StateName) = state_enter_result(StateName) .br StateFunctionResult = event_handler_result(state_name()) .br StateEnterResult(State) = state_enter_result(State) .br HandleEventResult = event_handler_result(state()) .br .RE .RE .RS .LP Whenever a \fIgen_statem\fR\& receives an event from \fIcall/2\fR\&, \fIcast/2\fR\&, or as a normal process message, one of these functions is called\&. If \fIcallback mode\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 \fI{call,From}\fR\&, the caller waits for a reply\&. The reply can be sent from this or from any other \fIstate callback\fR\& by returning with \fI{reply,From,Reply}\fR\& in \fIActions\fR\&, in \fIReplies\fR\&, or by calling \fIreply(From, Reply)\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 \fIaction()\fR\&\&. .LP When the \fIgen_statem\fR\& runs with \fIstate enter calls\fR\&, these functions are also called with arguments \fI(enter, OldState, \&.\&.\&.)\fR\& during every \fIstate change\fR\&\&. In this case there are some restrictions on the actions that may be returned: \fIpostpone()\fR\& is not allowed since a \fIstate enter call\fR\& is not an event so there is no event to postpone, and \fI{next_event,_,_}\fR\& is not allowed since using \fIstate enter calls\fR\& should not affect how events are consumed and produced\&. 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\&. Note that it is actually allowed to use \fI{repeat_state, NewData, \&.\&.\&.}\fR\& although it makes little sense since you immediately will be called again with a new \fIstate enter call\fR\& making this just a weird way of looping, and there are better ways to loop in Erlang\&. If you do not update \fINewData\fR\& and have some loop termination condition, or if you use \fI{repeat_state_and_data, _}\fR\& or \fIrepeat_state_and_data\fR\& you have an infinite loop! You are advised to use \fI{keep_state,\&.\&.\&.}\fR\&, \fI{keep_state_and_data,_}\fR\& or \fIkeep_state_and_data\fR\& since changing states from a \fIstate enter call\fR\& is not possible anyway\&. .LP Note the fact that you can use \fIthrow\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 cannot return \fI{next_state,State,Data}\fR\& because \fIState\fR\& or \fIData\fR\& is no longer in scope\&. .RE .LP .B Module:terminate(Reason, State, Data) -> Ignored .br .RS .LP Types: .RS 3 Reason = normal | shutdown | {shutdown,term()} | term() .br State = state() .br Data = data() .br Ignored = term() .br .RE .RE .RS .LP .RS -4 .B Note: .RE This callback is optional, so callback modules need not export it\&. The \fIgen_statem\fR\& module provides a default implementation without cleanup\&. .LP This function is called by a \fIgen_statem\fR\& when it is about to terminate\&. It is to be the opposite of \fIModule:init/1\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 \fIState\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 \fIActions\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 \fIlogger(3erl)\fR\&\&. .RE .SH "SEE ALSO" .LP \fIgen_event(3erl)\fR\&, \fIgen_fsm(3erl)\fR\&, \fIgen_server(3erl)\fR\&, \fIproc_lib(3erl)\fR\&, \fIsupervisor(3erl)\fR\&, \fIsys(3erl)\fR\&\&.