1 Star 0 Fork 0

cgutech-golang/core

Create your Gitee Account
Explore and code with more than 13.5 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
sream_serial.go 2.07 KB
Copy Edit Raw Blame History
// Copyright 2019 Yang ZhongXi
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package core
import (
"errors"
"time"
"github.com/tarm/serial"
)
// SerialPortStream 串口流操作类
type SerialPortStream struct {
receiver func(data []byte)
config *serial.Config
port *serial.Port
isOpened bool
}
// NewSerialPortStream 实例化串口操作类
func NewSerialPortStream(name string, baud int) *SerialPortStream {
v := &SerialPortStream{config: &serial.Config{Name: name, Baud: baud, ReadTimeout: time.Second}}
return v
}
// Open 打开串口
func (s *SerialPortStream) Open() error {
if s.isOpened {
return errors.New("串口已打开")
}
var err error
s.port, err = serial.OpenPort(s.config)
if err != nil {
return err
}
s.isOpened = true
go s.doWork()
return nil
}
// Close 关闭串口
func (s *SerialPortStream) Close() error {
if !s.isOpened {
return errors.New("串口未打开")
}
s.isOpened = false
s.port.Close()
return nil
}
// Write 写入数据
func (s *SerialPortStream) Write(data []byte) error {
if !s.isOpened {
return errors.New("串口未打开")
}
_, err := s.port.Write(data)
return err
}
// IsOpened 判断是否已打开
func (s *SerialPortStream) IsOpened() bool {
return s.isOpened
}
// SetReceiver 设置数据接收器
func (s *SerialPortStream) SetReceiver(receiver func(data []byte)) {
s.receiver = receiver
}
func (s *SerialPortStream) doWork() {
for s.isOpened {
buffer := make([]byte, 1024)
rLen, err := s.port.Read(buffer)
if err != nil {
continue
}
if rLen > 0 && s.receiver != nil {
s.receiver(buffer[:rLen])
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/cgutech-golang/core.git
git@gitee.com:cgutech-golang/core.git
cgutech-golang
core
core
v1.0.5

Search