2 %%% Light Weight Event System (LWES)
5 %%% Event0 = lwes_event:new ("MyEvent"),
6 %%% Event1 = lwes_event:set_uint16 (Event0, "MyUint16", 25),
10 %%% Channel = lwes:open (emitter, Ip, Port)
11 %%% ok = lwes:emit (Channel, Event1).
13 %%% Listening via callback
15 %%% Channel = lwes:open (listener, Ip, Port)
16 %%% lwes:listen (Channel, Type, Fun, Accum).
18 %%% Fun is called for each event
22 %%% lwes:close (Channel)
26 -include_lib ("lwes.hrl").
29 -include_lib("eunit/include/eunit.hrl").
38 %%====================================================================
40 %%====================================================================
41 open (Type
, Ip
, Port
) ->
42 try
check_args (Type
, Ip
, Port
) of
43 { T
, I
, P
} -> lwes_channel:open (T
, I
, P
)
45 _:_
-> {error
, cant_open
}
48 emit (Channel
, Event
) ->
49 lwes_channel:send_to (Channel
, lwes_event:to_binary (Event
)).
52 % Callback function - function is called with an event in given format
53 % and the current state, it should return the next
58 % raw - callback is given raw udp structure, use lwes_event:from_udp to
60 % list - callback is given an #lwes_event record where the name is a
61 % binary, and the attributes is a proplist where keys are binaries,
62 % and values are either integers (for lwes int types), binaries
63 % (for lwes strings), true|false atoms (for lwes booleans),
64 % or 4-tuples (for lwes ip addresses)
65 % tagged - callback is given an #lwes_event record where the name is a
66 % binary, and the attributes are 3-tuples with the first element
67 % the type of data, the second the key as a binary and the
68 % third the values as in the list format
70 % Initial State is whatever you want
71 listen (Channel
, CallbackFunction
, EventType
, CallbackInitialState
)
72 when is_function (CallbackFunction
, 2),
73 EventType
=:= raw
; EventType
=:= tagged
; EventType
=:= list ->
74 lwes_channel:register_callback (Channel
, CallbackFunction
,
75 EventType
, CallbackInitialState
).
78 lwes_channel:close (Channel
).
80 %%====================================================================
82 %%====================================================================
84 check_args (Type
, Ip
, Port
) ->
85 { normalize_type (Type
), lwes_util:normalize_ip (Ip
), normalize_port (Port
) }.
87 normalize_port (Port
) when is_integer (Port
), Port
>= 0, Port
=< 65535 ->
89 normalize_port (Port
) when is_list (Port
) ->
90 list_to_integer (Port
);
92 erlang:error (badarg
).
94 normalize_type (Type
) when Type
=:= emitter
; Type
=:= listener
->
97 erlang:error (badarg
).
99 %%====================================================================
101 %%====================================================================