Skip to content

Instantly share code, notes, and snippets.

@samaaron
Last active September 27, 2021 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samaaron/42db4776aa33d92a95e3a98e8374f09e to your computer and use it in GitHub Desktop.
Save samaaron/42db4776aa33d92a95e3a98e8374f09e to your computer and use it in GitHub Desktop.
TCP kill switch
-module(keepalive).
-export([start/1, init/1, loop/1]).
start(DaemonPortNum) ->
spawn_link(?MODULE, init, [DaemonPortNum]).
init(DaemonPortNum) ->
io:format("connecting to Daemon via TCP...~n", []),
{ok, DaemonSocket} = gen_tcp:connect({127,0,0,1}, DaemonPortNum, [
binary,
{active, true},
{packet, 4},
{keepalive, false}
]),
KillSwitch = erlang:send_after(5000, self(), trigger_kill_switch),
io:format("Waiting for keepalive messages...", []),
loop(KillSwitch).
loop(KillSwitch) ->
receive
{tcp, _Socket, Bin} ->
try osc:decode(Bin) of
{cmd, ["/system/keepalive"]} ->
io:format("Received keepalive message from Daemon ~n", []),
erlang:cancel_timer(KillSwitch),
NewKillSwitch = erlang:send_after(5000, self(), trigger_kill_switch),
?MODULE:loop(NewKillSwitch);
Other ->
io:format("Unexpected message from Daemon:~p~n", [Other]),
?MODULE:loop(KillSwitch)
catch
Class:Term:Trace ->
io:format("keepalive process: Error decoding OSC: ~p~n~p:~p~n~p~n",
[Bin, Class, Term, Trace]),
?MODULE:loop(KillSwitch)
end;
trigger_kill_switch ->
io:format("Tau kill switch activated. Shutting down....", []),
init:stop();
Any ->
io:format("Tau keepalive received unexpected message: ~p~n", [Any]),
?MODULE:loop(KillSwitch)
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment