1gen_statem(3) Erlang Module Definition gen_statem(3)
2
3
4
6 gen_statem - Generic state machine behavior.
7
9 This behavior module provides a state machine. Two callback modes are
10 supported:
11
12 * One for finite-state machines (gen_fsm like), which requires the
13 state to be an atom and uses that state as the name of the current
14 callback function
15
16 * One without restriction on the state data type that uses one call‐
17 back function for all states
18
19 Note:
20 This is a new behavior in Erlang/OTP 19.0. It has been thoroughly
21 reviewed, is stable enough to be used by at least two heavy OTP appli‐
22 cations, and is here to stay. Depending on user feedback, we do not
23 expect but can find it necessary to make minor not backward compatible
24 changes into Erlang/OTP 20.0.
25
26
27 The gen_statem behavior replaces gen_fsm in Erlang/OTP 20.0. It has the
28 same features and adds some really useful:
29
30 * Gathered state code.
31
32 * Arbitrary term state.
33
34 * Event postponing.
35
36 * Self-generated events.
37
38 * State time-out.
39
40 * Multiple generic named time-outs.
41
42 * Absolute time-out time.
43
44 * Automatic state enter calls.
45
46 * Reply from other state than the request.
47
48 * Multiple sys traceable replies.
49
50 The callback model(s) for gen_statem differs from the one for gen_fsm,
51 but it is still fairly easy to rewrite from gen_fsm to gen_statem.
52
53 A generic state machine process (gen_statem) implemented using this
54 module has a standard set of interface functions and includes function‐
55 ality for tracing and error reporting. It also fits into an OTP super‐
56 vision tree. For more information, see OTP Design Principles.
57
58 A gen_statem assumes all specific parts to be located in a callback
59 module exporting a predefined set of functions. The relationship
60 between the behavior functions and the callback functions is as fol‐
61 lows:
62
63 gen_statem module Callback module
64 ----------------- ---------------
65 gen_statem:start
66 gen_statem:start_link -----> Module:init/1
67
68 Server start or code change
69 -----> Module:callback_mode/0
70
71 gen_statem:stop -----> Module:terminate/3
72
73 gen_statem:call
74 gen_statem:cast
75 erlang:send
76 erlang:'!' -----> Module:StateName/3
77 Module:handle_event/4
78
79 - -----> Module:terminate/3
80
81 - -----> Module:code_change/4
82
83 Events are of different types, so the callback functions can know the
84 origin of an event and how to respond.
85
86 If a callback function fails or returns a bad value, the gen_statem
87 terminates, unless otherwise stated. However, an exception of class
88 throw is not regarded as an error but as a valid return from all call‐
89 back functions.
90
91 The "state callback" for a specific state in a gen_statem is the call‐
92 back function that is called for all events in this state. It is
93 selected depending on which callback mode that the callback module
94 defines with the callback function Module:callback_mode/0.
95
96 When the callback mode is state_functions, the state must be an atom
97 and is used as the state callback name; see Module:StateName/3. This
98 gathers all code for a specific state in one function as the gen_statem
99 engine branches depending on state name. Note the fact that the call‐
100 back function Module:terminate/3 makes the state name terminate unus‐
101 able in this mode.
102
103 When the callback mode is handle_event_function, the state can be any
104 term and the state callback name is Module:handle_event/4. This makes
105 it easy to branch depending on state or event as you desire. Be careful
106 about which events you handle in which states so that you do not acci‐
107 dentally postpone an event forever creating an infinite busy loop.
108
109 The gen_statem enqueues incoming events in order of arrival and
110 presents these to the state callback in that order. The state callback
111 can postpone an event so it is not retried in the current state. After
112 a state change the queue restarts with the postponed events.
113
114 The gen_statem event queue model is sufficient to emulate the normal
115 process message queue with selective receive. Postponing an event cor‐
116 responds to not matching it in a receive statement, and changing states
117 corresponds to entering a new receive statement.
118
119 The state callback can insert events using the action() next_event and
120 such an event is inserted as the next to present to the state callback.
121 That is, as if it is the oldest incoming event. A dedicated
122 event_type() internal can be used for such events making them impossi‐
123 ble to mistake for external events.
124
125 Inserting an event replaces the trick of calling your own state han‐
126 dling functions that you often would have to resort to in, for example,
127 gen_fsm to force processing an inserted event before others.
128
129 The gen_statem engine can automatically make a specialized call to the
130 state callback whenever a new state is entered; see state_enter(). This
131 is for writing code common to all state entries. Another way to do it
132 is to insert events at state transitions, but you have to do so every‐
133 where it is needed.
134
135 Note:
136 If you in gen_statem, for example, postpone an event in one state and
137 then call another state callback of yours, you have not changed states
138 and hence the postponed event is not retried, which is logical but can
139 be confusing.
140
141
142 For the details of a state transition, see type transition_option().
143
144 A gen_statem handles system messages as described in sys. The sys mod‐
145 ule can be used for debugging a gen_statem.
146
147 Notice that a gen_statem does not trap exit signals automatically, this
148 must be explicitly initiated in the callback module (by calling
149 process_flag(trap_exit, true).
150
151 Unless otherwise stated, all functions in this module fail if the spec‐
152 ified gen_statem does not exist or if bad arguments are specified.
153
154 The gen_statem process can go into hibernation; see proc_lib:hiber‐
155 nate/3. It is done when a state callback or Module:init/1 specifies
156 hibernate in the returned Actions list. This feature can be useful to
157 reclaim process heap memory while the server is expected to be idle for
158 a long time. However, use this feature with care, as hibernation can be
159 too costly to use after every event; see erlang:hibernate/3.
160
162 The following example shows a simple pushbutton model for a toggling
163 pushbutton implemented with callback mode state_functions. You can push
164 the button and it replies if it went on or off, and you can ask for a
165 count of how many times it has been pushed to switch on.
166
167 The following is the complete callback module file pushbutton.erl:
168
169 -module(pushbutton).
170 -behaviour(gen_statem).
171
172 -export([start/0,push/0,get_count/0,stop/0]).
173 -export([terminate/3,code_change/4,init/1,callback_mode/0]).
174 -export([on/3,off/3]).
175
176 name() -> pushbutton_statem. % The registered server name
177
178 %% API. This example uses a registered name name()
179 %% and does not link to the caller.
180 start() ->
181 gen_statem:start({local,name()}, ?MODULE, [], []).
182 push() ->
183 gen_statem:call(name(), push).
184 get_count() ->
185 gen_statem:call(name(), get_count).
186 stop() ->
187 gen_statem:stop(name()).
188
189 %% Mandatory callback functions
190 terminate(_Reason, _State, _Data) ->
191 void.
192 code_change(_Vsn, State, Data, _Extra) ->
193 {ok,State,Data}.
194 init([]) ->
195 %% Set the initial state + data. Data is used only as a counter.
196 State = off, Data = 0,
197 {ok,State,Data}.
198 callback_mode() -> state_functions.
199
200 %%% state callback(s)
201
202 off({call,From}, push, Data) ->
203 %% Go to 'on', increment count and reply
204 %% that the resulting status is 'on'
205 {next_state,on,Data+1,[{reply,From,on}]};
206 off(EventType, EventContent, Data) ->
207 handle_event(EventType, EventContent, Data).
208
209 on({call,From}, push, Data) ->
210 %% Go to 'off' and reply that the resulting status is 'off'
211 {next_state,off,Data,[{reply,From,off}]};
212 on(EventType, EventContent, Data) ->
213 handle_event(EventType, EventContent, Data).
214
215 %% Handle events common to all states
216 handle_event({call,From}, get_count, Data) ->
217 %% Reply with the current count
218 {keep_state,Data,[{reply,From,Data}]};
219 handle_event(_, _, Data) ->
220 %% Ignore all other events
221 {keep_state,Data}.
222
223
224 The following is a shell session when running it:
225
226 1> pushbutton:start().
227 {ok,<0.36.0>}
228 2> pushbutton:get_count().
229 0
230 3> pushbutton:push().
231 on
232 4> pushbutton:get_count().
233 1
234 5> pushbutton:push().
235 off
236 6> pushbutton:get_count().
237 1
238 7> pushbutton:stop().
239 ok
240 8> pushbutton:push().
241 ** exception exit: {noproc,{gen_statem,call,[pushbutton_statem,push,infinity]}}
242 in function gen:do_for_proc/2 (gen.erl, line 261)
243 in call from gen_statem:call/3 (gen_statem.erl, line 386)
244
245
246 To compare styles, here follows the same example using callback mode
247 handle_event_function, or rather the code to replace after function
248 init/1 of the pushbutton.erl example file above:
249
250 callback_mode() -> handle_event_function.
251
252 %%% state callback(s)
253
254 handle_event({call,From}, push, off, Data) ->
255 %% Go to 'on', increment count and reply
256 %% that the resulting status is 'on'
257 {next_state,on,Data+1,[{reply,From,on}]};
258 handle_event({call,From}, push, on, Data) ->
259 %% Go to 'off' and reply that the resulting status is 'off'
260 {next_state,off,Data,[{reply,From,off}]};
261 %%
262 %% Event handling common to all states
263 handle_event({call,From}, get_count, State, Data) ->
264 %% Reply with the current count
265 {next_state,State,Data,[{reply,From,Data}]};
266 handle_event(_, _, State, Data) ->
267 %% Ignore all other events
268 {next_state,State,Data}.
269
270
272 server_name() =
273 {global, GlobalName :: term()} |
274 {via, RegMod :: module(), Name :: term()} |
275 {local, atom()}
276
277 Name specification to use when starting a gen_statem server. See
278 start_link/3 and server_ref() below.
279
280 server_ref() =
281 pid() |
282 (LocalName :: atom()) |
283 {Name :: atom(), Node :: atom()} |
284 {global, GlobalName :: term()} |
285 {via, RegMod :: module(), ViaName :: term()}
286
287 Server specification to use when addressing a gen_statem server.
288 See call/2 and server_name() above.
289
290 It can be:
291
292 pid() | LocalName:
293 The gen_statem is locally registered.
294
295 {Name,Node}:
296 The gen_statem is locally registered on another node.
297
298 {global,GlobalName}:
299 The gen_statem is globally registered in global.
300
301 {via,RegMod,ViaName}:
302 The gen_statem is registered in an alternative process reg‐
303 istry. The registry callback module RegMod is to export
304 functions register_name/2, unregister_name/1,
305 whereis_name/1, and send/2, which are to behave like the
306 corresponding functions in global. Thus, {via,global,Global‐
307 Name} is the same as {global,GlobalName}.
308
309 debug_opt() =
310 {debug,
311 Dbgs ::
312 [trace | log | statistics | debug | {logfile, string()}]}
313
314 Debug option that can be used when starting a gen_statem server
315 through, enter_loop/4-6.
316
317 For every entry in Dbgs, the corresponding function in sys is
318 called.
319
320 hibernate_after_opt() =
321 {hibernate_after, HibernateAfterTimeout :: timeout()}
322
323 hibernate_after option that can be used when starting a
324 gen_statem server through, enter_loop/4-6.
325
326 If option{hibernate_after,HibernateAfterTimeout} is present, the
327 gen_statem process awaits any message for HibernateAfterTimeout
328 milliseconds and if no message is received, the process goes
329 into hibernation automatically (by calling proc_lib:hiber‐
330 nate/3).
331
332 start_opt() =
333 debug_opt() |
334 {timeout, Time :: timeout()} |
335 hibernate_after_opt() |
336 {spawn_opt, [proc_lib:spawn_option()]}
337
338 Options that can be used when starting a gen_statem server
339 through, for example, start_link/3.
340
341 start_ret() = {ok, pid()} | ignore | {error, term()}
342
343 Return value from the start functions, for example,
344 start_link/3.
345
346 from() = {To :: pid(), Tag :: term()}
347
348 Destination to use when replying through, for example, the
349 action() {reply,From,Reply} to a process that has called the
350 gen_statem server using call/2.
351
352 state() = state_name() | term()
353
354 If the callback mode is handle_event_function, the state can be
355 any term. After a state change (NextState =/= State), all post‐
356 poned events are retried.
357
358 state_name() = atom()
359
360 If the callback mode is state_functions, the state must be of
361 this type. After a state change (NextState =/= State), all post‐
362 poned events are retried.
363
364 data() = term()
365
366 A term in which the state machine implementation is to store any
367 server data it needs. The difference between this and the
368 state() itself is that a change in this data does not cause
369 postponed events to be retried. Hence, if a change in this data
370 would change the set of events that are handled, then that data
371 item is to be made a part of the state.
372
373 event_type() =
374 external_event_type() | timeout_event_type() | internal
375
376 There are 3 categories of events: external, timeout, and inter‐
377 nal.
378
379 internal events can only be generated by the state machine
380 itself through the state transition action next_event.
381
382 external_event_type() = {call, From :: from()} | cast | info
383
384 External events are of 3 types: {call,From}, cast, or info.
385 Calls (synchronous) and casts originate from the corresponding
386 API functions. For calls, the event contains whom to reply to.
387 Type info originates from regular process messages sent to the
388 gen_statem.
389
390 timeout_event_type() =
391 timeout | {timeout, Name :: term()} | state_timeout
392
393 There are 3 types of timeout events that the state machine can
394 generate for itself with the corresponding timeout_action()s.
395
396 callback_mode_result() =
397 callback_mode() | [callback_mode() | state_enter()]
398
399 This is the return type from Module:callback_mode/0 and selects
400 callback mode and whether to do state enter calls, or not.
401
402 callback_mode() = state_functions | handle_event_function
403
404 The callback mode is selected when starting the gen_statem and
405 after code change using the return value from Module:call‐
406 back_mode/0.
407
408 state_functions:
409 The state must be of type state_name() and one callback
410 function per state, that is, Module:StateName/3, is used.
411
412 handle_event_function:
413 The state can be any term and the callback function Mod‐
414 ule:handle_event/4 is used for all states.
415
416 state_enter() = state_enter
417
418 Whether the state machine should use state enter calls or not is
419 selected when starting the gen_statem and after code change
420 using the return value from Module:callback_mode/0.
421
422 If Module:callback_mode/0 returns a list containing state_enter,
423 the gen_statem engine will, at every state change, call the
424 state callback with arguments (enter, OldState, Data). This may
425 look like an event but is really a call performed after the pre‐
426 vious state callback returned and before any event is delivered
427 to the new state callback. See Module:StateName/3 and Mod‐
428 ule:handle_event/4. Such a call can be repeated by returning a
429 repeat_state or repeat_state_and_data tuple from the state call‐
430 back.
431
432 If Module:callback_mode/0 does not return such a list, no state
433 enter calls are done.
434
435 If Module:code_change/4 should transform the state to a state
436 with a different name it is still regarded as the same state so
437 this does not cause a state enter call.
438
439 Note that a state enter call will be done right before entering
440 the initial state even though this formally is not a state
441 change. In this case OldState will be the same as State, which
442 can not happen for a subsequent state change, but will happen
443 when repeating the state enter call.
444
445 transition_option() =
446 postpone() |
447 hibernate() |
448 event_timeout() |
449 generic_timeout() |
450 state_timeout()
451
452 Transition options can be set by actions and they modify how the
453 state transition is done:
454
455 * If the state changes, is the initial state, repeat_state or
456 repeat_state_and_data is used, and also state enter calls
457 are used, the gen_statem calls the new state callback with
458 arguments (enter, OldState, Data). Any actions returned from
459 this call are handled as if they were appended to the
460 actions returned by the state callback that changed states.
461
462 * All actions are processed in order of appearance.
463
464 * If postpone() is true, the current event is postponed.
465
466 * If the state changes, the queue of incoming events is reset
467 to start with the oldest postponed.
468
469 * All events stored with action() next_event are inserted to
470 be processed before the other queued events.
471
472 * Time-out timers event_timeout(), generic_timeout() and
473 state_timeout() are handled. Time-outs with zero time are
474 guaranteed to be delivered to the state machine before any
475 external not yet received event so if there is such a time-
476 out requested, the corresponding time-out zero event is
477 enqueued as the newest event.
478
479 Any event cancels an event_timeout() so a zero time event
480 time-out is only generated if the event queue is empty.
481
482 A state change cancels a state_timeout() and any new transi‐
483 tion option of this type belongs to the new state.
484
485 * If there are enqueued events the state callback for the pos‐
486 sibly new state is called with the oldest enqueued event,
487 and we start again from the top of this list.
488
489 * Otherwise the gen_statem goes into receive or hibernation
490 (if hibernate() is true) to wait for the next message. In
491 hibernation the next non-system event awakens the
492 gen_statem, or rather the next incoming message awakens the
493 gen_statem, but if it is a system event it goes right back
494 into hibernation. When a new message arrives the state call‐
495 back is called with the corresponding event, and we start
496 again from the top of this list.
497
498 postpone() = boolean()
499
500 If true, postpones the current event and retries it when the
501 state changes (NextState =/= State).
502
503 hibernate() = boolean()
504
505 If true, hibernates the gen_statem by calling proc_lib:hiber‐
506 nate/3 before going into receive to wait for a new external
507 event. If there are enqueued events, to prevent receiving any
508 new event, an erlang:garbage_collect/0 is done instead to simu‐
509 late that the gen_statem entered hibernation and immediately got
510 awakened by the oldest enqueued event.
511
512 event_timeout() = timeout() | integer()
513
514 Starts a timer set by enter_action() timeout. When the timer
515 expires an event of event_type() timeout will be generated. See
516 erlang:start_timer/4 for how Time and Options are interpreted.
517 Future erlang:start_timer/4 Options will not necessarily be sup‐
518 ported.
519
520 Any event that arrives cancels this time-out. Note that a
521 retried or inserted event counts as arrived. So does a state
522 time-out zero event, if it was generated before this time-out is
523 requested.
524
525 If Time is infinity, no timer is started, as it never would
526 expire anyway.
527
528 If Time is relative and 0 no timer is actually started, instead
529 the the time-out event is enqueued to ensure that it gets pro‐
530 cessed before any not yet received external event.
531
532 Note that it is not possible nor needed to cancel this time-out,
533 as it is cancelled automatically by any other event.
534
535 generic_timeout() = timeout() | integer()
536
537 Starts a timer set by enter_action() {timeout,Name}. When the
538 timer expires an event of event_type() {timeout,Name} will be
539 generated. See erlang:start_timer/4 for how Time and Options are
540 interpreted. Future erlang:start_timer/4 Options will not neces‐
541 sarily be supported.
542
543 If Time is infinity, no timer is started, as it never would
544 expire anyway.
545
546 If Time is relative and 0 no timer is actually started, instead
547 the the time-out event is enqueued to ensure that it gets pro‐
548 cessed before any not yet received external event.
549
550 Setting a timer with the same Name while it is running will
551 restart it with the new time-out value. Therefore it is possible
552 to cancel a specific time-out by setting it to infinity.
553
554 state_timeout() = timeout() | integer()
555
556 Starts a timer set by enter_action() state_timeout. When the
557 timer expires an event of event_type() state_timeout will be
558 generated. See erlang:start_timer/4 for how Time and Options are
559 interpreted. Future erlang:start_timer/4 Options will not neces‐
560 sarily be supported.
561
562 If Time is infinity, no timer is started, as it never would
563 expire anyway.
564
565 If Time is relative and 0 no timer is actually started, instead
566 the the time-out event is enqueued to ensure that it gets pro‐
567 cessed before any not yet received external event.
568
569 Setting this timer while it is running will restart it with the
570 new time-out value. Therefore it is possible to cancel this
571 time-out by setting it to infinity.
572
573 timeout_option() = {abs, Abs :: boolean()}
574
575 If Abs is true an absolute timer is started, and if it is false
576 a relative, which is the default. See erlang:start_timer/4 for
577 details.
578
579 action() =
580 postpone |
581 {postpone, Postpone :: postpone()} |
582 {next_event,
583 EventType :: event_type(),
584 EventContent :: term()} |
585 enter_action()
586
587 These state transition actions can be invoked by returning them
588 from the state callback when it is called with an event, from
589 Module:init/1 or by giving them to enter_loop/5,6.
590
591 Actions are executed in the containing list order.
592
593 Actions that set transition options override any previous of the
594 same type, so the last in the containing list wins. For example,
595 the last postpone() overrides any previous postpone() in the
596 list.
597
598 postpone:
599 Sets the transition_option() postpone() for this state tran‐
600 sition. This action is ignored when returned from Mod‐
601 ule:init/1 or given to enter_loop/5,6, as there is no event
602 to postpone in those cases.
603
604 next_event:
605 Stores the specified EventType and EventContent for inser‐
606 tion after all actions have been executed.
607
608 The stored events are inserted in the queue as the next to
609 process before any already queued events. The order of these
610 stored events is preserved, so the first next_event in the
611 containing list becomes the first to process.
612
613 An event of type internal is to be used when you want to
614 reliably distinguish an event inserted this way from any
615 external event.
616
617 enter_action() =
618 hibernate |
619 {hibernate, Hibernate :: hibernate()} |
620 timeout_action() |
621 reply_action()
622
623 These state transition actions can be invoked by returning them
624 from the state callback, from Module:init/1 or by giving them to
625 enter_loop/5,6.
626
627 Actions are executed in the containing list order.
628
629 Actions that set transition options override any previous of the
630 same type, so the last in the containing list wins. For example,
631 the last event_timeout() overrides any previous event_timeout()
632 in the list.
633
634 hibernate:
635 Sets the transition_option() hibernate() for this state
636 transition.
637
638 timeout_action() =
639 (Timeout :: event_timeout()) |
640 {timeout, Time :: event_timeout(), EventContent :: term()} |
641 {timeout,
642 Time :: event_timeout(),
643 EventContent :: term(),
644 Options :: timeout_option() | [timeout_option()]} |
645 {{timeout, Name :: term()},
646 Time :: generic_timeout(),
647 EventContent :: term()} |
648 {{timeout, Name :: term()},
649 Time :: generic_timeout(),
650 EventContent :: term(),
651 Options :: timeout_option() | [timeout_option()]} |
652 {state_timeout,
653 Time :: state_timeout(),
654 EventContent :: term()} |
655 {state_timeout,
656 Time :: state_timeout(),
657 EventContent :: term(),
658 Options :: timeout_option() | [timeout_option()]}
659
660 These state transition actions can be invoked by returning them
661 from the state callback, from Module:init/1 or by giving them to
662 enter_loop/5,6.
663
664 These timeout actions sets timeout transition options.
665
666 Timeout:
667 Short for {timeout,Timeout,Timeout}, that is, the time-out
668 message is the time-out time. This form exists to make the
669 state callback return value {next_state,NextState,New‐
670 Data,Timeout} allowed like for gen_fsm's
671
672 timeout:
673 Sets the transition_option() event_timeout() to Time with
674 EventContent and time-out options Options.
675
676 {timeout,Name}:
677 Sets the transition_option() generic_timeout() to Time for
678 Name with EventContent and time-out options Options.
679
680 state_timeout:
681 Sets the transition_option() state_timeout() to Time with
682 EventContent and time-out options Options.
683
684 reply_action() = {reply, From :: from(), Reply :: term()}
685
686 This state transition action can be invoked by returning it from
687 the state callback, from Module:init/1 or by giving it to
688 enter_loop/5,6.
689
690 It replies to a caller waiting for a reply in call/2. From must
691 be the term from argument {call,From} in a call to a state call‐
692 back.
693
694 Note that using this action from Module:init/1 or enter_loop/5,6
695 would be weird on the border of witchcraft since there has been
696 no earlier call to a state callback in this server.
697
698 init_result(StateType) =
699 {ok, State :: StateType, Data :: data()} |
700 {ok,
701 State :: StateType,
702 Data :: data(),
703 Actions :: [action()] | action()} |
704 ignore |
705 {stop, Reason :: term()}
706
707 For a succesful initialization, State is the initial state() and
708 Data the initial server data() of the gen_statem.
709
710 The Actions are executed when entering the first state just as
711 for a state callback, except that the action postpone is forced
712 to false since there is no event to postpone.
713
714 For an unsuccesful initialization, {stop,Reason} or ignore
715 should be used; see start_link/3,4.
716
717 state_enter_result(State) =
718 {next_state, State, NewData :: data()} |
719 {next_state,
720 State,
721 NewData :: data(),
722 Actions :: [enter_action()] | enter_action()} |
723 state_callback_result(enter_action())
724
725 State is the current state and it can not be changed since the
726 state callback was called with a state enter call.
727
728 next_state:
729 The gen_statem does a state transition to State, which has
730 to be the current state, sets NewData, and executes all
731 Actions.
732
733 event_handler_result(StateType) =
734 {next_state, NextState :: StateType, NewData :: data()} |
735 {next_state,
736 NextState :: StateType,
737 NewData :: data(),
738 Actions :: [action()] | action()} |
739 state_callback_result(action())
740
741 StateType is state_name() if callback mode is state_functions,
742 or state() if callback mode is handle_event_function.
743
744 next_state:
745 The gen_statem does a state transition to NextState (which
746 can be the same as the current state), sets NewData, and
747 executes all Actions.
748
749 state_callback_result(ActionType) =
750 {keep_state, NewData :: data()} |
751 {keep_state,
752 NewData :: data(),
753 Actions :: [ActionType] | ActionType} |
754 keep_state_and_data |
755 {keep_state_and_data, Actions :: [ActionType] | ActionType} |
756 {repeat_state, NewData :: data()} |
757 {repeat_state,
758 NewData :: data(),
759 Actions :: [ActionType] | ActionType} |
760 repeat_state_and_data |
761 {repeat_state_and_data, Actions :: [ActionType] | ActionType} |
762 stop |
763 {stop, Reason :: term()} |
764 {stop, Reason :: term(), NewData :: data()} |
765 {stop_and_reply,
766 Reason :: term(),
767 Replies :: [reply_action()] | reply_action()} |
768 {stop_and_reply,
769 Reason :: term(),
770 Replies :: [reply_action()] | reply_action(),
771 NewData :: data()}
772
773 ActionType is enter_action() if the state callback was called
774 with a state enter call and action() if the state callback was
775 called with an event.
776
777 keep_state:
778 The gen_statem keeps the current state, or does a state
779 transition to the current state if you like, sets NewData,
780 and executes all Actions. This is the same as
781 {next_state,CurrentState,NewData,Actions}.
782
783 keep_state_and_data:
784 The gen_statem keeps the current state or does a state tran‐
785 sition to the current state if you like, keeps the current
786 server data, and executes all Actions. This is the same as
787 {next_state,CurrentState,CurrentData,Actions}.
788
789 repeat_state:
790 The gen_statem keeps the current state, or does a state
791 transition to the current state if you like, sets NewData,
792 and executes all Actions. If the gen_statem runs with state
793 enter calls, the state enter call is repeated, see type
794 transition_option(), otherwise repeat_state is the same as
795 keep_state.
796
797 repeat_state_and_data:
798 The gen_statem keeps the current state and data, or does a
799 state transition to the current state if you like, and exe‐
800 cutes all Actions. This is the same as {repeat_state,Cur‐
801 rentData,Actions}. If the gen_statem runs with state enter
802 calls, the state enter call is repeated, see type transi‐
803 tion_option(), otherwise repeat_state_and_data is the same
804 as keep_state_and_data.
805
806 stop:
807 Terminates the gen_statem by calling Module:terminate/3 with
808 Reason and NewData, if specified.
809
810 stop_and_reply:
811 Sends all Replies, then terminates the gen_statem by calling
812 Module:terminate/3 with Reason and NewData, if specified.
813
814 All these terms are tuples or atoms and this property will hold
815 in any future version of gen_statem.
816
818 call(ServerRef :: server_ref(), Request :: term()) ->
819 Reply :: term()
820
821 call(ServerRef :: server_ref(),
822 Request :: term(),
823 Timeout ::
824 timeout() |
825 {clean_timeout, T :: timeout()} |
826 {dirty_timeout, T :: timeout()}) ->
827 Reply :: term()
828
829 Makes a synchronous call to the gen_statem ServerRef by sending
830 a request and waiting until its reply arrives. The gen_statem
831 calls the state callback with event_type() {call,From} and event
832 content Request.
833
834 A Reply is generated when a state callback returns with
835 {reply,From,Reply} as one action(), and that Reply becomes the
836 return value of this function.
837
838 Timeout is an integer > 0, which specifies how many milliseconds
839 to wait for a reply, or the atom infinity to wait indefinitely,
840 which is the default. If no reply is received within the speci‐
841 fied time, the function call fails.
842
843 Note:
844 For Timeout < infinity, to avoid getting a late reply in the
845 caller's inbox if the caller should catch exceptions, this func‐
846 tion spawns a proxy process that does the call. A late reply
847 gets delivered to the dead proxy process, hence gets discarded.
848 This is less efficient than using Timeout == infinity.
849
850
851 Timeout can also be a tuple {clean_timeout,T} or {dirty_time‐
852 out,T}, where T is the time-out time. {clean_timeout,T} works
853 like just T described in the note above and uses a proxy process
854 for T < infinity, while {dirty_timeout,T} bypasses the proxy
855 process which is more lightweight.
856
857 Note:
858 If you combine catching exceptions from this function with
859 {dirty_timeout,T} to avoid that the calling process dies when
860 the call times out, you will have to be prepared to handle a
861 late reply. So why not just let the calling process die?
862
863
864 The call can also fail, for example, if the gen_statem dies
865 before or during this function call.
866
867 cast(ServerRef :: server_ref(), Msg :: term()) -> ok
868
869 Sends an asynchronous event to the gen_statem ServerRef and
870 returns ok immediately, ignoring if the destination node or
871 gen_statem does not exist. The gen_statem calls the state call‐
872 back with event_type() cast and event content Msg.
873
874 enter_loop(Module :: module(),
875 Opts :: [debug_opt() | hibernate_after_opt()],
876 State :: state(),
877 Data :: data()) ->
878 no_return()
879
880 The same as enter_loop/6 with Actions = [] except that no
881 server_name() must have been registered. This creates an anony‐
882 mous server.
883
884 enter_loop(Module :: module(),
885 Opts :: [debug_opt() | hibernate_after_opt()],
886 State :: state(),
887 Data :: data(),
888 Server_or_Actions :: server_name() | pid() | [action()]) ->
889 no_return()
890
891 If Server_or_Actions is a list(), the same as enter_loop/6
892 except that no server_name() must have been registered and
893 Actions = Server_or_Actions. This creates an anonymous server.
894
895 Otherwise the same as enter_loop/6 with Server =
896 Server_or_Actions and Actions = [].
897
898 enter_loop(Module :: module(),
899 Opts :: [debug_opt() | hibernate_after_opt()],
900 State :: state(),
901 Data :: data(),
902 Server :: server_name() | pid(),
903 Actions :: [action()] | action()) ->
904 no_return()
905
906 Makes the calling process become a gen_statem. Does not return,
907 instead the calling process enters the gen_statem receive loop
908 and becomes a gen_statem server. The process must have been
909 started using one of the start functions in proc_lib. The user
910 is responsible for any initialization of the process, including
911 registering a name for it.
912
913 This function is useful when a more complex initialization pro‐
914 cedure is needed than the gen_statem behavior provides.
915
916 Module, Opts have the same meaning as when calling
917 start[_link]/3,4.
918
919 If Server is self() an anonymous server is created just as when
920 using start[_link]/3. If Server is a server_name() a named
921 server is created just as when using start[_link]/4. However,
922 the server_name() name must have been registered accordingly
923 before this function is called.
924
925 State, Data, and Actions have the same meanings as in the return
926 value of Module:init/1. Also, the callback module does not need
927 to export a Module:init/1 function.
928
929 The function fails if the calling process was not started by a
930 proc_lib start function, or if it is not registered according to
931 server_name().
932
933 reply(Replies :: [reply_action()] | reply_action()) -> ok
934
935 reply(From :: from(), Reply :: term()) -> ok
936
937 This function can be used by a gen_statem to explicitly send a
938 reply to a process that waits in call/2 when the reply cannot be
939 defined in the return value of a state callback.
940
941 From must be the term from argument {call,From} to the state
942 callback. A reply or multiple replies canalso be sent using one
943 or several reply_action()s from a state callback.
944
945 Note:
946 A reply sent with this function is not visible in sys debug out‐
947 put.
948
949
950 start(Module :: module(), Args :: term(), Opts :: [start_opt()]) ->
951 start_ret()
952
953 start(ServerName :: server_name(),
954 Module :: module(),
955 Args :: term(),
956 Opts :: [start_opt()]) ->
957 start_ret()
958
959 Creates a standalone gen_statem process according to OTP design
960 principles (using proc_lib primitives). As it does not get
961 linked to the calling process, this start function cannot be
962 used by a supervisor to start a child.
963
964 For a description of arguments and return values, see
965 start_link/3,4.
966
967 start_link(Module :: module(),
968 Args :: term(),
969 Opts :: [start_opt()]) ->
970 start_ret()
971
972 start_link(ServerName :: server_name(),
973 Module :: module(),
974 Args :: term(),
975 Opts :: [start_opt()]) ->
976 start_ret()
977
978 Creates a gen_statem process according to OTP design principles
979 (using proc_lib primitives) that is linked to the calling
980 process. This is essential when the gen_statem must be part of a
981 supervision tree so it gets linked to its supervisor.
982
983 The gen_statem process calls Module:init/1 to initialize the
984 server. To ensure a synchronized startup procedure,
985 start_link/3,4 does not return until Module:init/1 has returned.
986
987 ServerName specifies the server_name() to register for the
988 gen_statem. If the gen_statem is started with start_link/3, no
989 ServerName is provided and the gen_statem is not registered.
990
991 Module is the name of the callback module.
992
993 Args is an arbitrary term that is passed as the argument to Mod‐
994 ule:init/1.
995
996 * If option {timeout,Time} is present in Opts, the gen_statem
997 is allowed to spend Time milliseconds initializing or it
998 terminates and the start function returns {error,timeout}.
999
1000 * If option{hibernate_after,HibernateAfterTimeout} is present,
1001 the gen_statem process awaits any message for Hiber‐
1002 nateAfterTimeout milliseconds and if no message is received,
1003 the process goes into hibernation automatically (by calling
1004 proc_lib:hibernate/3).
1005
1006 * If option {debug,Dbgs} is present in Opts, debugging through
1007 sys is activated.
1008
1009 * If option {spawn_opt,SpawnOpts} is present in Opts,
1010 SpawnOpts is passed as option list to erlang:spawn_opt/2,
1011 which is used to spawn the gen_statem process.
1012
1013 Note:
1014 Using spawn option monitor is not allowed, it causes this func‐
1015 tion to fail with reason badarg.
1016
1017
1018 If the gen_statem is successfully created and initialized, this
1019 function returns {ok,Pid}, where Pid is the pid() of the
1020 gen_statem. If a process with the specified ServerName exists
1021 already, this function returns {error,{already_started,Pid}},
1022 where Pid is the pid() of that process.
1023
1024 If Module:init/1 fails with Reason, this function returns
1025 {error,Reason}. If Module:init/1 returns {stop,Reason} or
1026 ignore, the process is terminated and this function returns
1027 {error,Reason} or ignore, respectively.
1028
1029 stop(ServerRef :: server_ref()) -> ok
1030
1031 The same as stop(ServerRef, normal, infinity).
1032
1033 stop(ServerRef :: server_ref(),
1034 Reason :: term(),
1035 Timeout :: timeout()) ->
1036 ok
1037
1038 Orders the gen_statem ServerRef to exit with the specified Rea‐
1039 son and waits for it to terminate. The gen_statem calls Mod‐
1040 ule:terminate/3 before exiting.
1041
1042 This function returns ok if the server terminates with the
1043 expected reason. Any other reason than normal, shutdown, or
1044 {shutdown,Term} causes an error report to be issued through
1045 error_logger:format/2. The default Reason is normal.
1046
1047 Timeout is an integer > 0, which specifies how many milliseconds
1048 to wait for the server to terminate, or the atom infinity to
1049 wait indefinitely. Defaults to infinity. If the server does not
1050 terminate within the specified time, a timeout exception is
1051 raised.
1052
1053 If the process does not exist, a noproc exception is raised.
1054
1056 The following functions are to be exported from a gen_statem callback
1057 module.
1058
1060 Module:callback_mode() -> CallbackMode
1061
1062 Types:
1063
1064 CallbackMode = callback_mode() | [ callback_mode() |
1065 state_enter() ]
1066
1067 This function is called by a gen_statem when it needs to find
1068 out the callback mode of the callback module. The value is
1069 cached by gen_statem for efficiency reasons, so this function is
1070 only called once after server start and after code change, but
1071 before the first state callback in the current code version is
1072 called. More occasions may be added in future versions of
1073 gen_statem.
1074
1075 Server start happens either when Module:init/1 returns or when
1076 enter_loop/4-6 is called. Code change happens when Mod‐
1077 ule:code_change/4 returns.
1078
1079 The CallbackMode is either just callback_mode() or a list con‐
1080 taining callback_mode() and possibly the atom state_enter.
1081
1082 Note:
1083 If this function's body does not return an inline constant value
1084 the callback module is doing something strange.
1085
1086
1087 Module:code_change(OldVsn, OldState, OldData, Extra) -> Result
1088
1089 Types:
1090
1091 OldVsn = Vsn | {down,Vsn}
1092 Vsn = term()
1093 OldState = NewState = term()
1094 Extra = term()
1095 Result = {ok,NewState,NewData} | Reason
1096 OldState = NewState = state()
1097 OldData = NewData = data()
1098 Reason = term()
1099
1100 Note:
1101 This callback is optional, so callback modules need not export
1102 it. If a release upgrade/downgrade with Change={advanced,Extra}
1103 specified in the .appup file is made when code_change/4 is not
1104 implemented the process will crash with exit reason undef.
1105
1106
1107 This function is called by a gen_statem when it is to update its
1108 internal state during a release upgrade/downgrade, that is, when
1109 the instruction {update,Module,Change,...}, where
1110 Change={advanced,Extra}, is specified in the appup file. For
1111 more information, see OTP Design Principles.
1112
1113 For an upgrade, OldVsn is Vsn, and for a downgrade, OldVsn is
1114 {down,Vsn}. Vsn is defined by the vsn attribute(s) of the old
1115 version of the callback module Module. If no such attribute is
1116 defined, the version is the checksum of the Beam file.
1117
1118 OldState and OldData is the internal state of the gen_statem.
1119
1120 Extra is passed "as is" from the {advanced,Extra} part of the
1121 update instruction.
1122
1123 If successful, the function must return the updated internal
1124 state in an {ok,NewState,NewData} tuple.
1125
1126 If the function returns a failure Reason, the ongoing upgrade
1127 fails and rolls back to the old release. Note that Reason can
1128 not be an {ok,_,_} tuple since that will be regarded as a
1129 {ok,NewState,NewData} tuple, and that a tuple matching {ok,_} is
1130 an also invalid failure Reason. It is recommended to use an atom
1131 as Reason since it will be wrapped in an {error,Reason} tuple.
1132
1133 Also note when upgrading a gen_statem, this function and hence
1134 the Change={advanced,Extra} parameter in the appup file is not
1135 only needed to update the internal state or to act on the Extra
1136 argument. It is also needed if an upgrade or downgrade should
1137 change callback mode, or else the callback mode after the code
1138 change will not be honoured, most probably causing a server
1139 crash.
1140
1141 Module:init(Args) -> Result(StateType)
1142
1143 Types:
1144
1145 Args = term()
1146 Result(StateType) = init_result(StateType)
1147
1148 Whenever a gen_statem is started using start_link/3,4 or
1149 start/3,4, this function is called by the new process to ini‐
1150 tialize the implementation state and server data.
1151
1152 Args is the Args argument provided to that start function.
1153
1154 Note:
1155 Note that if the gen_statem is started trough proc_lib and
1156 enter_loop/4-6, this callback will never be called. Since this
1157 callback is not optional it can in that case be implemented as:
1158
1159 init(Args) -> erlang:error(not_implemented, [Args]).
1160
1161
1162 Module:format_status(Opt, [PDict,State,Data]) -> Status
1163
1164 Types:
1165
1166 Opt = normal | terminate
1167 PDict = [{Key, Value}]
1168 State = state()
1169 Data = data()
1170 Key = term()
1171 Value = term()
1172 Status = term()
1173
1174 Note:
1175 This callback is optional, so a callback module does not need to
1176 export it. The gen_statem module provides a default implementa‐
1177 tion of this function that returns {State,Data}.
1178
1179 If this callback is exported but fails, to hide possibly sensi‐
1180 tive data, the default function will instead return
1181 {State,Info}, where Info says nothing but the fact that for‐
1182 mat_status/2 has crashed.
1183
1184
1185 This function is called by a gen_statem process when any of the
1186 following apply:
1187
1188 *
1189 One of sys:get_status/1,2 is invoked to get the gen_statem
1190 status. Opt is set to the atom normal for this case.
1191
1192 *
1193 The gen_statem terminates abnormally and logs an error. Opt
1194 is set to the atom terminate for this case.
1195
1196 This function is useful for changing the form and appearance of
1197 the gen_statem status for these cases. A callback module wishing
1198 to change the sys:get_status/1,2 return value and how its status
1199 appears in termination error logs exports an instance of for‐
1200 mat_status/2, which returns a term describing the current status
1201 of the gen_statem.
1202
1203 PDict is the current value of the process dictionary of the
1204 gen_statem.
1205
1206 State is the internal state of the gen_statem.
1207
1208 Data is the internal server data of the gen_statem.
1209
1210 The function is to return Status, a term that contains the
1211 appropriate details of the current state and status of the
1212 gen_statem. There are no restrictions on the form Status can
1213 take, but for the sys:get_status/1,2 case (when Opt is normal),
1214 the recommended form for the Status value is [{data, [{"State",
1215 Term}]}], where Term provides relevant details of the gen_statem
1216 state. Following this recommendation is not required, but it
1217 makes the callback module status consistent with the rest of the
1218 sys:get_status/1,2 return value.
1219
1220 One use for this function is to return compact alternative state
1221 representations to avoid having large state terms printed in log
1222 files. Another use is to hide sensitive data from being written
1223 to the error log.
1224
1225 Module:StateName(enter, OldState, Data) -> StateEnterResult(StateName)
1226 Module:StateName(EventType, EventContent, Data) -> StateFunctionResult
1227 Module:handle_event(enter, OldState, State, Data) -> StateEnterRe‐
1228 sult(State)
1229 Module:handle_event(EventType, EventContent, State, Data) -> Han‐
1230 dleEventResult
1231
1232 Types:
1233
1234 EventType = event_type()
1235 EventContent = term()
1236 State = state()
1237 Data = NewData = data()
1238 StateEnterResult(StateName) = state_enter_result(StateName)
1239 StateFunctionResult = event_handler_result(state_name())
1240 StateEnterResult(State) = state_enter_result(State)
1241 HandleEventResult = event_handler_result(state())
1242
1243 Whenever a gen_statem receives an event from call/2, cast/2, or
1244 as a normal process message, one of these functions is called.
1245 If callback mode is state_functions, Module:StateName/3 is
1246 called, and if it is handle_event_function, Module:han‐
1247 dle_event/4 is called.
1248
1249 If EventType is {call,From}, the caller waits for a reply. The
1250 reply can be sent from this or from any other state callback by
1251 returning with {reply,From,Reply} in Actions, in Replies, or by
1252 calling reply(From, Reply).
1253
1254 If this function returns with a next state that does not match
1255 equal (=/=) to the current state, all postponed events are
1256 retried in the next state.
1257
1258 The only difference between StateFunctionResult and HandleEven‐
1259 tResult is that for StateFunctionResult the next state must be
1260 an atom, but for HandleEventResult there is no restriction on
1261 the next state.
1262
1263 For options that can be set and actions that can be done by
1264 gen_statem after returning from this function, see action().
1265
1266 When the gen_statem runs with state enter calls, these functions
1267 are also called with arguments (enter, OldState, ...) whenever
1268 the state changes. In this case there are some restrictions on
1269 the actions that may be returned: postpone() is not allowed
1270 since a state enter call is not an event so there is no event to
1271 postpone, and {next_event,_,_} is not allowed since using state
1272 enter calls should not affect how events are consumed and pro‐
1273 duced. You may also not change states from this call. Should you
1274 return {next_state,NextState, ...} with NextState =/= State the
1275 gen_statem crashes. It is possible to use {repeat_state, ...},
1276 {repeat_state_and_data,_} or repeat_state_and_data but all of
1277 them makes little sense since you immediately will be called
1278 again with a new state enter call making this just a weird way
1279 of looping, and there are better ways to loop in Erlang. You are
1280 advised to use {keep_state,...}, {keep_state_and_data,_} or
1281 keep_state_and_data since you can not change states from a state
1282 enter call anyway.
1283
1284 Note the fact that you can use throw to return the result, which
1285 can be useful. For example to bail out with
1286 throw(keep_state_and_data) from deep within complex code that
1287 can not return {next_state,State,Data} because State or Data is
1288 no longer in scope.
1289
1290 Module:terminate(Reason, State, Data) -> Ignored
1291
1292 Types:
1293
1294 Reason = normal | shutdown | {shutdown,term()} | term()
1295 State = state()
1296 Data = data()
1297 Ignored = term()
1298
1299 Note:
1300 This callback is optional, so callback modules need not export
1301 it. The gen_statem module provides a default implementation
1302 without cleanup.
1303
1304
1305 This function is called by a gen_statem when it is about to ter‐
1306 minate. It is to be the opposite of Module:init/1 and do any
1307 necessary cleaning up. When it returns, the gen_statem termi‐
1308 nates with Reason. The return value is ignored.
1309
1310 Reason is a term denoting the stop reason and State is the
1311 internal state of the gen_statem.
1312
1313 Reason depends on why the gen_statem is terminating. If it is
1314 because another callback function has returned, a stop tuple
1315 {stop,Reason} in Actions, Reason has the value specified in that
1316 tuple. If it is because of a failure, Reason is the error rea‐
1317 son.
1318
1319 If the gen_statem is part of a supervision tree and is ordered
1320 by its supervisor to terminate, this function is called with
1321 Reason = shutdown if both the following conditions apply:
1322
1323 * The gen_statem has been set to trap exit signals.
1324
1325 * The shutdown strategy as defined in the supervisor's child
1326 specification is an integer time-out value, not brutal_kill.
1327
1328 Even if the gen_statem is not part of a supervision tree, this
1329 function is called if it receives an 'EXIT' message from its
1330 parent. Reason is the same as in the 'EXIT' message.
1331
1332 Otherwise, the gen_statem is immediately terminated.
1333
1334 Notice that for any other reason than normal, shutdown, or
1335 {shutdown,Term}, the gen_statem is assumed to terminate because
1336 of an error and an error report is issued using error_log‐
1337 ger:format/2.
1338
1340 gen_event(3), gen_fsm(3), gen_server(3), proc_lib(3), supervisor(3),
1341 sys(3).
1342
1343
1344
1345Ericsson AB stdlib 3.4.5.1 gen_statem(3)