[erlang-questions] Statem troubles

Schneider schneider@REDACTED
Mon Oct 17 11:41:00 CEST 2016


Dear list,

I feel really stupid this morning, trying to get the gen_statem working. 
Even the code_lock example given in the gen_statem behaviour 
documentation doesn't work:

Erlang/OTP 19 [erts-8.0.5] [source] [64-bit] [smp:2:2] 
[async-threads:10] [hipe] [kernel-poll:false]

Eshell V8.0.5  (abort with ^G)
1> c(code_lock).
{ok,code_lock}
2> code_lock:start_link("123").
Lock
** exception exit: {callback_mode,ok}


TIA,

Frans


-module(code_lock).
-behaviour(gen_statem).
-define(NAME, code_lock).

-export([start_link/1]).
-export([button/1]).
-export([init/1,callback_mode/0,terminate/3,code_change/4]).
-export([locked/3,open/3]).

start_link(Code) ->
     gen_statem:start_link({local,?NAME}, ?MODULE, Code, []).

button(Digit) ->
     gen_statem:cast(?NAME, {button,Digit}).

init(Code) ->
     do_lock(),
     Data = #{code => Code, remaining => Code},
     {ok,locked,Data}.

callback_mode() ->
     state_functions.

locked(
   cast, {button,Digit},
   #{code := Code, remaining := Remaining} = Data) ->
     case Remaining of
         [Digit] ->
	    do_unlock(),
             {next_state,open,Data#{remaining := Code},10000};
         [Digit|Rest] -> % Incomplete
             {next_state,locked,Data#{remaining := Rest}};
         _Wrong ->
             {next_state,locked,Data#{remaining := Code}}
     end.

open(timeout, _,  Data) ->
     do_lock(),
     {next_state,locked,Data};
open(cast, {button,_}, Data) ->
     do_lock(),
     {next_state,locked,Data}.

do_lock() ->
     io:format("Lock~n", []).
do_unlock() ->
     io:format("Unlock~n", []).

terminate(_Reason, State, _Data) ->
     State =/= locked andalso do_lock(),
     ok.
code_change(_Vsn, State, Data, _Extra) ->
     {ok,State,Data}.




More information about the erlang-questions mailing list