deepukjayan

deepukjayan OP

update: phx_raw doesnt wotk. The Author himself have told that in one of the github issues.

I also tried it, just to make sure. Phoenix tries to handle all the requests and mess up with phx_raw.

Planning to look at custom dispatch…

0
Post #11
lud

lud

elixir-socket is for TCP (or UDP) sockets, not websockets. Which protocol does your device talk ? TCP or websockets ?

1
Post #12
idi527

idi527

:waving_hand:

I have an IOT device that would open a socket connection and start sending data. I really dont have control over how this device send data.

I used ranch for an iot project in the past. The devices were sending data over tcp, it worked roughly like this:

lib/iot_device_server.ex

defmodule IOTDeviceServer do
  @behaviour :ranch_protocol

  @impl true
  def start_link(ref, _socket, transport, opts) do
    pid = :proc_lib.spawn_link(__MODULE__, :init, [ref, transport, opts])
    {:ok, pid}
  end

  @doc false
  def init(ref, transport, _opts) do
    {:ok, socket} = :ranch.handshake(ref)
    __MODULE__.loop(socket, transport)
  end

  @doc false
  def loop(socket, transport) do
    case transport.recv(socket, 0, 5000) do
      {:ok, data} ->
        case handle_in(data) do
          {:reply, reply} ->
            transport.send(socket, reply)

          :noreply ->
            :ok
        end

        loop(socket, transport)

      _ ->
        :ok = transport.close(socket)
    end
  end

  @spec handle_in(binary) :: {:reply, iodata} | :noreply
  defp handle_in(<<...some markers..., _rest::bytes>> = binary_packet) do
    {:ok, packet, _rest} = IOTPacket.decode(binary_packet)
    # :ok = publish(packet) then it was published to a queue
    :noreply
  end
end

lib/application.ex

defmodule IOTDeviceServer.Application do
  @moduledoc false
  use Application

  def start(_type, _args) do
    config = Application.get_all_env(:iot_device_server)

    _children = [
        :ranch.child_spec(IOTDeviceServer, :ranch_tcp, [port: config[:port]], IOTDeviceServer, [])
    ]

    opts = [strategy: :one_for_one, name: IOTDeviceServer.Supervisor]
    Supervisor.start_link(children, opts)
  end
end
1
Post #13
deepukjayan

deepukjayan OP

You are right. My device use ws. What do you think about custom dispatch as a solution?

0
Post #14
lud

lud

Well if you need to use Phoenix then you have no choice but use custom dispatch.

Now, you could also just use cowboy and not Phoenix at all.

0
Post #15
— All posts loaded —