forked from HAW-AI/VS-2012-WS-A4-PDTTDLFH
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreceiver.erl
64 lines (51 loc) · 1.92 KB
/
receiver.erl
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
-module(receiver).
-behaviour(gen_server).
%% API
-export([start/3]).
%% gen_server callbacks
-export([init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
-record(state, {coordinator_pid :: pid(),
receiving_socket,
own_ip}).
start(CoordinatorPID, ReceivingSocket, LocalIp) ->
gen_server:start(?MODULE, [CoordinatorPID, ReceivingSocket, LocalIp], []).
init([CoordinatorPID, ReceivingSocket, LocalIp]) ->
{ok, #state{coordinator_pid = CoordinatorPID, receiving_socket = ReceivingSocket, own_ip = LocalIp}}.
handle_cast(kill, State) ->
utility:log("receiver: received kill message"),
{stop, normal, State}; % calls :terminate and then shuts down
handle_cast(UnknownMessage, State) ->
utility:log(io:format("received unknown msg: ~p~n", [UnknownMessage])),
{noreply, State}.
%%% do everything required for a clean shutdown
terminate(_Reason, State) ->
utility:log("receiver: closed receiving socket"),
gen_udp:close(State#state.receiving_socket),
utility:log("receiver: terminated"),
ok.
handle_info({udp, _Socket, IPtuple, _InPortNo, Packet}, State) ->
case inet_parse:ntoa(IPtuple) == atom_to_list(State#state.own_ip) of
true ->
utility:log("receiver: received own packet");
false ->
Timestamp = utility:current_timestamp(),
Slot = utility:slot_of_timestamp(Timestamp),
utility:log("receiver: received packet~p~n",[IPtuple]),
utility:log("seams to be in slot ~p~n",[Slot]),
gen_server:cast(State#state.coordinator_pid, {received, Slot, Timestamp, Packet})
end,
{noreply, State};
%%% OTP gen_server boilerplate - ignore this
handle_info(Info, State) ->
utility:log("receiver: how about sending gen server a msg in a proper way: ~p~n",[Info]),
{noreply, State}.
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.