diff --git a/src/wsio_handler.erl b/src/wsio_handler.erl index 7207d7e..affaa98 100644 --- a/src/wsio_handler.erl +++ b/src/wsio_handler.erl @@ -12,6 +12,7 @@ init(R, _) -> websocket_init(S) -> Ref = st:lookup(wsbus), + erlang:send_after(?TTL_PING, self(), ping), {ok, S#{wsbus => nil, ref_wsbus => Ref}}. websocket_handle({text, <>}, S) -> @@ -22,9 +23,9 @@ websocket_handle({text, <>}, S) -> {ok, S} end; websocket_handle({json, #{<<"ref">> := Ref}}, #{wsbus := nil} = S) -> - {[{text, jsx:encode(#{<<"ref">> => Ref, <<"wsio-code">> => 0})}], S}; + {[{text, jsx:encode(#{<<"ref">> => Ref, <<"wsio-code">> => <<"0">>})}], S}; websocket_handle({json, Data}, #{wsbus := BUS} = S) -> - gen_server:cast(BUS, {call, Data, self()}), + gen_server:cast(BUS, {call, Data}), {ok, S}; websocket_handle(_, State) -> {ok, State}. @@ -42,10 +43,20 @@ websocket_info({send, List}, S) when is_list(List) -> {List, S}; websocket_info({'DOWN', _, process, PID, _}, #{wsbus := PID} = S) -> {ok, S#{wsbus => nil, ref_wsbus => st:lookup(wsbus)}}; +websocket_info({_, {send, _} = Msg}, S) -> + websocket_info(Msg, S); websocket_info({_, {Ref, {error, notfound}}}, #{ref_wsbus := Ref} = S) -> {ok, S#{ref_wsbus => st:lookup(wsbus)}}; -websocket_info({_, {Ref, {ok, PID}}}, #{ref_wsbus := Ref} = S) -> - erlang:monitor(process, PID), - {ok, maps:remove(ref_wsbus, S#{wsbus => PID})}; +websocket_info({_, {Ref, {ok, Service}}}, #{wsbus := nil, ref_wsbus := Ref} = S) -> + try gen_server:call(Service, {new, self()}) of + {ok, PID} -> + erlang:monitor(process, PID), + {ok, maps:remove(ref_wsbus, S#{wsbus => PID})}; + {error, ignored} -> + {ok, S#{ref_wsbus => st:lookup(wsbus)}} + catch + _:_ -> + {ok, S#{ref_wsbus => st:lookup(wsbus)}} + end; websocket_info(_, S) -> {ok, S}.