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

EXAMPLE

179       The  following  example  shows a simple pushbutton model for a toggling
180       pushbutton implemented with callback mode state_functions. You can push
181       the  button  and it replies if it went on or off, and you can ask for a
182       count of how many times it has been pushed to switch on.
183
184       The following is the complete callback module file pushbutton.erl:
185
186       -module(pushbutton).
187       -behaviour(gen_statem).
188
189       -export([start/0,push/0,get_count/0,stop/0]).
190       -export([terminate/3,code_change/4,init/1,callback_mode/0]).
191       -export([on/3,off/3]).
192
193       name() -> pushbutton_statem. % The registered server name
194
195       %% API.  This example uses a registered name name()
196       %% and does not link to the caller.
197       start() ->
198           gen_statem:start({local,name()}, ?MODULE, [], []).
199       push() ->
200           gen_statem:call(name(), push).
201       get_count() ->
202           gen_statem:call(name(), get_count).
203       stop() ->
204           gen_statem:stop(name()).
205
206       %% Mandatory callback functions
207       terminate(_Reason, _State, _Data) ->
208           void.
209       code_change(_Vsn, State, Data, _Extra) ->
210           {ok,State,Data}.
211       init([]) ->
212           %% Set the initial state + data.  Data is used only as a counter.
213           State = off, Data = 0,
214           {ok,State,Data}.
215       callback_mode() -> state_functions.
216
217       %%% state callback(s)
218
219       off({call,From}, push, Data) ->
220           %% Go to 'on', increment count and reply
221           %% that the resulting status is 'on'
222           {next_state,on,Data+1,[{reply,From,on}]};
223       off(EventType, EventContent, Data) ->
224           handle_event(EventType, EventContent, Data).
225
226       on({call,From}, push, Data) ->
227           %% Go to 'off' and reply that the resulting status is 'off'
228           {next_state,off,Data,[{reply,From,off}]};
229       on(EventType, EventContent, Data) ->
230           handle_event(EventType, EventContent, Data).
231
232       %% Handle events common to all states
233       handle_event({call,From}, get_count, Data) ->
234           %% Reply with the current count
235           {keep_state,Data,[{reply,From,Data}]};
236       handle_event(_, _, Data) ->
237           %% Ignore all other events
238           {keep_state,Data}.
239
240
241       The following is a shell session when running it:
242
243       1> pushbutton:start().
244       {ok,<0.36.0>}
245       2> pushbutton:get_count().
246       0
247       3> pushbutton:push().
248       on
249       4> pushbutton:get_count().
250       1
251       5> pushbutton:push().
252       off
253       6> pushbutton:get_count().
254       1
255       7> pushbutton:stop().
256       ok
257       8> pushbutton:push().
258       ** exception exit: {noproc,{gen_statem,call,[pushbutton_statem,push,infinity]}}
259            in function  gen:do_for_proc/2 (gen.erl, line 261)
260            in call from gen_statem:call/3 (gen_statem.erl, line 386)
261
262
263       To compare styles, here follows the same example  using  callback  mode
264       handle_event_function,  or  rather  the  code to replace after function
265       init/1 of the pushbutton.erl example file above:
266
267       callback_mode() -> handle_event_function.
268
269       %%% state callback(s)
270
271       handle_event({call,From}, push, off, Data) ->
272           %% Go to 'on', increment count and reply
273           %% that the resulting status is 'on'
274           {next_state,on,Data+1,[{reply,From,on}]};
275       handle_event({call,From}, push, on, Data) ->
276           %% Go to 'off' and reply that the resulting status is 'off'
277           {next_state,off,Data,[{reply,From,off}]};
278       %%
279       %% Event handling common to all states
280       handle_event({call,From}, get_count, State, Data) ->
281           %% Reply with the current count
282           {next_state,State,Data,[{reply,From,Data}]};
283       handle_event(_, _, State, Data) ->
284           %% Ignore all other events
285           {next_state,State,Data}.
286
287

DATA TYPES

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

EXPORTS

