summaryrefslogtreecommitdiff
path: root/tda.erl
blob: b417d9a2b76f3f129c71944f588b31fc289d05e3 (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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
-module(tda).

-export([start/0, client/1, stop/0]).
-export([ext/0, co/0]).

-define(TIMEOUT, 300000).
-define(CONNECT_TIMEOUT, 3000).
-define(HOST, "192.168.240.20").
-define(PORT, 33333).

start() -> register(tdaPid, spawn(?MODULE, client, [{dial, ?HOST, ?PORT}])).

stop() -> tdaPid ! {logout}.
ext() -> tdaPid ! {ext}.
co() -> tdaPid ! {co}.

client({dial, Host, Port}) ->
	io:format("Dial ~p:~p~n", [Host, Port]),
	Conn = gen_tcp:connect(Host, Port,
			       [binary, {active, once}, {packet, 2}],
			       ?CONNECT_TIMEOUT),
	client(Conn);
client({ok, Sock}) ->
	io:format("Connected~n", []),
	tdaPid ! {login},
	loop(Sock);
client({error, Reason}) ->
	io:format("Error: ~p~n", [Reason]),
	{error, Reason}.

loop(Sock) ->
	inet:setopts(Sock, [{active, once}]),
	io:format("Loop~n", []),
	receive
		{login} ->
			io:format("Login~n", []),
			{ok, Hello} = acse:associate(),
			gen_tcp:send(Sock, Hello),
			loop(Sock);
		{logout} ->
			io:format("Logout~n", []),
			{ok, Bye} = acse:release(),
			gen_tcp:send(Sock, Bye),
			loop(Sock);
		{ext} ->
			io:format("Request Ext lines~n", []),
			{ok, Rq} = rose:invoke({present, 2},
				{local, 51}, csta:ext_lines()),
			io:format("Send: ~p~n", [Rq]),
			gen_tcp:send(Sock, Rq),
			loop(Sock);
		{co} ->
			io:format("Request CO lines~n", []),
			{ok, Rq} = rose:invoke({present, 2},
				{local, 51}, csta:co_lines()),
			io:format("Send: ~p~n", [Rq]),
			gen_tcp:send(Sock, Rq),
			loop(Sock);
		{tcp, Sock, Msg} ->
			io:format("Reply ~p~n", [Msg]),
			case decode(Sock, Msg) of
				ok -> loop(Sock);
				error -> gen_tcp:close(Sock),
					 error
			end;
		{tcp_closed, _} ->
			io:format("Connection closed~n", []),
			closed
	after ?TIMEOUT ->
		gen_tcp:close(Sock),
		timeout
	end.

decode(Sock, Msg) ->
	case dispatch(Msg) of
		rose ->
			{ok, Rose} = rose:decode(Msg),
			io:format("ROSE> ~p~n", [Rose]),
			case rose:dispatch(Rose) of
				{ok, Result} ->
					gen_tcp:send(Sock, Result);
				{result, Msg} ->
					io:format("Result: ~p~n", [Msg]),
					ok;
				{ok} -> ok
			end;
		acse ->
			{ok, Acse} = acse:decode(Msg),
			io:format("ACSE> ~p~n", [Acse]),
			acse:accepted(Acse)
	end.

dispatch(<<Head:8,_/binary>>) ->
	case Head of
		 96 -> acse;	% aarq
		 97 -> acse;	% aare
		 98 -> acse;	% rlrq
		 99 -> acse;	% rlre
		100 -> acse;	% abrt
		161 -> rose;	% invoke
		162 -> rose;	% returnResult
		163 -> rose;	% returnError
		164 -> rose	% reject
	end.