我正在使用从我的设备切断比特流返回的elixir_serial,如何在elixir中将其连接到"\n"
分隔符?我在node.js node-serialport中找到了示例,但找不到在handle_info()中构建它的好例子?
def init([]) do
{:ok, serial} = Serial.start_link
Serial.open(serial, "/dev/cu.usbserial-A5026NYN")
Serial.set_speed(serial, 9600)
Serial.connect(serial)
Logger.debug "pid #{inspect serial}"
# @key_parts = []
{:ok, []}
end
def handle_info({:elixir_serial, serial, data}, state) do
Logger.debug "received :data #{data}"
{:noreply, state}
end
答案 0 :(得分:2)
您可以使用String.split/3:
iex(1)> String.split("foo\nbar", "\n")
["foo", "bar"]
您可以对此进行模式匹配,以获取所有数据,直到\n
:
iex(2)> [head | _tail] = String.split("foo\nbar", "\n")
["foo", "bar"]
iex(3)> head
"foo"
如果字符串中没有\n
,则原始字符串将在包含1个元素的列表中返回。
修改强>
要建立一个列表,直到收到\n
:
def init(_) do
{:ok, []}
end
def handle_info({:elixir_serial, serial, "\n"}, state) do
#Do stuff with state - be sure to reverse state as we have been building up using `[head | tail]`
# You can use Enum.reverse(state) for this.
{:noreply, state}
end
def handle_info({:elixir_serial, serial, data}, state) do
{:noreply, [data | state]}
end