0

我有一个数显卡尺,可以通过串口发送测量值。该数据的格式类似于+123.45\r设备,可以随时发送。

所以我的程序需要“监听”第一个数据输入(总是以回车结束)并在这个之后直接关闭读取,然后再继续他自己的工作。

像CoolTermPutty这样的专用终端可以完美地处理这些不可预测的输入……但我不知道如何在 Go 中做到这一点(即使使用 cgo)。

我的系统

  • OS X 10.9.5
  • 去 1.4.2 达尔文/AMD64

设备

  • 4800 波特
  • 7 个数据位
  • 偶校验
  • 2 个停止位
  • DTR

我的实际代码

……这行不通……</p>

package main

import (
    "bufio"
    "fmt"
    "os"
    "syscall"
    "unsafe"
)

func main() {
    f, err := os.OpenFile("/dev/tty.PL2303-00003014", syscall.O_RDWR+syscall.O_NOCTTY+syscall.O_NDELAY+syscall.O_NONBLOCK, 0666)
    if err != nil {
        panic(err)
    }
    defer f.Close()

    // Init terminal for 4800 7E2.
    t := &syscall.Termios{
        // Enable parity checking, strip to 7 bits, CR to NL, outgoing software flow control.
        Iflag: syscall.INPCK + syscall.ISTRIP + syscall.ICRNL + syscall.IXON,
        // Set 4800 bauds, 7 data bits, even parity, 2 stop bits, DTR.
        Cflag:  syscall.B4800 + syscall.CS7 + syscall.PARENB + syscall.CSTOPB + syscall.TIOCM_DTR + syscall.CREAD + syscall.CLOCAL + syscall.CSIZE,
        Cc:     [20]uint8{syscall.VMIN: 1},
        Ispeed: syscall.B4800,
        Ospeed: syscall.B4800,
    }

    _, _, errno := syscall.Syscall(syscall.SYS_FCNTL, uintptr(f.Fd()), uintptr(syscall.F_SETFL), uintptr(unsafe.Pointer(t)))
    if errno != 0 {
        panic("syscall error: " + errno.Error())
    }

    // Read until the first new line byte (\r is converted to \n with the ICRNL flag).
    fr := bufio.NewReader(f)
    line, err := fr.ReadBytes('\n')
    if err != nil {
        panic(err)
    }
    fmt.Println(string(line))
}
4

0 回答 0