oscdispatch 0.1
I finished the first version of my OSCDispatch server in erlang.
The program defines a generic server and uses a callback function for the dispaching rules.
the oscdispatch.erl looks like this and uses a parameter in the module definition
-module(oscdispatch, [Dispatch]).
-export([start_server/0]).
-include("server_config.hrl").
start_server() ->
spawn( fun() -> server(?server_port) end ).
server(Port) ->
{ok, Socket} = gen_udp:open( Port, [binary] ),
io:format( "socked opened ~p~n ", [Socket]),
loop(Socket).
loop(Socket) ->
receive
{udp, Socket, Host, Port, Bin} ->
Adr = binary_to_list(util:getadr(Bin)),
io:format( "got: ~p~n", [{Host, Port, Adr}]),
Dispatch:dispatch( Adr, Bin ),
loop(Socket)
end.
to use the server a module has to define the dispatch/2 function and create an instance of the oscdispatch module.
-module(demo).
-export([start/0, dispatch/2]).
start() ->
S = oscdispatch:new(demo), %%% <- create an instance of the
%%% oscdispacht module using a parameter
S:start_server().
%% define where to send the messages
dispatch( "/color" ++ _, Bin ) ->
util:send( "localhost", 1234, Bin),
util:send( "localhost", 1235, Bin);
dispatch( "/osc/midi" ++ _, Bin ) ->
util:send( "localhost", 4002, Bin);
dispatch( _, _ ) ->
io:format( "UNKNOWN ~n" ).
in util erl some utility functions for splitting strings and sending udp messages are defined
-module(util).
-export([send/3, getadr/1]).
%% send message to host/port
send( Host, Port, Bin) ->
{ok, Socket} = gen_udp:open( 0, [binary] ),
ok = gen_udp:send( Socket, Host, Port, Bin ),
gen_udp:close( Socket ).
%% extract osc event address
getadr( Bin ) ->
Len = msglen( Bin, 0 ),
{Msg, _} = split_binary(Bin, Len),
Msg.
%% Get Length of the first \0 based string
msglen(<<0, _/binary>>, Len) -> Len;
msglen(Bin, Len) ->
{ _, Next} = split_binary( Bin, 1 ),
msglen( Next, Len + 1).
server_config.hrl is used to defined the listening port of the server app
-define(server_port, 4000).
See also:
sketch experiment 7 - osc events
Android Monome-Clone in Processing
Mapping linux input events to OSC
cocoa osc app