851       call(ServerRef :: server_ref(), Request :: term()) ->
852               Reply :: term()
853
854       call(ServerRef :: server_ref(),
855            Request :: term(),
856            Timeout ::
857                timeout() |
858                {clean_timeout, T :: timeout()} |
859                {dirty_timeout, T :: timeout()}) ->
860               Reply :: term()
861
862              Makes  a synchronous call to the gen_statem ServerRef by sending
863              a request and waiting until its reply  arrives.  The  gen_statem
864              calls the state callback with event_type() {call,From} and event
865              content Request.
866
867              A  Reply  is  generated  when  a  state  callback  returns  with
868              {reply,From,Reply}  as  one action(), and that Reply becomes the
869              return value of this function.
870
871              Timeout is an integer > 0, which specifies how many milliseconds
872              to  wait for a reply, or the atom infinity to wait indefinitely,
873              which is the default. If no reply is received within the  speci‐
874              fied time, the function call fails.
875
876          Note:
877              For  Timeout  <  infinity,  to avoid getting a late reply in the
878              caller's inbox if the caller should catch exceptions, this func‐
879              tion  spawns  a  proxy  process that does the call. A late reply
880              gets delivered to the dead proxy process, hence gets  discarded.
881              This is less efficient than using Timeout == infinity.
882
883
884              Timeout  can  also  be a tuple {clean_timeout,T} or {dirty_time‐
885              out,T}, where T is the time-out  time.  {clean_timeout,T}  works
886              like just T described in the note above and uses a proxy process
887              while {dirty_timeout,T} bypasses the proxy process which is more
888              lightweight.
889
890          Note:
891              If  you  combine  catching  exceptions  from  this function with
892              {dirty_timeout,T} to avoid that the calling  process  dies  when
893              the  call  times  out,  you will have to be prepared to handle a
894              late reply. Note that there is an odd chance to get a late reply
895              even  with  {dirty_timeout,infinity}  or infinity for example in
896              the event of network problems. So why not just let  the  calling
897              process die by not catching the exception?
898
899
900              The  call  can  also  fail,  for example, if the gen_statem dies
901              before or during this function call.
902
903       cast(ServerRef :: server_ref(), Msg :: term()) -> ok
904
905              Sends an asynchronous event  to  the  gen_statem  ServerRef  and
906              returns  ok  immediately,  ignoring  if  the destination node or
907              gen_statem does not exist. The gen_statem calls the state  call‐
908              back with event_type() cast and event content Msg.
909
910       enter_loop(Module :: module(),
911                  Opts :: [debug_opt() | hibernate_after_opt()],
912                  State :: state(),
913                  Data :: data()) ->
914                     no_return()
915
916              The  same  as  enter_loop/6  with  Actions  =  [] except that no
917              server_name() must have been registered. This creates an  anony‐
918              mous server.
919
920       enter_loop(Module :: module(),
921                  Opts :: [debug_opt() | hibernate_after_opt()],
922                  State :: state(),
923                  Data :: data(),
924                  Server_or_Actions :: server_name() | pid() | [action()]) ->
925                     no_return()
926
927              If  Server_or_Actions  is  a  list(),  the  same as enter_loop/6
928              except that no  server_name()  must  have  been  registered  and
929              Actions = Server_or_Actions. This creates an anonymous server.
930
931              Otherwise    the    same   as   enter_loop/6   with   Server   =
932              Server_or_Actions and Actions = [].
933
934       enter_loop(Module :: module(),
935                  Opts :: [debug_opt() | hibernate_after_opt()],
936                  State :: state(),
937                  Data :: data(),
938                  Server :: server_name() | pid(),
939                  Actions :: [action()] | action()) ->
940                     no_return()
941
942              Makes the calling process become a gen_statem. Does not  return,
943              instead  the  calling process enters the gen_statem receive loop
944              and becomes a gen_statem server.  The  process  must  have  been
945              started  using  one of the start functions in proc_lib. The user
946              is responsible for any initialization of the process,  including
947              registering a name for it.
948
949              This  function is useful when a more complex initialization pro‐
950              cedure is needed than the gen_statem behavior provides.
951
952              Module,  Opts  have   the   same   meaning   as   when   calling
953              start[_link]/3,4.
954
955              If  Server is self() an anonymous server is created just as when
956              using start[_link]/3. If  Server  is  a  server_name()  a  named
957              server  is  created  just as when using start[_link]/4. However,
958              the server_name() name must  have  been  registered  accordingly
959              before this function is called.
960
961              State, Data, and Actions have the same meanings as in the return
962              value of Module:init/1. Also, the callback module does not  need
963              to export a Module:init/1 function.
964
965              The  function  fails if the calling process was not started by a
966              proc_lib start function, or if it is not registered according to
967              server_name().
968
969       reply(Replies :: [reply_action()] | reply_action()) -> ok
970
971       reply(From :: from(), Reply :: term()) -> ok
972
973              This  function  can be used by a gen_statem to explicitly send a
974              reply to a process that waits in call/2 when the reply cannot be
975              defined in the return value of a state callback.
976
977              From  must  be  the  term from argument {call,From} to the state
978              callback. A reply or multiple replies canalso be sent using  one
979              or several reply_action()s from a state callback.
980
981          Note:
982              A reply sent with this function is not visible in sys debug out‐
983              put.
984
985
986       start(Module :: module(), Args :: term(), Opts :: [start_opt()]) ->
987                start_ret()
988
989       start(ServerName :: server_name(),
990             Module :: module(),
991             Args :: term(),
992             Opts :: [start_opt()]) ->
993                start_ret()
994
995              Creates a standalone gen_statem process according to OTP  design
996              principles  (using  proc_lib  primitives).  As  it  does not get
997              linked to the calling process, this  start  function  cannot  be
998              used by a supervisor to start a child.
999
1000              For   a   description   of  arguments  and  return  values,  see
1001              start_link/3,4.
1002
1003       start_link(Module :: module(),
1004                  Args :: term(),
1005                  Opts :: [start_opt()]) ->
1006                     start_ret()
1007
1008       start_link(ServerName :: server_name(),
1009                  Module :: module(),
1010                  Args :: term(),
1011                  Opts :: [start_opt()]) ->
1012                     start_ret()
1013
1014              Creates a gen_statem process according to OTP design  principles
1015              (using  proc_lib  primitives)  that  is  linked  to  the calling
1016              process. This is essential when the gen_statem must be part of a
1017              supervision tree so it gets linked to its supervisor.
1018
1019              The  gen_statem  process  calls  Module:init/1 to initialize the
1020              server.   To   ensure   a   synchronized   startup    procedure,
1021              start_link/3,4 does not return until Module:init/1 has returned.
1022
1023              ServerName  specifies  the  server_name()  to  register  for the
1024              gen_statem. If the gen_statem is started with  start_link/3,  no
1025              ServerName is provided and the gen_statem is not registered.
1026
1027              Module is the name of the callback module.
1028
1029              Args is an arbitrary term that is passed as the argument to Mod‐
1030              ule:init/1.
1031
1032                * If option {timeout,Time} is present in Opts, the  gen_statem
1033                  is  allowed  to  spend  Time milliseconds initializing or it
1034                  terminates and the start function returns {error,timeout}.
1035
1036                * If option{hibernate_after,HibernateAfterTimeout} is present,
1037                  the   gen_statem  process  awaits  any  message  for  Hiber‐
1038                  nateAfterTimeout milliseconds and if no message is received,
1039                  the  process goes into hibernation automatically (by calling
1040                  proc_lib:hibernate/3).
1041
1042                * If option {debug,Dbgs} is present in Opts, debugging through
1043                  sys is activated.
1044
1045                * If   option   {spawn_opt,SpawnOpts}   is  present  in  Opts,
1046                  SpawnOpts is passed as option  list  to  erlang:spawn_opt/2,
1047                  which is used to spawn the gen_statem process.
1048
1049          Note:
1050              Using  spawn option monitor is not allowed, it causes this func‐
1051              tion to fail with reason badarg.
1052
1053
1054              If the gen_statem is successfully created and initialized,  this
1055              function  returns  {ok,Pid},  where  Pid  is  the  pid()  of the
1056              gen_statem. If a process with the  specified  ServerName  exists
1057              already,  this  function  returns {error,{already_started,Pid}},
1058              where Pid is the pid() of that process.
1059
1060              If  Module:init/1  fails  with  Reason,  this  function  returns
1061              {error,Reason}.   If   Module:init/1  returns  {stop,Reason}  or
1062              ignore, the process is  terminated  and  this  function  returns
1063              {error,Reason} or ignore, respectively.
1064
1065       stop(ServerRef :: server_ref()) -> ok
1066
1067              The same as stop(ServerRef, normal, infinity).
1068
1069       stop(ServerRef :: server_ref(),
1070            Reason :: term(),
1071            Timeout :: timeout()) ->
1072               ok
1073
1074              Orders  the gen_statem ServerRef to exit with the specified Rea‐
1075              son and waits for it to terminate.  The  gen_statem  calls  Mod‐
1076              ule:terminate/3 before exiting.
1077
1078              This  function  returns  ok  if  the  server terminates with the
1079              expected reason. Any other  reason  than  normal,  shutdown,  or
1080              {shutdown,Term} causes an error report to be issued through log‐
1081              ger(3). The default Reason is normal.
1082
1083              Timeout is an integer > 0, which specifies how many milliseconds
1084              to  wait  for  the  server to terminate, or the atom infinity to
1085              wait indefinitely. Defaults to infinity. If the server does  not
1086              terminate  within  the  specified  time,  a timeout exception is
1087              raised.
1088
1089              If the process does not exist, a noproc exception is raised.
1090

