summaryrefslogtreecommitdiff
path: root/src/pbx_conn.erl
blob: f819fdd3d398a958434e141d8ef6d8d423180424 (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
-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, []),
	gen_tcp:connect(Host, Port, [binary, {packet, 2}]).

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

handle_cast({ok, Reply}, Socket) ->
	io:format("Send: ~p~n", [Reply]),
	gen_tcp:send(Socket, Reply),
	{noreply, Socket};
handle_cast({error, Reason}, Socket) ->
	{stop, Reason, Socket}.

handle_info({tcp, _, Data}, Socket) ->
	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) ->
	pbx_pdu:delete_handler(pbx_acse, []),
	gen_tcp:close(Socket).

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

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