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