CALLBACK FUNCTIONS

1092       The following functions are to be exported from a  gen_statem  callback
1093       module.
1094

EXPORTS

1096       Module:callback_mode() -> CallbackMode
1097
1098              Types:
1099
1100                  CallbackMode   =   callback_mode()  |  [  callback_mode()  |
1101                 state_enter() ]
1102
1103              This function is called by a gen_statem when it  needs  to  find
1104              out  the  callback  mode  of  the  callback module. The value is
1105              cached by gen_statem for efficiency reasons, so this function is
1106              only  called  once after server start and after code change, but
1107              before the first state callback in the current code  version  is
1108              called.  More  occasions  may  be  added  in  future versions of
1109              gen_statem.
1110
1111              Server start happens either when Module:init/1 returns  or  when
1112              enter_loop/4-6   is   called.  Code  change  happens  when  Mod‐
1113              ule:code_change/4 returns.
1114
1115              The CallbackMode is either just callback_mode() or a  list  con‐
1116              taining callback_mode() and possibly the atom state_enter.
1117
1118          Note:
1119              If this function's body does not return an inline constant value
1120              the callback module is doing something strange.
1121
1122
1123       Module:code_change(OldVsn, OldState, OldData, Extra) -> Result
1124
1125              Types:
1126
1127                 OldVsn = Vsn | {down,Vsn}
1128                  Vsn = term()
1129                 OldState = NewState = term()
1130                 Extra = term()
1131                 Result = {ok,NewState,NewData} | Reason
1132                  OldState = NewState = state()
1133                  OldData = NewData = data()
1134                 Reason = term()
1135
1136          Note:
1137              This callback is optional, so callback modules need  not  export
1138              it.  If a release upgrade/downgrade with Change={advanced,Extra}
1139              specified in the .appup file is made when code_change/4  is  not
1140              implemented the process will crash with exit reason undef.
1141
1142
1143              This function is called by a gen_statem when it is to update its
1144              internal state during a release upgrade/downgrade, that is, when
1145              the      instruction      {update,Module,Change,...},      where
1146              Change={advanced,Extra}, is specified in  the  appup  file.  For
1147              more information, see OTP Design Principles.
1148
1149              For  an  upgrade,  OldVsn is Vsn, and for a downgrade, OldVsn is
1150              {down,Vsn}. Vsn is defined by the vsn attribute(s)  of  the  old
1151              version  of  the callback module Module. If no such attribute is
1152              defined, the version is the checksum of the Beam file.
1153
1154              OldState and OldData is the internal state of the gen_statem.
1155
1156              Extra is passed "as is" from the {advanced,Extra}  part  of  the
1157              update instruction.
1158
1159              If  successful,  the  function  must return the updated internal
1160              state in an {ok,NewState,NewData} tuple.
1161
1162              If the function returns a failure Reason,  the  ongoing  upgrade
1163              fails  and  rolls  back to the old release. Note that Reason can
1164              not be an {ok,_,_} tuple  since  that  will  be  regarded  as  a
1165              {ok,NewState,NewData} tuple, and that a tuple matching {ok,_} is
1166              an also invalid failure Reason. It is recommended to use an atom
1167              as Reason since it will be wrapped in an {error,Reason} tuple.
1168
1169              Also  note  when upgrading a gen_statem, this function and hence
1170              the Change={advanced,Extra} parameter in the appup file  is  not
1171              only  needed to update the internal state or to act on the Extra
1172              argument. It is also needed if an upgrade  or  downgrade  should
1173              change  callback  mode, or else the callback mode after the code
1174              change will not be honoured,  most  probably  causing  a  server
1175              crash.
1176
1177       Module:init(Args) -> Result(StateType)
1178
1179              Types:
1180
1181                 Args = term()
1182                  Result(StateType) = init_result(StateType)
1183
1184              Whenever   a  gen_statem  is  started  using  start_link/3,4  or
1185              start/3,4, this function is called by the new  process  to  ini‐
1186              tialize the implementation state and server data.
1187
1188              Args is the Args argument provided to that start function.
1189
1190          Note:
1191              Note  that  if  the  gen_statem  is started through proc_lib and
1192              enter_loop/4-6, this callback will never be called.  Since  this
1193              callback is not optional it can in that case be implemented as:
1194
1195              init(Args) -> erlang:error(not_implemented, [Args]).
1196
1197
1198       Module:format_status(Opt, [PDict,State,Data]) -> Status
1199
1200              Types:
1201
1202                 Opt = normal | terminate
1203                 PDict = [{Key, Value}]
1204                  State = state()
1205                  Data = data()
1206                 Key = term()
1207                 Value = term()
1208                 Status = term()
1209
1210          Note:
1211              This callback is optional, so a callback module does not need to
1212              export it. The gen_statem module provides a default  implementa‐
1213              tion of this function that returns {State,Data}.
1214
1215              If  this callback is exported but fails, to hide possibly sensi‐
1216              tive  data,   the   default   function   will   instead   return
1217              {State,Info},  where  Info  says  nothing but the fact that for‐
1218              mat_status/2 has crashed.
1219
1220
1221              This function is called by a gen_statem process when any of  the
1222              following apply:
1223
1224                *
1225                   One  of sys:get_status/1,2 is invoked to get the gen_statem
1226                  status. Opt is set to the atom normal for this case.
1227
1228                *
1229                   The gen_statem terminates abnormally and logs an error. Opt
1230                  is set to the atom terminate for this case.
1231
1232              This  function is useful for changing the form and appearance of
1233              the gen_statem status for these cases. A callback module wishing
1234              to change the sys:get_status/1,2 return value and how its status
1235              appears in termination error logs exports an  instance  of  for‐
1236              mat_status/2, which returns a term describing the current status
1237              of the gen_statem.
1238
1239              PDict is the current value of  the  process  dictionary  of  the
1240              gen_statem.
1241
1242              State is the internal state of the gen_statem.
1243
1244              Data is the internal server data of the gen_statem.
1245
1246              The  function  is  to  return  Status,  a term that contains the
1247              appropriate details of the  current  state  and  status  of  the
1248              gen_statem.  There  are  no  restrictions on the form Status can
1249              take, but for the sys:get_status/1,2 case (when Opt is  normal),
1250              the  recommended form for the Status value is [{data, [{"State",
1251              Term}]}], where Term provides relevant details of the gen_statem
1252              state.  Following  this  recommendation  is not required, but it
1253              makes the callback module status consistent with the rest of the
1254              sys:get_status/1,2 return value.
1255
1256              One use for this function is to return compact alternative state
1257              representations to avoid having large state terms printed in log
1258              files.  Another use is to hide sensitive data from being written
1259              to the error log.
1260
1261       Module:StateName(enter, OldState, Data) -> StateEnterResult(StateName)
1262       Module:StateName(EventType, EventContent, Data) -> StateFunctionResult
1263       Module:handle_event(enter,  OldState,  State,  Data)  ->  StateEnterRe‐
1264       sult(State)
1265       Module:handle_event(EventType,   EventContent,  State,  Data)  ->  Han‐
1266       dleEventResult
1267
1268              Types:
1269
1270                  EventType = event_type()
1271                 EventContent = term()
1272                  State = state()
1273                  Data = NewData = data()
1274                  StateEnterResult(StateName) = state_enter_result(StateName)
1275                  StateFunctionResult = event_handler_result(state_name())
1276                  StateEnterResult(State) = state_enter_result(State)
1277                  HandleEventResult = event_handler_result(state())
1278
1279              Whenever a gen_statem receives an event from call/2, cast/2,  or
1280              as  a  normal process message, one of these functions is called.
1281              If  callback  mode  is  state_functions,  Module:StateName/3  is
1282              called,   and   if   it  is  handle_event_function,  Module:han‐
1283              dle_event/4 is called.
1284
1285              If EventType is {call,From}, the caller waits for a  reply.  The
1286              reply  can be sent from this or from any other state callback by
1287              returning with {reply,From,Reply} in Actions, in Replies, or  by
1288              calling reply(From, Reply).
1289
1290              If  this  function returns with a next state that does not match
1291              equal (=/=) to the  current  state,  all  postponed  events  are
1292              retried in the next state.
1293
1294              The  only difference between StateFunctionResult and HandleEven‐
1295              tResult is that for StateFunctionResult the next state  must  be
1296              an  atom,  but  for HandleEventResult there is no restriction on
1297              the next state.
1298
1299              For options that can be set and actions  that  can  be  done  by
1300              gen_statem after returning from this function, see action().
1301
1302              When the gen_statem runs with state enter calls, these functions
1303              are also called with arguments (enter, OldState,  ...)  whenever
1304              the  state  changes. In this case there are some restrictions on
1305              the actions that may be  returned:  postpone()  is  not  allowed
1306              since a state enter call is not an event so there is no event to
1307              postpone, and {next_event,_,_} is not allowed since using  state
1308              enter  calls  should not affect how events are consumed and pro‐
1309              duced. You may also not change states from this call. Should you
1310              return  {next_state,NextState, ...} with NextState =/= State the
1311              gen_statem crashes. Note that it  is  actually  allowed  to  use
1312              {repeat_state,  NewData,  ...}  although  it  makes little sense
1313              since you immediately will be called  again  with  a  new  state
1314              enter  call  making  this just a weird way of looping, and there
1315              are better ways to loop in Erlang. If you do not update  NewData
1316              and  have  some  loop  termination  condition,  or  if  you  use
1317              {repeat_state_and_data, _} or repeat_state_and_data you have  an
1318              infinite   loop!   You  are  advised  to  use  {keep_state,...},
1319              {keep_state_and_data,_} or  keep_state_and_data  since  changing
1320              states from a state enter call is not possible anyway.
1321
1322              Note the fact that you can use throw to return the result, which
1323              can   be   useful.   For    example    to    bail    out    with
1324              throw(keep_state_and_data)  from  deep  within complex code that
1325              can not return {next_state,State,Data} because State or Data  is
1326              no longer in scope.
1327
1328       Module:terminate(Reason, State, Data) -> Ignored
1329
1330              Types:
1331
1332                 Reason = normal | shutdown | {shutdown,term()} | term()
1333                 State = state()
1334                 Data = data()
1335                 Ignored = term()
1336
1337          Note:
1338              This  callback  is optional, so callback modules need not export
1339              it. The gen_statem  module  provides  a  default  implementation
1340              without cleanup.
1341
1342
1343              This function is called by a gen_statem when it is about to ter‐
1344              minate. It is to be the opposite of  Module:init/1  and  do  any
1345              necessary  cleaning  up.  When it returns, the gen_statem termi‐
1346              nates with Reason. The return value is ignored.
1347
1348              Reason is a term denoting the  stop  reason  and  State  is  the
1349              internal state of the gen_statem.
1350
1351              Reason  depends  on  why the gen_statem is terminating. If it is
1352              because another callback function has  returned,  a  stop  tuple
1353              {stop,Reason} in Actions, Reason has the value specified in that
1354              tuple. If it is because of a failure, Reason is the  error  rea‐
1355              son.
1356
1357              If  the  gen_statem is part of a supervision tree and is ordered
1358              by its supervisor to terminate, this  function  is  called  with
1359              Reason = shutdown if both the following conditions apply:
1360
1361                * The gen_statem has been set to trap exit signals.
1362
1363                * The  shutdown  strategy as defined in the supervisor's child
1364                  specification is an integer time-out value, not brutal_kill.
1365
1366              Even if the gen_statem is not part of a supervision  tree,  this
1367              function  is  called  if  it receives an 'EXIT' message from its
1368              parent. Reason is the same as in the 'EXIT' message.
1369
1370              Otherwise, the gen_statem is immediately terminated.
1371
1372              Notice that for any  other  reason  than  normal,  shutdown,  or
1373              {shutdown,Term},  the gen_statem is assumed to terminate because
1374              of an error and an error report is issued using logger(3).
1375

SEE ALSO

1377       gen_event(3), gen_fsm(3),  gen_server(3),  proc_lib(3),  supervisor(3),
1378       sys(3).
1379
1380
1381
1382Ericsson AB                     stdlib 3.8.2.1                   gen_statem(3)
Impressum