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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With