anuaralfetahe

anuaralfetahe

Stumbled on the same problems.
So basically I created a GenServer which is wrapper for the WebSockex process.
Starting the GenServer will return the pid no matter if the WebSockex fails on the start_link or not. You actualy start the websocket connection in the handle_continue/2 func asynchrously.
Then you need to specify handle_initial_conn_failure: true option on the WebSockex start_link func so you can handle the error in the handle_disconnect/2 func. In the handle_disconnect/2 func you can return the tuple {:reconnect, state} for automatic reconnecting. I have added some process sleep there aswell. Here’s the code:

      def start_link(args) do
        GenServer.start_link(__MODULE__, args)
      end

      @impl GenServer
      def init(state) do
        {:ok, state, {:continue, :start_ws}}
      end

      @impl GenServer
      def handle_continue(:start_ws, state) do
        {:ok, pid} = WebSockex.start_link(url, __MODULE__, [], [handle_initial_conn_failure: true])

        subscribe(pid, state)

        {:noreply, state}
      end

      @impl WebSockex
      def handle_disconnect(_conn, state) do
        IO.puts("Disconnected!")

        # Wait before trying to reconnect.
        Process.sleep(5000)

        {:reconnect, state}
      end

Theres also an option called async on the WebSocex library but this does not seem to work with the sending frame or I am missing something.

1
Post #51
marschro

marschro

Hi all,

I try to understand something.

I have a iot device (shelly switch) that I am connected to via stateful websockex.

When I just disconnect the shelly from the power grid, so that it immediately stops and the socket connection stops, then according to the docs terminate is invoked on our side (the side that created the socket connection)

I have those two callbacks:

 def terminate({:remote, :closed} = reason, state) do
    Logger.error("[ ShellySocketConnector ] - Terminate: #{inspect(reason)}")
    {:ok, state}
  end

  def terminate(reason, state) do
    Logger.error("[ ShellySocketConnector ] - Terminate: #{inspect(reason)}")
    {:ok, state}
  end

… but I never get a log when terminating the socket connection by pulling the plug.

So is this expected behavior or am I doing something wrong. I would be happy to find a way, when a client disconnects or more in my case, terminates the socket connection.

Any hint appreciated.

cheers,
Martin

0
Post #52
LostKobrakai

LostKobrakai

Check the conditions required for terminate to be called.

1
Post #53
— All posts loaded —