我正在使用 github.com/go.bug.st/serial 从串行输入中读取。我等待输入流。然后,当外部机器向我发送数据时,我一次性获得一堆数据。问题是没有结束或停止字符。当流完成后,它只是停止发送数据。流是连续的,但不知道会持续多久。我假设我需要使用某种计时器来基本上在我开始阅读时启动某种计时器,然后如果我在两秒钟左右没有收到新输入,则终止该函数以便读取结束。我正在通过串行端口连接到外部机器。我按下这台机器上的按钮,此时它开始进行测试。测试完成后,它开始通过串行端口传输数据。据我所知,除了流停止之外,没有结束字符或指示它已完成。
通过串口传入的数据如下所示:
10.2,1
10,2
9.8,2
9.9,3
但是我将得到的行数未知并且可能会有所不同。
我不知道这是否是正确的方法,或者是否有一种惯用的方法来做到这一点。我确信我可以找到一些方法来做到这一点,但我认为必须有更好的方法。
下面是我的代码的一个非常简单的版本:
port := OpenPort()
scanner := bufio.NewScanner(port)
//the data does come in as lines:
scanner.Split(bufio.ScanLines)
mydata := make([]string,0)
for scanner.Scan() {
line := scanner.Text()
//assuming a timer needs to go here to say that we've started reading and to somehow
// stop once we are no longer getting data.
mydata := append(mydata, line)
}
//we never get here because we never stop scanning...
//now use the data once we are done reading the input:
graphFile := MakeGraph(mydata)
err := graph.Render(chart.PNG, graphFile)
if err != nil {panic(err)}
根据评论,我能够提出以下解决方案:
func ReadData(port serial.Port) string {
var started bool
byteBuff := bytes.NewBufferString("")
buff := make([]byte, 100)
for {
n, err := port.Read(buff)
if err != nil {panic(err)}
//if this is the first read, start the timeout
if !started{
started = true
err := port.SetReadTimeout(time.Second * 1)
if err != nil {panic(err)}
}
//0 means we hit the timeout.
if n == 0{
return byteBuff.String()
}
byteBuff.Write(buff[:n])
}
}
超时基本上每秒都会进行一次读取。由于线路上没有数据传入,因此将读取 0 字节。因此,只有在我们开始获取数据后才开始超时。谢谢@aMike 和@JimB。