我正在使用knewter/erlang-serial和Elixir,并尝试读取通过串行输入从Arduino接收控制信号后传入的JSON字符串(例如{"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
出现,然后连接这些内容?
:timer.send_interval 5000, serial_pid, {:send, control_signal}
)后,它只会发送一对值,因此不应该同时有多个值。 - optikfluffel