summaryrefslogtreecommitdiff
path: root/src/pbx_conn.erl
blob: bb5f478d020b801c476e7f0852e5b6464ce64f57 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
-module(pbx_conn).
-behaviour(gen_server).
-define(SERVER, ?MODULE).

-export([start_link/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
	 terminate/2, code_change/3]).
-export([send/1]).

-include("config.hrl").

start_link() ->
	gen_server:start_link({local, ?SERVER}, ?MODULE, [?HOST, ?PORT], []).

init([Host, Port]) ->
	pbx_pdu:start_link(),
	pbx_pdu:add_handler(pbx_acse, []),
	pbx_pdu:add_handler(pbx_rose, []),
	send(pbx_acse:encode(associate)),
	gen_tcp:connect(Host, Port, [binary, {packet, 2}]).

handle_call(_Request, _From, Socket) ->
	{reply, ok, Socket}.

handle_cast({ok, Reply}, Socket) ->
	gen_tcp:send(Socket, Reply),
	{noreply, Socket};
handle_cast({error, Reason}, Socket) ->
	{stop, Reason, Socket}.

handle_info({tcp, _, Data}, Socket) ->
	%pbx_acse:decode(Data),
	Pdu = pbx_pdu:decode(Data),
	io:format("PDU ~p~n", [Pdu]),
	gen_event:notify(pbx_pdu, Pdu),
	{noreply, Socket};

handle_info({tcp_closed, _}, Socket) ->
	{stop, normal, Socket}.

terminate(_Reason, Socket) ->
	send(pbx_acse:encode(release)),
	gen_tcp:close(Socket).

code_change(_OldVsn, Socket, _Extra) ->
	{ok, Socket}.

send(Reply) ->
	gen_server:cast(?SERVER, Reply).