1gen_statem(3)              Erlang Module Definition              gen_statem(3)
2
3
4

NAME

6       gen_statem - Generic state machine behavior.
7

DESCRIPTION

9       gen_statem provides a generic state machine behaviour that for new code
10       replaces its predecessor gen_fsm since Erlang/OTP 20.0. The gen_fsm be‐
11       haviour remains in OTP "as is".
12
13   Note:
14       If you are new to gen_statem and want an overview of concepts and oper‐
15       ation the section gen_statem Behaviour  located  in  the  User's  Guide
16       OTP  Design  Principles    is recommended to read before this reference
17       manual, possibly after the Description section you are reading here.
18
19
20       This reference manual contains type descriptions generated  from  types
21       in the gen_statem source code, so they are correct. However, the gener‐
22       ated descriptions also reflect  the  type  hierarchy,  which  sometimes
23       makes it hard to get a good overview. If so, see the section gen_statem
24       Behaviour  in the  OTP Design Principles  User's Guide.
25
26   Note:
27
28         * This behavior appeared in Erlang/OTP 19.0.
29
30         *
31            In OTP 19.1 a backwards incompatible change of  the  return  tuple
32           from  Module:init/1  was  made  and the mandatory callback function
33           Module:callback_mode/0 was introduced.
34
35         *
36            In OTP 20.0  generic time-outs  were added.
37
38         *
39            In OTP 22.1 time-out content update and explicit  time-out  cancel
40           were added.
41
42         *
43            In  OTP  22.3  the  possibility to change the callback module with
44           actions change_callback_module, push_callback_module and  pop_call‐
45           back_module, was added.
46
47       gen_statem  has  got  the  same features that gen_fsm had and adds some
48       really useful:
49
50         * Co-located state code
51
52         * Arbitrary term state
53
54         * Event postponing
55
56         * Self-generated events
57
58         * State time-out
59
60         * Multiple generic named time-outs
61
62         * Absolute time-out time
63
64         * Automatic state enter calls
65
66         *
67            Reply from other state than the request, sys traceable
68
69         * Multiple sys traceable replies
70
71         * Changing the callback module
72
73       Two callback modes are supported:
74
75         * One for finite-state machines (gen_fsm like),  which  requires  the
76           state  to be an atom and uses that state as the name of the current
77           callback function.
78
79         * One that allows the state to be any term and that uses one callback
80           function for all states.
81
82       The  callback model(s) for gen_statem differs from the one for gen_fsm,
83       but it is still fairly easy to  rewrite from  gen_fsm to gen_statem.
84
85       A generic state machine server process (gen_statem)  implemented  using
86       this  module  has  a  standard  set of interface functions and includes
87       functionality for tracing and error reporting. It also fits into an OTP
88       supervision tree. For more information, see OTP Design Principles.
89
90       A  gen_statem  assumes  all  specific parts to be located in a callback
91       module exporting  a  predefined  set  of  functions.  The  relationship
92       between  the  behavior  functions and the callback functions is as fol‐
93       lows:
94
95       gen_statem module            Callback module
96       -----------------            ---------------
97       gen_statem:start
98       gen_statem:start_link -----> Module:init/1
99
100       Server start or code change
101                             -----> Module:callback_mode/0
102
103       gen_statem:stop       -----> Module:terminate/3
104
105       gen_statem:call
106       gen_statem:cast
107       erlang:send
108       erlang:'!'            -----> Module:StateName/3
109                                    Module:handle_event/4
110
111       -                     -----> Module:terminate/3
112
113       -                     -----> Module:code_change/4
114
115       Events are of different types, so the callback functions can  know  the
116       origin of an event and how to respond.
117
118       If  a  callback  function  fails or returns a bad value, the gen_statem
119       terminates, unless otherwise stated. However,  an  exception  of  class
120       throw  is not regarded as an error but as a valid return from all call‐
121       back functions.
122
123       The state callback for a specific state in a gen_statem is the callback
124       function  that  is  called for all events in this state. It is selected
125       depending on which callback mode that the callback module defines  with
126       the callback function Module:callback_mode/0.
127
128       When  the  callback  mode is state_functions, the state must be an atom
129       and is used as the state callback name;  see  Module:StateName/3.  This
130       co-locates  all  code  for  a  specific  state  in  one function as the
131       gen_statem engine branches depending on state name. Note the fact  that
132       the callback function Module:terminate/3 makes the state name terminate
133       unusable in this mode.
134
135       When the callback mode is handle_event_function, the state can  be  any
136       term  and  the state callback name is Module:handle_event/4. This makes
137       it easy to branch depending on state or event as you desire. Be careful
138       about  which events you handle in which states so that you do not acci‐
139       dentally postpone an event forever creating an infinite busy loop.
140
141       When gen_statem receives a process message  it  is  converted  into  an
142       event and the state callback is called with the event as two arguments:
143       type and content. When the state callback has processed  the  event  it
144       returns  to  gen_statem  which  does  a state transition. If this state
145       transition is to a different state, that is: NextState =/= State, it is
146       a state change.
147
148       The state callback may return transition actions for gen_statem to exe‐
149       cute  during  the  state  transition,  for  example  to  reply   to   a
150       gen_statem:call/2,3.
151
152       One  of  the  possible  transition  actions  is to postpone the current
153       event. Then it is not retried in  the  current  state.  The  gen_statem
154       engine  keeps  a  queue of events divided into the postponed events and
155       the events still to process. After a state change  the  queue  restarts
156       with the postponed events.
157
158       The  gen_statem  event  queue model is sufficient to emulate the normal
159       process message queue with selective receive. Postponing an event  cor‐
160       responds to not matching it in a receive statement, and changing states
161       corresponds to entering a new receive statement.
162
163       The state callback can  insert  events  using  the  transition  actions
164       next_event and such an event is inserted in the event queue as the next
165       to call the state callback with. That is, as if it is the oldest incom‐
166       ing  event.  A  dedicated  event_type()  internal  can be used for such
167       events making them impossible to mistake for external events.
168
169       Inserting an event replaces the trick of calling your  own  state  han‐
170       dling functions that you often would have to resort to in, for example,
171       gen_fsm to force processing an inserted event before others.
172
173       The gen_statem engine can automatically make a specialized call to  the
174       state callback whenever a new state is entered; see state_enter(). This
175       is for writing code common to all state entries. Another way to  do  it
176       is to explicitly insert an event at the state transition, and/or to use
177       a dedicated state transition function, but that is something  you  will
178       have  to  remember  at every state transition to the state(s) that need
179       it.
180
181   Note:
182       If you in gen_statem, for example, postpone an event in one  state  and
183       then  call  another  state callback of yours, you have not done a state
184       change and hence the postponed event is not retried, which  is  logical
185       but can be confusing.
186
187
188       For the details of a state transition, see type transition_option().
189
190       A  gen_statem handles system messages as described in sys. The sys mod‐
191       ule can be used for debugging a gen_statem.
192
193       Notice that a gen_statem does not trap exit signals automatically, this
194       must  be  explicitly  initiated  in  the  callback  module  (by calling
195       process_flag(trap_exit, true).
196
197       Unless otherwise stated, all functions in this module fail if the spec‐
198       ified gen_statem does not exist or if bad arguments are specified.
199
200       The  gen_statem  process  can  go into hibernation; see proc_lib:hiber‐
201       nate/3. It is done when a state  callback  or  Module:init/1  specifies
202       hibernate  in  the returned Actions list. This feature can be useful to
203       reclaim process heap memory while the server is expected to be idle for
204       a long time. However, use this feature with care, as hibernation can be
205       too costly to use after every event; see erlang:hibernate/3.
206
207       There is also a server  start  option  {hibernate_after,  Timeout}  for
208       start/3,4,  start_link/3,4  or  enter_loop/4,5,6,  that  may be used to
209       automatically hibernate the server.
210

EXAMPLE

212       The following example shows a simple pushbutton model  for  a  toggling
213       pushbutton implemented with callback mode state_functions. You can push
214       the button and it replies if it went on or off, and you can ask  for  a
215       count of how many times it has been pushed to switch on.
216
217       The following is the complete callback module file pushbutton.erl:
218
219       -module(pushbutton).
220       -behaviour(gen_statem).
221
222       -export([start/0,push/0,get_count/0,stop/0]).
223       -export([terminate/3,code_change/4,init/1,callback_mode/0]).
224       -export([on/3,off/3]).
225
226       name() -> pushbutton_statem. % The registered server name
227
228       %% API.  This example uses a registered name name()
229       %% and does not link to the caller.
230       start() ->
231           gen_statem:start({local,name()}, ?MODULE, [], []).
232       push() ->
233           gen_statem:call(name(), push).
234       get_count() ->
235           gen_statem:call(name(), get_count).
236       stop() ->
237           gen_statem:stop(name()).
238
239       %% Mandatory callback functions
240       terminate(_Reason, _State, _Data) ->
241           void.
242       code_change(_Vsn, State, Data, _Extra) ->
243           {ok,State,Data}.
244       init([]) ->
245           %% Set the initial state + data.  Data is used only as a counter.
246           State = off, Data = 0,
247           {ok,State,Data}.
248       callback_mode() -> state_functions.
249
250       %%% state callback(s)
251
252       off({call,From}, push, Data) ->
253           %% Go to 'on', increment count and reply
254           %% that the resulting status is 'on'
255           {next_state,on,Data+1,[{reply,From,on}]};
256       off(EventType, EventContent, Data) ->
257           handle_event(EventType, EventContent, Data).
258
259       on({call,From}, push, Data) ->
260           %% Go to 'off' and reply that the resulting status is 'off'
261           {next_state,off,Data,[{reply,From,off}]};
262       on(EventType, EventContent, Data) ->
263           handle_event(EventType, EventContent, Data).
264
265       %% Handle events common to all states
266       handle_event({call,From}, get_count, Data) ->
267           %% Reply with the current count
268           {keep_state,Data,[{reply,From,Data}]};
269       handle_event(_, _, Data) ->
270           %% Ignore all other events
271           {keep_state,Data}.
272
273
274       The following is a shell session when running it:
275
276       1> pushbutton:start().
277       {ok,<0.36.0>}
278       2> pushbutton:get_count().
279       0
280       3> pushbutton:push().
281       on
282       4> pushbutton:get_count().
283       1
284       5> pushbutton:push().
285       off
286       6> pushbutton:get_count().
287       1
288       7> pushbutton:stop().
289       ok
290       8> pushbutton:push().
291       ** exception exit: {noproc,{gen_statem,call,[pushbutton_statem,push,infinity]}}
292            in function  gen:do_for_proc/2 (gen.erl, line 261)
293            in call from gen_statem:call/3 (gen_statem.erl, line 386)
294
295
296       To  compare  styles,  here follows the same example using callback mode
297       handle_event_function, or rather the code  to  replace  after  function
298       init/1 of the pushbutton.erl example file above:
299
300       callback_mode() -> handle_event_function.
301
302       %%% state callback(s)
303
304       handle_event({call,From}, push, off, Data) ->
305           %% Go to 'on', increment count and reply
306           %% that the resulting status is 'on'
307           {next_state,on,Data+1,[{reply,From,on}]};
308       handle_event({call,From}, push, on, Data) ->
309           %% Go to 'off' and reply that the resulting status is 'off'
310           {next_state,off,Data,[{reply,From,off}]};
311       %%
312       %% Event handling common to all states
313       handle_event({call,From}, get_count, State, Data) ->
314           %% Reply with the current count
315           {next_state,State,Data,[{reply,From,Data}]};
316       handle_event(_, _, State, Data) ->
317           %% Ignore all other events
318           {next_state,State,Data}.
319
320

DATA TYPES

322       server_name() =
323           {global, GlobalName :: term()} |
324           {via, RegMod :: module(), Name :: term()} |
325           {local, atom()}
326
327              Name specification to use when starting a gen_statem server. See
328              start_link/3 and server_ref() below.
329
330       server_ref() =
331           pid() |
332           (LocalName :: atom()) |
333           {Name :: atom(), Node :: atom()} |
334           {global, GlobalName :: term()} |
335           {via, RegMod :: module(), ViaName :: term()}
336
337              Server specification to use when addressing a gen_statem server.
338              See call/2 and server_name() above.
339
340              It can be:
341
342                pid() | LocalName:
343                  The gen_statem is locally registered.
344
345                {Name,Node}:
346                  The gen_statem is locally registered on another node.
347
348                {global,GlobalName}:
349                  The gen_statem is globally registered in global.
350
351                {via,RegMod,ViaName}:
352                  The  gen_statem is registered in an alternative process reg‐
353                  istry. The registry callback  module  RegMod  is  to  export
354                  functions         register_name/2,        unregister_name/1,
355                  whereis_name/1, and send/2, which are  to  behave  like  the
356                  corresponding functions in global. Thus, {via,global,Global‐
357                  Name} is the same as {global,GlobalName}.
358
359       start_opt() =
360           {timeout, Time :: timeout()} |
361           {spawn_opt, [proc_lib:spawn_option()]} |
362           enter_loop_opt()
363
364              Options that can be  used  when  starting  a  gen_statem  server
365              through, for example, start_link/3.
366
367       start_ret() = {ok, pid()} | ignore | {error, term()}
368
369              Return   value   from   the   start   functions,   for  example,
370              start_link/3.
371
372       enter_loop_opt() =
373           {hibernate_after, HibernateAfterTimeout :: timeout()} |
374           {debug, Dbgs :: [sys:debug_option()]}
375
376              Options that can be  used  when  starting  a  gen_statem  server
377              through, enter_loop/4-6.
378
379                hibernate_after:
380                  HibernateAfterTimeout  specifies that the gen_statem process
381                  awaits any message  for  HibernateAfterTimeout  milliseconds
382                  and  if no message is received, the process goes into hiber‐
383                  nation automatically (by calling proc_lib:hibernate/3).
384
385                debug:
386                  For every entry in Dbgs, the corresponding function  in  sys
387                  is called.
388
389       from() = {To :: pid(), Tag :: term()}
390
391              Destination  to  use  when  replying  through,  for example, the
392              action() {reply,From,Reply} to a process  that  has  called  the
393              gen_statem server using call/2.
394
395       state() = state_name() | term()
396
397              If  the callback mode is handle_event_function, the state can be
398              any term. After a state change (NextState =/= State), all  post‐
399              poned events are retried.
400
401       state_name() = atom()
402
403              If  the  callback  mode is state_functions, the state must be an
404              atom. After a state change (NextState =/= State), all  postponed
405              events  are retried. Note that the state terminate is not possi‐
406              ble to use since it would collide  with  the  optional  callback
407              function Module:terminate/3.
408
409       data() = term()
410
411              A term in which the state machine implementation is to store any
412              server data it  needs.  The  difference  between  this  and  the
413              state()  itself  is  that  a  change in this data does not cause
414              postponed events to be retried. Hence, if a change in this  data
415              would  change the set of events that are handled, then that data
416              item is to be made a part of the state.
417
418       event_type() =
419           external_event_type() | timeout_event_type() | internal
420
421              There are 3 categories of events: external, timeout, and  inter‐
422              nal.
423
424              internal  events  can  only  be  generated  by the state machine
425              itself through the transition action next_event.
426
427       external_event_type() = {call, From :: from()} | cast | info
428
429              External events are of 3  types:  {call,From},  cast,  or  info.
430              Calls  (synchronous)  and casts originate from the corresponding
431              API functions. For calls, the event contains whom to  reply  to.
432              Type  info  originates from regular process messages sent to the
433              gen_statem.
434
435       timeout_event_type() =
436           timeout | {timeout, Name :: term()} | state_timeout
437
438              There are 3 types of time-out events that the state machine  can
439              generate for itself with the corresponding timeout_action()s.
440
441       callback_mode_result() =
442           callback_mode() | [callback_mode() | state_enter()]
443
444              This  is the return type from Module:callback_mode/0 and selects
445              callback mode and whether to do state enter calls, or not.
446
447       callback_mode() = state_functions | handle_event_function
448
449              The callback mode is selected with the return  value  from  Mod‐
450              ule:callback_mode/0:
451
452                state_functions:
453                  The  state  must  be  of  type state_name() and one callback
454                  function per state, that is, Module:StateName/3, is used.
455
456                handle_event_function:
457                  The state can be any term and  the  callback  function  Mod‐
458                  ule:handle_event/4 is used for all states.
459
460              The  function Module:callback_mode/0 is called when starting the
461              gen_statem, after code change and after  changing  the  callback
462              module   with   any   of   the  actions  change_callback_module,
463              push_callback_module  or  pop_callback_module.  The  result   is
464              cached for subsequent calls to state callbacks.
465
466       state_enter() = state_enter
467
468              Whether the state machine should use state enter calls or not is
469              selected when starting the  gen_statem  and  after  code  change
470              using the return value from Module:callback_mode/0.
471
472              If Module:callback_mode/0 returns a list containing state_enter,
473              the gen_statem engine will, at  every  state  change,  call  the
474              state callback with arguments (enter, OldState, Data) or (enter,
475              OldState, State, Data), depending on the callback mode. This may
476              look like an event but is really a call performed after the pre‐
477              vious state callback returned and before any event is  delivered
478              to  the  new  state  callback.  See  Module:StateName/3 and Mod‐
479              ule:handle_event/4. Such a call can be repeated by  returning  a
480              repeat_state or repeat_state_and_data tuple from the state call‐
481              back.
482
483              If Module:callback_mode/0 does not return such a list, no  state
484              enter calls are done.
485
486              If  Module:code_change/4  should  transform  the  state,  it  is
487              regarded as a state rename and not a state  change,  which  will
488              not cause a state enter call.
489
490              Note  that a state enter call will be done right before entering
491              the initial state even though  this  actually  is  not  a  state
492              change. In this case OldState =:= State, which cannot happen for
493              a subsequent state change, but will happen  when  repeating  the
494              state enter call.
495
496       transition_option() =
497           postpone() |
498           hibernate() |
499           event_timeout() |
500           generic_timeout() |
501           state_timeout()
502
503              Transition  options  can  be set by actions and modify the state
504              transition. The state transition  takes  place  when  the  state
505              callback  has  processed  an  event  and  returns.  Here are the
506              sequence of steps for a state transition:
507
508                * All returned actions are processed in order  of  appearance.
509                  In this step all replies generated by any reply_action() are
510                  sent. Other actions set transition_option()s that come  into
511                  play in subsequent steps.
512
513                * If  state enter calls are used, and either it is the initial
514                  state or one of the callback  results  repeat_state_and_data
515                  or repeat_state_and_data is used the gen_statem engine calls
516                  the current state callback  with  arguments  (enter,  State,
517                  Data)  or (enter, State, State, Data) (depending on callback
518                  mode) and when it returns starts again from the top of  this
519                  sequence.
520
521                  If  state  enter  calls  are used, and the state changes the
522                  gen_statem engine calls the new state  callback  with  argu‐
523                  ments  (enter,  OldState,  Data) or (enter, OldState, State,
524                  Data) (depending on  callback  mode)  and  when  it  returns
525                  starts again from the top of this sequence.
526
527                * If postpone() is true, the current event is postponed.
528
529                * If  this  is a state change, the queue of incoming events is
530                  reset to start with the oldest postponed.
531
532                * All events stored with action() next_event are  inserted  to
533                  be processed before previously queued events.
534
535                * Time-out   timers   event_timeout(),  generic_timeout()  and
536                  state_timeout() are handled. Time-outs with  zero  time  are
537                  guaranteed  to  be delivered to the state machine before any
538                  external not yet received event so if there is such a  time-
539                  out  requested,  the  corresponding  time-out  zero event is
540                  enqueued as the newest received event; that is after already
541                  queued events such as inserted and postponed events.
542
543                  Any  event  cancels  an event_timeout() so a zero time event
544                  time-out is only generated if the event queue is empty.
545
546                  A state change cancels a state_timeout() and any new transi‐
547                  tion  option of this type belongs to the new state, that is;
548                  a state_timeout() applies to the  state  the  state  machine
549                  enters.
550
551                * If there are enqueued events the state callback for the pos‐
552                  sibly new state is called with the  oldest  enqueued  event,
553                  and we start again from the top of this sequence.
554
555                * Otherwise  the  gen_statem  goes into receive or hibernation
556                  (if hibernate() is true) to wait for the  next  message.  In
557                  hibernation   the   next   non-system   event   awakens  the
558                  gen_statem, or rather the next incoming message awakens  the
559                  gen_statem,  but  if it is a system event it goes right back
560                  into hibernation. When a new message arrives the state call‐
561                  back  is  called  with the corresponding event, and we start
562                  again from the top of this sequence.
563
564       postpone() = boolean()
565
566              If true, postpones the current event  and  retries  it  after  a
567              state change (NextState =/= State).
568
569       hibernate() = boolean()
570
571              If  true,  hibernates  the gen_statem by calling proc_lib:hiber‐
572              nate/3 before going into receive to  wait  for  a  new  external
573              event.
574
575          Note:
576              If  there  are  enqueued  events  to  process when hibrnation is
577              requested, this is optimized  by  not  hibernating  but  instead
578              calling erlang:garbage_collect/0 to simulate that the gen_statem
579              entered hibernation and immediately got awakened by an  enqueued
580              event.
581
582
583       event_timeout() = timeout() | integer()
584
585              Starts  a  timer  set  by enter_action() timeout. When the timer
586              expires an event of event_type() timeout will be generated.  See
587              erlang:start_timer/4  for  how Time and Options are interpreted.
588              Future erlang:start_timer/4 Options will not necessarily be sup‐
589              ported.
590
591              Any  event  that  arrives  cancels  this  time-out.  Note that a
592              retried or inserted event counts as arrived.  So  does  a  state
593              time-out zero event, if it was generated before this time-out is
594              requested.
595
596              If Time is infinity, no timer is  started,  as  it  never  would
597              expire anyway.
598
599              If  Time is relative and 0 no timer is actually started, instead
600              the the time-out event is enqueued to ensure that it  gets  pro‐
601              cessed  before  any  not  yet received external event, but after
602              already queued events.
603
604              Note that it is not possible nor needed to cancel this time-out,
605              as it is cancelled automatically by any other event.
606
607       generic_timeout() = timeout() | integer()
608
609              Starts  a  timer  set by enter_action() {timeout,Name}. When the
610              timer expires an event of event_type()  {timeout,Name}  will  be
611              generated. See erlang:start_timer/4 for how Time and Options are
612              interpreted. Future erlang:start_timer/4 Options will not neces‐
613              sarily be supported.
614
615              If  Time  is  infinity,  no  timer is started, as it never would
616              expire anyway.
617
618              If Time is relative and 0 no timer is actually started,  instead
619              the  the  time-out event is enqueued to ensure that it gets pro‐
620              cessed before any not yet received external event.
621
622              Setting a timer with the same Name  while  it  is  running  will
623              restart it with the new time-out value. Therefore it is possible
624              to cancel a specific time-out by setting it to infinity.
625
626       state_timeout() = timeout() | integer()
627
628              Starts a timer set by  enter_action()  state_timeout.  When  the
629              timer  expires  an  event  of event_type() state_timeout will be
630              generated. See erlang:start_timer/4 for how Time and Options are
631              interpreted. Future erlang:start_timer/4 Options will not neces‐
632              sarily be supported.
633
634              If Time is infinity, no timer is  started,  as  it  never  would
635              expire anyway.
636
637              If  Time is relative and 0 no timer is actually started, instead
638              the the time-out event is enqueued to ensure that it  gets  pro‐
639              cessed before any not yet received external event.
640
641              Setting  this timer while it is running will restart it with the
642              new time-out value. Therefore it  is  possible  to  cancel  this
643              time-out by setting it to infinity.
644
645       timeout_option() = {abs, Abs :: boolean()}
646
647              If  Abs is true an absolute timer is started, and if it is false
648              a relative, which is the default. See  erlang:start_timer/4  for
649              details.
650
651       action() =
652           postpone |
653           {postpone, Postpone :: postpone()} |
654           {next_event,
655            EventType :: event_type(),
656            EventContent :: term()} |
657           {change_callback_module, NewModule :: module()} |
658           {push_callback_module, NewModule :: module()} |
659           pop_callback_module |
660           enter_action()
661
662              These  transition  actions can be invoked by returning them from
663              the state callback when it is called with an  event,  from  Mod‐
664              ule:init/1 or by giving them to enter_loop/5,6.
665
666              Actions are executed in the containing list order.
667
668              Actions  that  set  transition options  override any previous of
669              the same type, so the last in  the  containing  list  wins.  For
670              example,  the  last postpone() overrides any previous postpone()
671              in the list.
672
673                postpone:
674                  Sets the transition_option() postpone() for this state tran‐
675                  sition.  This  action  is  ignored  when  returned from Mod‐
676                  ule:init/1 or given to enter_loop/5,6, as there is no  event
677                  to postpone in those cases.
678
679                next_event:
680                  This action does not set any transition_option() but instead
681                  stores the specified EventType and EventContent  for  inser‐
682                  tion after all actions have been executed.
683
684                  The  stored  events are inserted in the queue as the next to
685                  process before any already queued events. The order of these
686                  stored  events  is preserved, so the first next_event in the
687                  containing list becomes the first to process.
688
689                  An event of type internal is to be used  when  you  want  to
690                  reliably  distinguish  an  event  inserted this way from any
691                  external event.
692
693                change_callback_module:
694                  Changes the callback module to NewModule which will be  used
695                  when calling all subsequent state callbacks.
696
697                  The  gen_statem  engine  will  find out the callback mode of
698                  NewModule by calling  NewModule:callback_mode/0  before  the
699                  next state callback.
700
701                  Changing the callback module does not affect the state tran‐
702                  sition in any way, it only changes which module that handles
703                  the events. Be aware that all relevant callback functions in
704                  NewModule   such   as   the    state    callback,    NewMod‐
705                  ule:code_change/4,   NewModule:format_status/2  and  NewMod‐
706                  ule:terminate/3 must be able to handle the  state  and  data
707                  from the old module.
708
709                push_callback_module
710                  : Pushes the current callback module to the top of an inter‐
711                  nal stack of callback modules and changes the callback  mod‐
712                  ule  to  NewModule.  Otherwise like {change_callback_module,
713                  NewModule} above.
714
715                pop_callback_module:
716                   Pops the top module from the  internal  stack  of  callback
717                  modules  and  changes  the  callback module to be the popped
718                  module. If the stack is empty the  server  fails.  Otherwise
719                  like {change_callback_module, NewModule} above.
720
721       enter_action() =
722           hibernate |
723           {hibernate, Hibernate :: hibernate()} |
724           timeout_action() |
725           reply_action()
726
727              These  transition  actions can be invoked by returning them from
728              the state callback, from Module:init/1  or  by  giving  them  to
729              enter_loop/5,6.
730
731              Actions are executed in the containing list order.
732
733              Actions that set transition options override any previous of the
734              same type, so the last in the containing list wins. For example,
735              the  last event_timeout() overrides any previous event_timeout()
736              in the list.
737
738                hibernate:
739                  Sets the  transition_option()  hibernate()  for  this  state
740                  transition.
741
742       timeout_action() =
743           (Time :: event_timeout()) |
744           {timeout, Time :: event_timeout(), EventContent :: term()} |
745           {timeout,
746            Time :: event_timeout(),
747            EventContent :: term(),
748            Options :: timeout_option() | [timeout_option()]} |
749           {{timeout, Name :: term()},
750            Time :: generic_timeout(),
751            EventContent :: term()} |
752           {{timeout, Name :: term()},
753            Time :: generic_timeout(),
754            EventContent :: term(),
755            Options :: timeout_option() | [timeout_option()]} |
756           {state_timeout,
757            Time :: state_timeout(),
758            EventContent :: term()} |
759           {state_timeout,
760            Time :: state_timeout(),
761            EventContent :: term(),
762            Options :: timeout_option() | [timeout_option()]} |
763           timeout_cancel_action() |
764           timeout_update_action()
765
766              These  transition  actions can be invoked by returning them from
767              the state callback, from Module:init/1  or  by  giving  them  to
768              enter_loop/5,6.
769
770              These time-out actions sets time-out transition options.
771
772                Time:
773                  Short for {timeout,Time,Time}, that is, the time-out message
774                  is the time-out time. This form exists  to  make  the  state
775                  callback  return  value  {next_state,NextState,NewData,Time}
776                  allowed like for gen_fsm.
777
778                timeout:
779                  Sets the transition_option() event_timeout()  to  Time  with
780                  EventContent and time-out options Options.
781
782                {timeout,Name}:
783                  Sets  the  transition_option() generic_timeout() to Time for
784                  Name with EventContent and time-out options Options.
785
786                state_timeout:
787                  Sets the transition_option() state_timeout()  to  Time  with
788                  EventContent and time-out options Options.
789
790       timeout_cancel_action() =
791           {timeout, cancel} |
792           {{timeout, Name :: term()}, cancel} |
793           {state_timeout, cancel}
794
795              This  is  a  shorter and clearer form of  timeout_action()  with
796              Time = infinity which cancels a time-out.
797
798       timeout_update_action() =
799           {timeout, update, EventContent :: term()} |
800           {{timeout, Name :: term()}, update, EventContent :: term()} |
801           {state_timeout, update, EventContent :: term()}
802
803              Updates  a  time-out  with  a  new  EventContent.   See    time‐
804              out_action()  for how to start a time-out.
805
806              If  no  time-out  of  the same type is active instead insert the
807              time-out event just like when starting a time-out with  relative
808              Time = 0.
809
810       reply_action() = {reply, From :: from(), Reply :: term()}
811
812              This  transition  action can be invoked by returning it from the
813              state  callback,  from  Module:init/1  or  by   giving   it   to
814              enter_loop/5,6.
815
816              It does not set any transition_option() but instead replies to a
817              caller waiting for a reply in call/2. From must be the term from
818              argument {call,From} in a call to a state callback.
819
820              Note that using this action from Module:init/1 or enter_loop/5,6
821              would be weird on the border of witchcraft since there has  been
822              no earlier call to a state callback in this server.
823
824       init_result(StateType) =
825           {ok, State :: StateType, Data :: data()} |
826           {ok,
827            State :: StateType,
828            Data :: data(),
829            Actions :: [action()] | action()} |
830           ignore |
831           {stop, Reason :: term()}
832
833              For a succesful initialization, State is the initial state() and
834              Data the initial server data() of the gen_statem.
835
836              The Actions are executed when entering the first state  just  as
837              for  a state callback, except that the action postpone is forced
838              to false since there is no event to postpone.
839
840              For  an  unsuccesful  initialization,  {stop,Reason}  or  ignore
841              should be used; see start_link/3,4.
842
843       state_enter_result(State) =
844           {next_state, State, NewData :: data()} |
845           {next_state, State,
846            NewData :: data(),
847            Actions :: [enter_action()] | enter_action()} |
848           state_callback_result(enter_action())
849
850              State  is  the  current state and it cannot be changed since the
851              state callback was called with a state enter call.
852
853                next_state:
854                  The gen_statem does a state transition to State,  which  has
855                  to  be  the  current  state,  sets NewData, and executes all
856                  Actions.
857
858       event_handler_result(StateType) =
859           {next_state, NextState :: StateType, NewData :: data()} |
860           {next_state,
861            NextState :: StateType,
862            NewData :: data(),
863            Actions :: [action()] | action()} |
864           state_callback_result(action())
865
866              StateType is state_name() if callback mode  is  state_functions,
867              or state() if callback mode is handle_event_function.
868
869                next_state:
870                  The  gen_statem  does a state transition to NextState (which
871                  can be the same as the current  state),  sets  NewData,  and
872                  executes  all  Actions.  If  NextState  =/= CurrentState the
873                  state transition is a state change.
874
875       state_callback_result(ActionType) =
876           {keep_state, NewData :: data()} |
877           {keep_state,
878            NewData :: data(),
879            Actions :: [ActionType] | ActionType} |
880           keep_state_and_data |
881           {keep_state_and_data, Actions :: [ActionType] | ActionType} |
882           {repeat_state, NewData :: data()} |
883           {repeat_state,
884            NewData :: data(),
885            Actions :: [ActionType] | ActionType} |
886           repeat_state_and_data |
887           {repeat_state_and_data, Actions :: [ActionType] | ActionType} |
888           stop |
889           {stop, Reason :: term()} |
890           {stop, Reason :: term(), NewData :: data()} |
891           {stop_and_reply,
892            Reason :: term(),
893            Replies :: [reply_action()] | reply_action()} |
894           {stop_and_reply,
895            Reason :: term(),
896            Replies :: [reply_action()] | reply_action(),
897            NewData :: data()}
898
899              ActionType is enter_action() if the state  callback  was  called
900              with  a  state enter call and action() if the state callback was
901              called with an event.
902
903                keep_state:
904                  The same as {next_state,CurrentState,NewData,Actions}.
905
906                keep_state_and_data:
907                  The same as {keep_state,CurrentData,Actions}.
908
909                repeat_state:
910                  If the gen_statem runs with state  enter  calls,  the  state
911                  enter  call is repeated, see type transition_option(), other
912                  than that repeat_state is the same as keep_state.
913
914                repeat_state_and_data:
915                  The same as {repeat_state,CurrentData,Actions}.
916
917                stop:
918                  Terminates the gen_statem by calling Module:terminate/3 with
919                  Reason and NewData, if specified.
920
921                stop_and_reply:
922                  Sends all Replies, then terminates the gen_statem by calling
923                  Module:terminate/3 with Reason and NewData, if specified.
924
925              All these terms are tuples or atoms and this property will  hold
926              in any future version of gen_statem.
927

EXPORTS

929       call(ServerRef :: server_ref(), Request :: term()) ->
930               Reply :: term()
931
932       call(ServerRef :: server_ref(),
933            Request :: term(),
934            Timeout ::
935                timeout() |
936                {clean_timeout, T :: timeout()} |
937                {dirty_timeout, T :: timeout()}) ->
938               Reply :: term()
939
940              Makes  a synchronous call to the gen_statem ServerRef by sending
941              a request and waiting until its reply  arrives.  The  gen_statem
942              calls the state callback with event_type() {call,From} and event
943              content Request.
944
945              A  Reply  is  generated  when  a  state  callback  returns  with
946              {reply,From,Reply}  as  one action(), and that Reply becomes the
947              return value of this function.
948
949              Timeout is an integer > 0, which specifies how many milliseconds
950              to  wait for a reply, or the atom infinity to wait indefinitely,
951              which is the default. If no reply is received within the  speci‐
952              fied time, the function call fails.
953
954          Note:
955              For  Timeout  <  infinity,  to avoid getting a late reply in the
956              caller's inbox if the caller should catch exceptions, this func‐
957              tion  spawns  a  proxy  process that does the call. A late reply
958              gets delivered to the dead proxy process, hence gets  discarded.
959              This is less efficient than using Timeout == infinity.
960
961
962              Timeout  can  also  be a tuple {clean_timeout,T} or {dirty_time‐
963              out,T}, where T is the time-out  time.  {clean_timeout,T}  works
964              like just T described in the note above and uses a proxy process
965              while {dirty_timeout,T} bypasses the proxy process which is more
966              lightweight.
967
968          Note:
969              If  you  combine  catching  exceptions  from  this function with
970              {dirty_timeout,T} to avoid that the calling  process  dies  when
971              the  call  times  out,  you will have to be prepared to handle a
972              late reply. Note that there is an odd chance to get a late reply
973              even  with  {dirty_timeout,infinity}  or infinity for example in
974              the event of network problems. So why not just let  the  calling
975              process die by not catching the exception?
976
977
978              The  call  can  also  fail,  for example, if the gen_statem dies
979              before or during this function call.
980
981       cast(ServerRef :: server_ref(), Msg :: term()) -> ok
982
983              Sends an asynchronous event  to  the  gen_statem  ServerRef  and
984              returns  ok  immediately,  ignoring  if  the destination node or
985              gen_statem does not exist. The gen_statem calls the state  call‐
986              back with event_type() cast and event content Msg.
987
988       enter_loop(Module :: module(),
989                  Opts :: [enter_loop_opt()],
990                  State :: state(),
991                  Data :: data()) ->
992                     no_return()
993
994              The  same  as  enter_loop/6  with  Actions  =  [] except that no
995              server_name() must have been registered. This creates an  anony‐
996              mous server.
997
998       enter_loop(Module :: module(),
999                  Opts :: [enter_loop_opt()],
1000                  State :: state(),
1001                  Data :: data(),
1002                  Server_or_Actions :: server_name() | pid() | [action()]) ->
1003                     no_return()
1004
1005              If  Server_or_Actions  is  a  list(),  the  same as enter_loop/6
1006              except that no  server_name()  must  have  been  registered  and
1007              Actions = Server_or_Actions. This creates an anonymous server.
1008
1009              Otherwise    the    same   as   enter_loop/6   with   Server   =
1010              Server_or_Actions and Actions = [].
1011
1012       enter_loop(Module :: module(),
1013                  Opts :: [enter_loop_opt()],
1014                  State :: state(),
1015                  Data :: data(),
1016                  Server :: server_name() | pid(),
1017                  Actions :: [action()] | action()) ->
1018                     no_return()
1019
1020              Makes the calling process become a gen_statem. Does not  return,
1021              instead  the  calling process enters the gen_statem receive loop
1022              and becomes a gen_statem server.  The  process  must  have  been
1023              started  using  one of the start functions in proc_lib. The user
1024              is responsible for any initialization of the process,  including
1025              registering a name for it.
1026
1027              This  function is useful when a more complex initialization pro‐
1028              cedure is needed than the gen_statem behavior provides.
1029
1030              Module,  Opts  have   the   same   meaning   as   when   calling
1031              start[_link]/3,4.
1032
1033              If  Server is self() an anonymous server is created just as when
1034              using start[_link]/3. If  Server  is  a  server_name()  a  named
1035              server  is  created  just as when using start[_link]/4. However,
1036              the server_name() name must  have  been  registered  accordingly
1037              before this function is called.
1038
1039              State, Data, and Actions have the same meanings as in the return
1040              value of Module:init/1. Also, the callback module does not  need
1041              to export a Module:init/1 function.
1042
1043              The  function  fails if the calling process was not started by a
1044              proc_lib start function, or if it is not registered according to
1045              server_name().
1046
1047       reply(Replies :: [reply_action()] | reply_action()) -> ok
1048
1049       reply(From :: from(), Reply :: term()) -> ok
1050
1051              This  function  can be used by a gen_statem to explicitly send a
1052              reply to a process that waits in call/2 when the reply cannot be
1053              defined in the return value of a state callback.
1054
1055              From  must  be  the  term from argument {call,From} to the state
1056              callback. A reply or multiple replies canalso be sent using  one
1057              or several reply_action()s from a state callback.
1058
1059          Note:
1060              A reply sent with this function is not visible in sys debug out‐
1061              put.
1062
1063
1064       start(Module :: module(), Args :: term(), Opts :: [start_opt()]) ->
1065                start_ret()
1066
1067       start(ServerName :: server_name(),
1068             Module :: module(),
1069             Args :: term(),
1070             Opts :: [start_opt()]) ->
1071                start_ret()
1072
1073              Creates a standalone gen_statem process according to OTP  design
1074              principles  (using  proc_lib  primitives).  As  it  does not get
1075              linked to the calling process, this  start  function  cannot  be
1076              used by a supervisor to start a child.
1077
1078              For   a   description   of  arguments  and  return  values,  see
1079              start_link/3,4.
1080
1081       start_link(Module :: module(),
1082                  Args :: term(),
1083                  Opts :: [start_opt()]) ->
1084                     start_ret()
1085
1086       start_link(ServerName :: server_name(),
1087                  Module :: module(),
1088                  Args :: term(),
1089                  Opts :: [start_opt()]) ->
1090                     start_ret()
1091
1092              Creates a gen_statem process according to OTP design  principles
1093              (using  proc_lib  primitives)  that  is  linked  to  the calling
1094              process. This is essential when the gen_statem must be part of a
1095              supervision tree so it gets linked to its supervisor.
1096
1097              The  gen_statem  process  calls  Module:init/1 to initialize the
1098              server.   To   ensure   a   synchronized   startup    procedure,
1099              start_link/3,4 does not return until Module:init/1 has returned.
1100
1101              ServerName  specifies  the  server_name()  to  register  for the
1102              gen_statem. If the gen_statem is started with  start_link/3,  no
1103              ServerName is provided and the gen_statem is not registered.
1104
1105              Module is the name of the callback module.
1106
1107              Args is an arbitrary term that is passed as the argument to Mod‐
1108              ule:init/1.
1109
1110                * If option {timeout,Time} is present in Opts, the  gen_statem
1111                  is  allowed  to  spend  Time milliseconds initializing or it
1112                  terminates and the start function returns {error,timeout}.
1113
1114                * If   option    {hibernate_after,HibernateAfterTimeout}    is
1115                  present,  the  gen_statem  process  awaits  any  message for
1116                  HibernateAfterTimeout milliseconds  and  if  no  message  is
1117                  received,  the  process  goes into hibernation automatically
1118                  (by calling proc_lib:hibernate/3).
1119
1120                * If option {debug,Dbgs} is present in Opts, debugging through
1121                  sys is activated.
1122
1123                * If   option   {spawn_opt,SpawnOpts}   is  present  in  Opts,
1124                  SpawnOpts is passed as option  list  to  erlang:spawn_opt/2,
1125                  which is used to spawn the gen_statem process.
1126
1127          Note:
1128              Using  spawn option monitor is not allowed, it causes this func‐
1129              tion to fail with reason badarg.
1130
1131
1132              If the gen_statem is successfully created and initialized,  this
1133              function  returns  {ok,Pid},  where  Pid  is  the  pid()  of the
1134              gen_statem. If a process with the  specified  ServerName  exists
1135              already,  this  function  returns {error,{already_started,Pid}},
1136              where Pid is the pid() of that process.
1137
1138              If  Module:init/1  fails  with  Reason,  this  function  returns
1139              {error,Reason}.   If   Module:init/1  returns  {stop,Reason}  or
1140              ignore, the process is  terminated  and  this  function  returns
1141              {error,Reason} or ignore, respectively.
1142
1143       stop(ServerRef :: server_ref()) -> ok
1144
1145              The same as stop(ServerRef, normal, infinity).
1146
1147       stop(ServerRef :: server_ref(),
1148            Reason :: term(),
1149            Timeout :: timeout()) ->
1150               ok
1151
1152              Orders  the gen_statem ServerRef to exit with the specified Rea‐
1153              son and waits for it to terminate.  The  gen_statem  calls  Mod‐
1154              ule:terminate/3 before exiting.
1155
1156              This  function  returns  ok  if  the  server terminates with the
1157              expected reason. Any other  reason  than  normal,  shutdown,  or
1158              {shutdown,Term} causes an error report to be issued through log‐
1159              ger(3). The default Reason is normal.
1160
1161              Timeout is an integer > 0, which specifies how many milliseconds
1162              to  wait  for  the  server to terminate, or the atom infinity to
1163              wait indefinitely. Defaults to infinity. If the server does  not
1164              terminate  within  the  specified  time,  a timeout exception is
1165              raised.
1166
1167              If the process does not exist, a noproc exception is raised.
1168

CALLBACK FUNCTIONS

1170       The following functions are to be exported from a  gen_statem  callback
1171       module.
1172

EXPORTS

1174       Module:callback_mode() -> CallbackMode
1175
1176              Types:
1177
1178                  CallbackMode   =   callback_mode()  |  [  callback_mode()  |
1179                 state_enter() ]
1180
1181              This function is called by a gen_statem when it  needs  to  find
1182              out  the  callback  mode  of  the  callback module. The value is
1183              cached by gen_statem for efficiency reasons, so this function is
1184              only  called  once  after  server  start, after code change, and
1185              after changing the callback module, but before the  first  state
1186              callback  in  the  current  callback  module's  code  version is
1187              called. More occasions  may  be  added  in  future  versions  of
1188              gen_statem.
1189
1190              Server  start  happens either when Module:init/1 returns or when
1191              enter_loop/4-6  is  called.  Code  change  happens   when   Mod‐
1192              ule:code_change/4  returns. A change of the callback module hap‐
1193              pens  when  a  state  callback  returns  any  of   the   actions
1194              change_callback_module,    push_callback_module   or   pop_call‐
1195              back_module.
1196
1197              The CallbackMode is either just callback_mode() or a  list  con‐
1198              taining callback_mode() and possibly the atom state_enter.
1199
1200          Note:
1201              If this function's body does not return an inline constant value
1202              the callback module is doing something strange.
1203
1204
1205       Module:code_change(OldVsn, OldState, OldData, Extra) -> Result
1206
1207              Types:
1208
1209                 OldVsn = Vsn | {down,Vsn}
1210                  Vsn = term()
1211                 OldState = NewState = term()
1212                 Extra = term()
1213                 Result = {ok,NewState,NewData} | Reason
1214                  OldState = NewState = state()
1215                  OldData = NewData = data()
1216                 Reason = term()
1217
1218          Note:
1219              This callback is optional, so callback modules need  not  export
1220              it.    If    a   release   upgrade/downgrade   with   Change   =
1221              {advanced,Extra} specified in  the  .appup  file  is  made  when
1222              code_change/4  is  not  implemented  the process will crash with
1223              exit reason undef.
1224
1225
1226              This function is called by a gen_statem when it is to update its
1227              internal state during a release upgrade/downgrade, that is, when
1228              the  instruction  {update,Module,Change,...},  where  Change   =
1229              {advanced,Extra},  is  specified  in  the  appup  file. For more
1230              information, see OTP Design Principles.
1231
1232              For an upgrade, OldVsn is Vsn, and for a  downgrade,  OldVsn  is
1233              {down,Vsn}.  Vsn  is  defined by the vsn attribute(s) of the old
1234              version of the callback module Module. If no such  attribute  is
1235              defined, the version is the checksum of the Beam file.
1236
1237              OldState and OldData is the internal state of the gen_statem.
1238
1239              Extra  is  passed  "as is" from the {advanced,Extra} part of the
1240              update instruction.
1241
1242              If successful, the function must  return  the  updated  internal
1243              state in an {ok,NewState,NewData} tuple.
1244
1245              If  the  function  returns a failure Reason, the ongoing upgrade
1246              fails and rolls back to the old release. Note that Reason cannot
1247              be  an  {ok,_,_} tuple since that will be regarded as a {ok,New‐
1248              State,NewData} tuple, and that a tuple  matching  {ok,_}  is  an
1249              also invalid failure Reason. It is recommended to use an atom as
1250              Reason since it will be wrapped in an {error,Reason} tuple.
1251
1252              Also note when upgrading a gen_statem, this function  and  hence
1253              the Change = {advanced,Extra} parameter in the appup file is not
1254              only needed to update the internal state or to act on the  Extra
1255              argument.  It  is  also needed if an upgrade or downgrade should
1256              change callback mode, or else the callback mode after  the  code
1257              change  will  not  be  honoured,  most probably causing a server
1258              crash.
1259
1260              If the server changes callback module using any of  the  actions
1261              change_callback_module,    push_callback_module   or   pop_call‐
1262              back_module, be aware that it is  always  the  current  callback
1263              module  that will get this callback call. That the current call‐
1264              back module handles the current state and data update should  be
1265              no  surprise,  but  it  must be able to handle even parts of the
1266              state and data that it is not familiar with, somehow.
1267
1268              In the supervisor child specification there is a list of modules
1269              which  is recommended to contain only the callback module. For a
1270              gen_statem with multiple callback modules there is no real  need
1271              to  list all of them, it may not even be possible since the list
1272              could change after code upgrade. If this list would contain only
1273              the  start callback module, as recommended, what is important is
1274              to upgrade that module whenever a synchronized code  replacement
1275              is done. Then the release handler concludes that an upgrade that
1276              upgrades that module needs to suspend, code change,  and  resume
1277              any  server  whose child specification declares that it is using
1278              that module. And again; the current callback module will get the
1279              Module:code_change/4 call.
1280
1281       Module:init(Args) -> Result(StateType)
1282
1283              Types:
1284
1285                 Args = term()
1286                  Result(StateType) = init_result(StateType)
1287
1288              Whenever   a  gen_statem  is  started  using  start_link/3,4  or
1289              start/3,4, this function is called by the new  process  to  ini‐
1290              tialize the implementation state and server data.
1291
1292              Args is the Args argument provided to that start function.
1293
1294          Note:
1295              Note  that  if  the  gen_statem  is started through proc_lib and
1296              enter_loop/4-6, this callback will never be called.  Since  this
1297              callback is not optional it can in that case be implemented as:
1298
1299              init(Args) -> erlang:error(not_implemented, [Args]).
1300
1301
1302       Module:format_status(Opt, [PDict,State,Data]) -> Status
1303
1304              Types:
1305
1306                 Opt = normal | terminate
1307                 PDict = [{Key, Value}]
1308                  State = state()
1309                  Data = data()
1310                 Key = term()
1311                 Value = term()
1312                 Status = term()
1313
1314          Note:
1315              This callback is optional, so a callback module does not need to
1316              export it. The gen_statem module provides a default  implementa‐
1317              tion of this function that returns {State,Data}.
1318
1319              If  this callback is exported but fails, to hide possibly sensi‐
1320              tive  data,   the   default   function   will   instead   return
1321              {State,Info},  where  Info  says  nothing but the fact that for‐
1322              mat_status/2 has crashed.
1323
1324
1325              This function is called by a gen_statem process when any of  the
1326              following apply:
1327
1328                *
1329                   One  of sys:get_status/1,2 is invoked to get the gen_statem
1330                  status. Opt is set to the atom normal for this case.
1331
1332                *
1333                   The gen_statem terminates abnormally and logs an error. Opt
1334                  is set to the atom terminate for this case.
1335
1336              This  function is useful for changing the form and appearance of
1337              the gen_statem status for these cases. A callback module wishing
1338              to change the sys:get_status/1,2 return value and how its status
1339              appears in termination error logs exports an  instance  of  for‐
1340              mat_status/2, which returns a term describing the current status
1341              of the gen_statem.
1342
1343              PDict is the current value of  the  process  dictionary  of  the
1344              gen_statem.
1345
1346              State is the internal state of the gen_statem.
1347
1348              Data is the internal server data of the gen_statem.
1349
1350              The  function  is  to  return  Status,  a term that contains the
1351              appropriate details of the  current  state  and  status  of  the
1352              gen_statem.  There  are  no  restrictions on the form Status can
1353              take, but for the sys:get_status/1,2 case (when Opt is  normal),
1354              the  recommended form for the Status value is [{data, [{"State",
1355              Term}]}], where Term provides relevant details of the gen_statem
1356              state.  Following  this  recommendation  is not required, but it
1357              makes the callback module status consistent with the rest of the
1358              sys:get_status/1,2 return value.
1359
1360              One use for this function is to return compact alternative state
1361              representations to avoid having large state terms printed in log
1362              files.  Another use is to hide sensitive data from being written
1363              to the error log.
1364
1365       Module:StateName(enter, OldState, Data) -> StateEnterResult(StateName)
1366       Module:StateName(EventType, EventContent, Data) -> StateFunctionResult
1367       Module:handle_event(enter,  OldState,  State,  Data)  ->  StateEnterRe‐
1368       sult(State)
1369       Module:handle_event(EventType,   EventContent,  State,  Data)  ->  Han‐
1370       dleEventResult
1371
1372              Types:
1373
1374                  EventType = event_type()
1375                 EventContent = term()
1376                  State = state()
1377                  Data = NewData = data()
1378                  StateEnterResult(StateName) = state_enter_result(StateName)
1379                  StateFunctionResult = event_handler_result(state_name())
1380                  StateEnterResult(State) = state_enter_result(State)
1381                  HandleEventResult = event_handler_result(state())
1382
1383              Whenever a gen_statem receives an event from call/2, cast/2,  or
1384              as  a  normal process message, one of these functions is called.
1385              If  callback  mode  is  state_functions,  Module:StateName/3  is
1386              called,   and   if   it  is  handle_event_function,  Module:han‐
1387              dle_event/4 is called.
1388
1389              If EventType is {call,From}, the caller waits for a  reply.  The
1390              reply  can be sent from this or from any other state callback by
1391              returning with {reply,From,Reply} in Actions, in Replies, or  by
1392              calling reply(From, Reply).
1393
1394              If  this  function returns with a next state that does not match
1395              equal (=/=) to the  current  state,  all  postponed  events  are
1396              retried in the next state.
1397
1398              The  only difference between StateFunctionResult and HandleEven‐
1399              tResult is that for StateFunctionResult the next state  must  be
1400              an  atom,  but  for HandleEventResult there is no restriction on
1401              the next state.
1402
1403              For options that can be set and actions  that  can  be  done  by
1404              gen_statem after returning from this function, see action().
1405
1406              When the gen_statem runs with state enter calls, these functions
1407              are also called with arguments  (enter,  OldState,  ...)  during
1408              every  state change. In this case there are some restrictions on
1409              the actions that may be  returned:  postpone()  is  not  allowed
1410              since a state enter call is not an event so there is no event to
1411              postpone, and {next_event,_,_} is not allowed since using  state
1412              enter  calls  should not affect how events are consumed and pro‐
1413              duced. You may also not change states from this call. Should you
1414              return  {next_state,NextState, ...} with NextState =/= State the
1415              gen_statem crashes. Note that it  is  actually  allowed  to  use
1416              {repeat_state,  NewData,  ...}  although  it  makes little sense
1417              since you immediately will be called  again  with  a  new  state
1418              enter  call  making  this just a weird way of looping, and there
1419              are better ways to loop in Erlang. If you do not update  NewData
1420              and  have  some  loop  termination  condition,  or  if  you  use
1421              {repeat_state_and_data, _} or repeat_state_and_data you have  an
1422              infinite   loop!   You  are  advised  to  use  {keep_state,...},
1423              {keep_state_and_data,_} or  keep_state_and_data  since  changing
1424              states from a state enter call is not possible anyway.
1425
1426              Note the fact that you can use throw to return the result, which
1427              can   be   useful.   For    example    to    bail    out    with
1428              throw(keep_state_and_data)  from  deep  within complex code that
1429              cannot return {next_state,State,Data} because State or  Data  is
1430              no longer in scope.
1431
1432       Module:terminate(Reason, State, Data) -> Ignored
1433
1434              Types:
1435
1436                 Reason = normal | shutdown | {shutdown,term()} | term()
1437                 State = state()
1438                 Data = data()
1439                 Ignored = term()
1440
1441          Note:
1442              This  callback  is optional, so callback modules need not export
1443              it. The gen_statem  module  provides  a  default  implementation
1444              without cleanup.
1445
1446
1447              This function is called by a gen_statem when it is about to ter‐
1448              minate. It is to be the opposite of  Module:init/1  and  do  any
1449              necessary  cleaning  up.  When it returns, the gen_statem termi‐
1450              nates with Reason. The return value is ignored.
1451
1452              Reason is a term denoting the  stop  reason  and  State  is  the
1453              internal state of the gen_statem.
1454
1455              Reason  depends  on  why the gen_statem is terminating. If it is
1456              because another callback function has  returned,  a  stop  tuple
1457              {stop,Reason} in Actions, Reason has the value specified in that
1458              tuple. If it is because of a failure, Reason is the  error  rea‐
1459              son.
1460
1461              If  the  gen_statem is part of a supervision tree and is ordered
1462              by its supervisor to terminate, this  function  is  called  with
1463              Reason = shutdown if both the following conditions apply:
1464
1465                * The gen_statem has been set to trap exit signals.
1466
1467                * The  shutdown  strategy as defined in the supervisor's child
1468                  specification is an integer time-out value, not brutal_kill.
1469
1470              Even if the gen_statem is not part of a supervision  tree,  this
1471              function  is  called  if  it receives an 'EXIT' message from its
1472              parent. Reason is the same as in the 'EXIT' message.
1473
1474              Otherwise, the gen_statem is immediately terminated.
1475
1476              Notice that for any  other  reason  than  normal,  shutdown,  or
1477              {shutdown,Term},  the gen_statem is assumed to terminate because
1478              of an error and an error report is issued using logger(3).
1479

SEE ALSO

1481       gen_event(3), gen_fsm(3),  gen_server(3),  proc_lib(3),  supervisor(3),
1482       sys(3).
1483
1484
1485
1486Ericsson AB                      stdlib 3.12.1                   gen_statem(3)
Impressum