1 Star 0 Fork 0

李永键/golib

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
usart.go 1.82 KB
一键复制 编辑 原始数据 按行查看 历史
vinkim 提交于 2024-07-31 11:08 . 更新 usart
package tools
import (
"context"
"io"
"log"
"strings"
"github.com/jacobsa/go-serial/serial"
)
type VusartSct struct {
portName string
baudRate uint
}
func (vu *VusartSct) Initial(portName string, baudRate uint) {
vu.portName = portName
vu.baudRate = baudRate
}
func (vu *VusartSct) open() (io.ReadWriteCloser, error) {
options := serial.OpenOptions{
PortName: vu.portName,
BaudRate: vu.baudRate,
DataBits: 8,
StopBits: 1,
ParityMode: serial.PARITY_NONE,
MinimumReadSize: 4,
}
return serial.Open(options)
}
func (vu *VusartSct) Write(buf string) error {
// 写入数据
port, err := vu.open()
if err != nil {
return err
}
defer port.Close()
_, err = port.Write([]byte(buf))
return err
}
func (vu *VusartSct) Read(ctx context.Context) (chan string, error) {
ch := make(chan string, 128)
go func(ctx context.Context) {
port, err := vu.open()
if err != nil {
log.Println(err)
goto label_return
}
defer port.Close()
for {
select {
case <-ctx.Done():
goto label_return
default:
// 读取数据
buf := make([]byte, 1024)
n, err := port.Read(buf)
if err != nil {
log.Println(err)
break
}
ch <- string(buf[:n])
}
}
label_return:
close(ch)
}(ctx)
return ch, nil
}
func (vu *VusartSct) ReadSplit(ctx context.Context, sep string) (chan string, error) {
strs, err := vu.Read(ctx)
if err != nil {
return nil, err
}
ch := make(chan string)
go func() {
var tmpStr string = ""
for str := range strs {
if len(str) > 0 {
tmpStr += str
}
for {
crlf := strings.Index(tmpStr, sep)
if crlf >= 0 {
ch <- tmpStr[:crlf]
if len(tmpStr) > crlf+2 {
tmpStr = tmpStr[crlf+2:]
} else {
tmpStr = ""
}
} else {
break
}
}
}
close(ch)
}()
return ch, nil
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/lvinkim/golib.git
git@gitee.com:lvinkim/golib.git
lvinkim
golib
golib
cf58cc7da4a5

搜索帮助