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

I created a worker that receives messages from Arduino in the: elixir_serial handler, but now I want to use it in the channel to transmit the received data, can I insert a socket in: 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 on how to improve your working code, for example. Is Gen_Server necessary?

+5
source share
1 answer

When you receive the data, transfer it to the channel 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 do not want to transfer the actual socket , because it can disappear at any time and reconnect to the new process. Use the topic you are subscribed to and you will pass on the data to anyone who wants to know about it.

+8
source

Source: https://habr.com/ru/post/1234428/


All Articles