GO-serial

2020-05-24  本文已影响0人  Bug2Coder

GO串口通信实现

1、包名称github.com/tarm/serial

2、简单实现

package main

import (
    "fmt"
    "github.com/tarm/serial"
    "go/types"
    "log"
    "sync"
    "time"
)

type SerialManager struct {
    serialClient *serial.Port // 串口客户端
    SendCh       chan []byte  // 发送通道
    RecvCh       chan []byte  // 接收通道
}

//  构造函数
func NewSerial(Name string, Baud int) *SerialManager {
    c := serial.Config{Name: Name, Baud: Baud}
    //打开串口
    s, err := serial.OpenPort(&c)

    if err != nil {
        fmt.Println(err)
    }
    sendCh := make(chan []byte, 1000)
    recvCh := make(chan []byte, 1000)
    return &SerialManager{serialClient: s, SendCh: sendCh, RecvCh: recvCh}
}

// 读取特定长度的字节数据
func (sm SerialManager) read(len int, fullBuf *[]byte) error {
    if len <= 0 {
        return types.Error{}
    }
    l := 0
    for {
        var buf = make([]byte, 1)
        _, err := sm.serialClient.Read(buf)
        if err != nil {
            fmt.Println("err", err)
            return err
        }
        l += 1
        *fullBuf = append(*fullBuf, buf...)
        if l == len {
            return nil

        }

    }
}

// 数据读取
func (sm SerialManager) readThread() {
    go func() {
        for {
            var buf []byte
            err := sm.read(16, &buf)
            if err != nil {
                contiune
            }
            sm.RecvCh <- buf
        }
    }()
}

// 数据发送
func (sm SerialManager) sendThread() {
    go func() {
        for x := range sm.SendCh {
            fmt.Printf("发送数据:%q\n", x)
            _, err := sm.serialClient.Write(x)
            if err != nil {
                log.Fatal(err)
            }
            time.Sleep(time.Second)
        }
    }()
}

// 启动服务
func (sm SerialManager) Start() {
    go sm.readThread()
    go sm.sendThread()
}
上一篇下一篇

猜你喜欢

热点阅读