Fetch the repository succeeded.
// 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])
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。