[erlang-questions] Statem troubles

Vans S <>
Mon Oct 17 15:14:24 CEST 2016


Upgrade to R 19.1+. gen_statem should be marked unstable/beta in the docs. It changes too fast. 

    On Monday, October 17, 2016 5:41 AM, Schneider <> wrote:
 

 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}.

_______________________________________________
erlang-questions mailing list

http://erlang.org/mailman/listinfo/erlang-questions


   
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20161017/94472a17/attachment.html>


More information about the erlang-questions mailing list