gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:19:13 25 4
gpt4 key购买 nike

我正在使用 knewter/erlang-serial使用 Elixir 并尝试读取一个 JSON 字符串(例如 {"temperature":20.40,"humidity":30.10} 在收到控制信号后通过串行输入从 Arduino 传入:

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"

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

最佳答案

receive block 是一个非常低级的函数,因此它不能做这样专门的事情。

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

关于serial-port - 读取串行输入,直到控制字符指示消息结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30183214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com