读取串行输入,直到控制字符指示消息结束

时间:2015-05-12 06:19:07

标签: serial-port arduino elixir

我在Elixir上使用knewter/erlang-serial并尝试在收到控制信号后通过串行输入读取来自Arduino的JSON-String(例如{"temperature":20.40,"humidity":30.10}

defmodule MyApp.SerialInput do
  require Logger


  def start_link do
    serial_pid = :serial.start [{:open, "/dev/cu.usbmodem1431"}, {:speed, 115200}]

    control_signal = "1"
    :timer.send_interval 5000, serial_pid, {:send, control_signal}

    wait_for_new_values serial_pid
  end


  defp wait_for_new_values(serial_pid) do
    receive do
      {:data, jsonString} when is_binary(jsonString) ->
        Logger.debug "received :data #{inspect jsonString}"

    wait_for_new_values serial_pid
  end
end

我现在的问题是,我将串行输入分开(有时会立即通过):

[debug] received :data "{\"t"
[debug] received :data "emperature\":19.00,\"humidity\":42.00}\r\n"

[debug] received :data "{\"temperature\":19.60,\"humidity\":41"
[debug] received :data ".00}\r\n"

[debug] received :data "{\"temperature\":19.50,\"humidity\":40.90}\r\n"

[debug] received :data "{\"temperature\":19.50,\"humi"
[debug] received :data "dity\":40.90}\r\n"

[debug] received :data "{\"temperat"
[debug] received :data "ure\":19.50,\"humidity\":41.30}\r\n"

有没有办法告诉接收块等待,直到\r\n出现在字符串的末尾或者固定数量的字符或类似的东西?如果不是,那么在wait_for_new_values之前保持状态的最佳方式是什么,直到\r\n出现,然后才能将这些状态连接起来?

1 个答案:

答案 0 :(得分:5)

receive块是一个非常低级别的功能,所以它不能做这么专门的事情。

Elixir中的状态是显式的,可以通过可选参数(累加器(在本例中为acc)来实现。您可以稍后将累计值传递给递归调用,并仅在"\r\n"结束时打印它。

defp wait_for_new_values(serial_pid, acc \\ "") do
  receive do
    {:data, chunk} when is_binary(chunk) ->
      acc = acc + chunk
  end

  if String.ends_with? acc, "\r\n"
    Logger.debug "received :data #{inspect acc}"
    acc = ""
  end

  wait_for_new_values serial_pid, acc
end