Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use handle_info() from worker in Phoenix Channel?

I've created working worker, that gets messages from Arduino in :elixir_serial handler, but now I want to use it in Channel to broadcast received data, can I inject socket to :elixir_serial handle_info()?

defmodule MyApp.Serialport do
  require Logger
  use GenServer

  def start_link() do
    GenServer.start_link(__MODULE__, [])
  end

  def init([]) do
    work()
    {:ok, []}
  end

  defp work do
    {:ok, serial} = Serial.start_link
    Serial.open(serial, "/dev/tty.arduino")
    Serial.set_speed(serial, 9600)
    Serial.connect(serial)
    Logger.debug "pid #{inspect serial}"
  end

  def handle_info({:elixir_serial, serial, data}, state) do
    Logger.debug "received :data #{inspect data}"
    {:noreply, state}
  end
end

Do you have any suggestions about how to improve worker code, eg. Gen_Server is necessary?

like image 879
luzny Avatar asked Oct 24 '15 09:10

luzny


1 Answers

When you receive data, broadcast it to the channel's topic:

def handle_info({:elixir_serial, serial, data}, state) do
  Logger.debug "received :data #{inspect data}"
  MyApp.Endpoint.broadcast("some:topic", "serial_data", %{data: data}

  {:noreply, state}
end

You don't want to pass the actual socket because it could disappear any time and reconnect under a new process. Use the topic the socket is subscribed to instead and you will broadcast the data to anyone wanting to know about it.

like image 132
Chris McCord Avatar answered Oct 12 '22 06:10

Chris McCord