restructure to be a littel more flexible
[lwes-erlang/github-mirror.git] / src / lwes_channel_manager.erl
blob8318b860551d978e9a4ee3b2328f0a6e782d421a
1 -module (lwes_channel_manager).
3 -behaviour (gen_server).
5 -include_lib ("lwes.hrl").
6 -include_lib ("lwes_internal.hrl").
8 %% API
9 -export ([ start_link/0,
10 open_channel/1,
11 register_channel/2,
12 unregister_channel/1,
13 find_channel/1,
14 close_channel/1
15 ]).
17 %% gen_server callbacks
18 -export ([ init/1,
19 handle_call/3,
20 handle_cast/2,
21 handle_info/2,
22 terminate/2,
23 code_change/3
24 ]).
26 -define (TABLE, lwes_channels).
27 -record (state, {}).
29 %%====================================================================
30 %% API
31 %%====================================================================
32 start_link () ->
33 gen_server:start_link ( { local, ?MODULE }, ?MODULE, [], []).
35 open_channel (Channel) ->
36 lwes_channel_sup:open_channel (Channel).
38 register_channel (Channel, Pid) ->
39 gen_server:call (?MODULE, {reg, Channel, Pid}).
41 unregister_channel (Channel) ->
42 gen_server:call (?MODULE, {unreg, Channel}).
44 find_channel (Channel) ->
45 case ets:lookup (?TABLE, Channel) of
46 [] -> {error, not_open} ;
47 [{_Channel, Pid}] -> Pid
48 end.
50 close_channel (Channel) ->
51 gen_server:call (find_channel (Channel), stop).
53 %%====================================================================
54 %% gen_server callbacks
55 %%====================================================================
56 init ([]) ->
57 ets:new (?TABLE, [ named_table, { read_concurrency, true } ]),
58 { ok, #state {} }.
60 handle_call ({reg, Key, Val}, _From, State) ->
61 { reply, ets:insert (?TABLE, {Key, Val}), State };
62 handle_call ({unreg, Key}, _From, State) ->
63 {reply, ets:delete (?TABLE, Key), State };
64 handle_call (Request, From, State) ->
65 error_logger:warning_msg
66 ("lwes_channel_manager unrecognized call ~p from ~p~n",[Request, From]),
67 { reply, ok, State }.
69 handle_cast (Request, State) ->
70 error_logger:warning_msg
71 ("lwes_channel_manager unrecognized cast ~p~n",[Request]),
72 { noreply, State }.
74 handle_info (Request, State) ->
75 error_logger:warning_msg
76 ("lwes_channel_manager unrecognized info ~p~n",[Request]),
77 {noreply, State}.
79 terminate (_Reason, _State) ->
80 ets:delete (?TABLE),
81 ok.
83 code_change (_OldVsn, State, _Extra) ->
84 {ok, State}.
86 %%====================================================================
87 %% Internal functions
88 %%====================================================================
90 %%====================================================================
91 %% Test functions
92 %%====================================================================
93 -ifdef (TEST).
94 -include_lib ("eunit/include/eunit.hrl").
96 -endif.