Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b3711b62ad | |||
| ff4afcdddb | |||
| 27af1097f9 | |||
| 80d2794531 | |||
| 070b7685d5 | |||
|
|
f12391c01f | ||
|
|
8f447ebc07 | ||
|
|
20a47944cf | ||
|
|
9710c814f6 |
54
.gitignore
vendored
Normal file
54
.gitignore
vendored
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
# Binaries for programs and plugins
|
||||||
|
*.exe
|
||||||
|
*.exe~
|
||||||
|
*.dll
|
||||||
|
*.so
|
||||||
|
*.dylib
|
||||||
|
|
||||||
|
# Test binary, built with `go test -c`
|
||||||
|
*.test
|
||||||
|
|
||||||
|
# Output of the go coverage tool, specifically when used with LiteIDE
|
||||||
|
*.out
|
||||||
|
|
||||||
|
# Dependency directories (remove the comment below to include it)
|
||||||
|
# vendor/
|
||||||
|
|
||||||
|
# Go workspace file
|
||||||
|
go.work
|
||||||
|
|
||||||
|
# IDE directories and files
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
|
|
||||||
|
# OS generated files
|
||||||
|
.DS_Store
|
||||||
|
.DS_Store?
|
||||||
|
._*
|
||||||
|
.Spotlight-V100
|
||||||
|
.Trashes
|
||||||
|
ehthumbs.db
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# Test directory
|
||||||
|
testprogram/
|
||||||
|
|
||||||
|
# Build artifacts
|
||||||
|
*.tmp
|
||||||
|
*.temp
|
||||||
|
build/
|
||||||
|
dist/
|
||||||
|
|
||||||
|
# Log files
|
||||||
|
*.log
|
||||||
|
*.err
|
||||||
|
*.out.log
|
||||||
|
|
||||||
|
# Configuration files with sensitive information
|
||||||
|
*.local
|
||||||
|
*.secret
|
||||||
|
*.env
|
||||||
|
.claude/settings.local.json
|
||||||
169
CLAUDE.md
Normal file
169
CLAUDE.md
Normal file
@@ -0,0 +1,169 @@
|
|||||||
|
# CLAUDE.md
|
||||||
|
|
||||||
|
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||||
|
|
||||||
|
## 开发者约束要求
|
||||||
|
|
||||||
|
### 语言与地区
|
||||||
|
- **主要交互语言**: 中文(简体)
|
||||||
|
- **开发者所在地**: 中国大陆
|
||||||
|
- **时区**: GMT+8(北京时间)
|
||||||
|
|
||||||
|
### AI Agent交互规范
|
||||||
|
- 使用中文进行所有AI Agent交互和代码解释
|
||||||
|
- 文档和注释可以使用英文(保持与现有代码库风格一致)
|
||||||
|
- 技术术语遵循行业标准翻译
|
||||||
|
|
||||||
|
### Git提交规范
|
||||||
|
- **提交信息必须包含中文说明**:确保每个commit都有清晰的中文描述
|
||||||
|
- 提交信息格式:`<类型>: <主题>`,主题使用中文
|
||||||
|
- 提交信息应简洁明了,准确描述变更内容
|
||||||
|
- 类型可以是:feat(新功能)、fix(修复)、docs(文档)、style(样式)、refactor(重构)、test(测试)、chore(构建过程或辅助工具的变动)
|
||||||
|
|
||||||
|
### 代码库使用注意事项
|
||||||
|
- 本项目是一个开源Go库,主要用于跨平台串口通信
|
||||||
|
- 遵守BSD 3-clause开源许可证
|
||||||
|
- 保持代码的跨平台兼容性和简洁性
|
||||||
|
- 所有修改需要通过GitHub PR流程进行
|
||||||
|
|
||||||
|
### 代码库使用注意事项
|
||||||
|
- 本项目是一个开源Go库,主要用于跨平台串口通信
|
||||||
|
- 遵守BSD 3-clause开源许可证
|
||||||
|
- 保持代码的跨平台兼容性和简洁性
|
||||||
|
- 所有修改需要通过GitHub PR流程进行
|
||||||
|
|
||||||
|
## Project Overview
|
||||||
|
|
||||||
|
**go-serial** is a cross-platform serial port communication library for Go. It provides a simple and consistent API for accessing serial ports on Windows, macOS, Linux, and other Unix-like systems.
|
||||||
|
|
||||||
|
## Key Features
|
||||||
|
|
||||||
|
- Cross-platform support (Windows, macOS, Linux, FreeBSD, OpenBSD)
|
||||||
|
- Simple API for opening and configuring serial ports
|
||||||
|
- Support for modem control lines (RTS, DTR, CTS, DSR, etc.)
|
||||||
|
- USB device enumeration with VID/PID and serial number detection
|
||||||
|
- Read/write timeout support
|
||||||
|
- Parity, data bits, stop bits configuration
|
||||||
|
- Break signal support
|
||||||
|
|
||||||
|
## Package Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
go-serial/
|
||||||
|
├── serial.go # Core API definition (Port interface, Mode, errors)
|
||||||
|
├── serial_*.go # Platform-specific implementations (windows, darwin, linux, bsd, wasm)
|
||||||
|
├── enumerator/ # USB serial port enumeration with detailed info
|
||||||
|
│ ├── enumerator.go # Core enumerator API
|
||||||
|
│ └── usb_*.go # Platform-specific USB enumeration
|
||||||
|
├── portlist/ # Simple port listing implementation
|
||||||
|
├── unixutils/ # Unix-specific utility functions
|
||||||
|
└── *.test.go # Example and test files
|
||||||
|
```
|
||||||
|
|
||||||
|
## Core API
|
||||||
|
|
||||||
|
### Opening a Serial Port
|
||||||
|
|
||||||
|
```go
|
||||||
|
import "go.bug.st/serial"
|
||||||
|
|
||||||
|
mode := &serial.Mode{
|
||||||
|
BaudRate: 115200,
|
||||||
|
Parity: serial.EvenParity,
|
||||||
|
DataBits: 7,
|
||||||
|
StopBits: serial.OneStopBit,
|
||||||
|
}
|
||||||
|
port, err := serial.Open("/dev/ttyUSB0", mode)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
defer port.Close()
|
||||||
|
```
|
||||||
|
|
||||||
|
### Reading and Writing
|
||||||
|
|
||||||
|
```go
|
||||||
|
// Write data
|
||||||
|
n, err := port.Write([]byte("Hello"))
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read data with timeout
|
||||||
|
buff := make([]byte, 100)
|
||||||
|
port.SetReadTimeout(5 * time.Second)
|
||||||
|
n, err := port.Read(buff)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Getting Port List
|
||||||
|
|
||||||
|
```go
|
||||||
|
// Simple port list
|
||||||
|
ports, err := serial.GetPortsList()
|
||||||
|
|
||||||
|
// Detailed port list with USB info
|
||||||
|
import "go.bug.st/serial/enumerator"
|
||||||
|
ports, err := enumerator.GetDetailedPortsList()
|
||||||
|
for _, port := range ports {
|
||||||
|
if port.IsUSB {
|
||||||
|
fmt.Printf("USB Port: %s (VID:%s PID:%s Serial:%s)\n",
|
||||||
|
port.Name, port.VID, port.PID, port.SerialNumber)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Common Commands
|
||||||
|
|
||||||
|
### Testing
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go test -v ./... # Run all tests
|
||||||
|
go test -v ./enumerator # Run enumerator tests specifically
|
||||||
|
```
|
||||||
|
|
||||||
|
### Documentation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go doc go.bug.st/serial # Show package documentation
|
||||||
|
go doc go.bug.st/serial.Port # Show Port interface documentation
|
||||||
|
```
|
||||||
|
|
||||||
|
### Generating Windows Syscall Bindings
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd go-serial
|
||||||
|
go generate
|
||||||
|
```
|
||||||
|
|
||||||
|
## Platform-Specific Notes
|
||||||
|
|
||||||
|
- **Windows**: Uses Windows API for serial communication, supports most USB-to-serial adapters
|
||||||
|
- **macOS**: Uses IOKit framework (requires cgo) for USB enumeration
|
||||||
|
- **Linux**: Supports standard serial ports and USB-to-serial devices via `/dev/tty*`
|
||||||
|
- **Unix-like systems**: Use termios API for configuration
|
||||||
|
- **Wasm**: Limited support (enumeration not implemented)
|
||||||
|
|
||||||
|
## Recent Changes
|
||||||
|
|
||||||
|
The repository has recent commits related to:
|
||||||
|
- Fixing serial port getter methods
|
||||||
|
- Making Windows internal constants private
|
||||||
|
- Fixing incorrect masks for modem status bits on Windows
|
||||||
|
- Renaming variables to match documentation
|
||||||
|
- Windows port enumeration improvements
|
||||||
|
- **Linux系统下串口Close方法深度优化**:
|
||||||
|
- 优化了资源释放顺序,先释放独占访问权,再关闭实际的端口句柄
|
||||||
|
- 添加了句柄有效性检查,避免对无效句柄进行操作
|
||||||
|
- 确保所有资源都能正确清理,包括句柄和信号管道
|
||||||
|
- 改进了错误处理机制,确保只返回第一个错误
|
||||||
|
- 为所有方法添加了端口状态检查,确保在端口关闭后立即返回PortClosed错误
|
||||||
|
- 统一了错误处理格式,使用PortError类型包装系统错误
|
||||||
|
- 优化了Read方法的错误处理和超时逻辑
|
||||||
|
- 为Write、Break、SetMode、SetDTR、SetRTS和GetModemStatusBits方法添加了端口状态检查
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
BSD 3-clause license - see LICENSE file for details.
|
||||||
165
serial_unix.go
165
serial_unix.go
@@ -30,35 +30,48 @@ type unixPort struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (port *unixPort) Close() error {
|
func (port *unixPort) Close() error {
|
||||||
|
// 原子操作检查并设置端口关闭状态
|
||||||
if !atomic.CompareAndSwapUint32(&port.opened, 1, 0) {
|
if !atomic.CompareAndSwapUint32(&port.opened, 1, 0) {
|
||||||
return nil
|
return nil // 端口已经关闭,直接返回
|
||||||
}
|
}
|
||||||
|
|
||||||
// Close port
|
var firstErr error
|
||||||
port.releaseExclusiveAccess()
|
|
||||||
if err := unix.Close(port.handle); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
|
// 发送关闭信号以取消所有待处理的读操作
|
||||||
if port.closeSignal != nil {
|
if port.closeSignal != nil {
|
||||||
// Send close signal to all pending reads (if any)
|
if _, err := port.closeSignal.Write([]byte{0}); err != nil && firstErr == nil {
|
||||||
port.closeSignal.Write([]byte{0})
|
firstErr = err
|
||||||
|
|
||||||
// Wait for all readers to complete
|
|
||||||
port.closeLock.Lock()
|
|
||||||
defer port.closeLock.Unlock()
|
|
||||||
|
|
||||||
// Close signaling pipe
|
|
||||||
if err := port.closeSignal.Close(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
|
||||||
|
// 检查句柄是否有效,然后执行关闭操作
|
||||||
|
if port.handle != -1 {
|
||||||
|
// 释放独占访问权 - 应在关闭handle之前完成
|
||||||
|
if err := port.releaseExclusiveAccess(); err != nil && firstErr == nil {
|
||||||
|
firstErr = err
|
||||||
|
}
|
||||||
|
|
||||||
|
// 关闭实际的端口句柄 - 这将解除任何挂起的读写操作
|
||||||
|
if err := unix.Close(port.handle); err != nil && firstErr == nil {
|
||||||
|
firstErr = err
|
||||||
|
}
|
||||||
|
|
||||||
|
port.handle = -1 // 标记句柄无效
|
||||||
|
}
|
||||||
|
|
||||||
|
// 关闭信号管道
|
||||||
|
if port.closeSignal != nil {
|
||||||
|
if err := port.closeSignal.Close(); err != nil && firstErr == nil {
|
||||||
|
firstErr = err
|
||||||
|
}
|
||||||
|
port.closeSignal = nil // 清除指针
|
||||||
|
}
|
||||||
|
|
||||||
|
return firstErr
|
||||||
}
|
}
|
||||||
|
|
||||||
func (port *unixPort) Read(p []byte) (int, error) {
|
func (port *unixPort) Read(p []byte) (int, error) {
|
||||||
port.closeLock.RLock()
|
// 首先检查端口是否已经关闭
|
||||||
defer port.closeLock.RUnlock()
|
|
||||||
if atomic.LoadUint32(&port.opened) != 1 {
|
if atomic.LoadUint32(&port.opened) != 1 {
|
||||||
return 0, &PortError{code: PortClosed}
|
return 0, &PortError{code: PortClosed}
|
||||||
}
|
}
|
||||||
@@ -70,104 +83,157 @@ func (port *unixPort) Read(p []byte) (int, error) {
|
|||||||
|
|
||||||
fds := unixutils.NewFDSet(port.handle, port.closeSignal.ReadFD())
|
fds := unixutils.NewFDSet(port.handle, port.closeSignal.ReadFD())
|
||||||
for {
|
for {
|
||||||
|
// 在每次select之前再次检查端口状态(非阻塞检查)
|
||||||
|
if atomic.LoadUint32(&port.opened) != 1 {
|
||||||
|
return 0, &PortError{code: PortClosed}
|
||||||
|
}
|
||||||
|
|
||||||
timeout := time.Duration(-1)
|
timeout := time.Duration(-1)
|
||||||
if port.readTimeout != NoTimeout {
|
if port.readTimeout != NoTimeout {
|
||||||
timeout = time.Until(deadline)
|
timeout = time.Until(deadline)
|
||||||
if timeout < 0 {
|
if timeout < 0 {
|
||||||
// a negative timeout means "no-timeout" in Select(...)
|
// 负超时值在Select(...)中表示"无超时"
|
||||||
timeout = 0
|
timeout = 0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
res, err := unixutils.Select(fds, nil, fds, timeout)
|
res, err := unixutils.Select(fds, nil, fds, timeout)
|
||||||
if err == unix.EINTR {
|
if err == unix.EINTR {
|
||||||
continue
|
continue // 系统调用被中断,重试
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
// 如果在端口关闭后遇到错误,返回PortClosed错误
|
||||||
}
|
if atomic.LoadUint32(&port.opened) != 1 {
|
||||||
if res.IsReadable(port.closeSignal.ReadFD()) {
|
|
||||||
return 0, &PortError{code: PortClosed}
|
return 0, &PortError{code: PortClosed}
|
||||||
}
|
}
|
||||||
if !res.IsReadable(port.handle) {
|
return 0, &PortError{code: FunctionNotImplemented, causedBy: err}
|
||||||
// Timeout happened
|
|
||||||
return 0, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if res.IsReadable(port.closeSignal.ReadFD()) {
|
||||||
|
// 收到关闭信号
|
||||||
|
return 0, &PortError{code: PortClosed}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !res.IsReadable(port.handle) {
|
||||||
|
// 超时
|
||||||
|
if port.readTimeout == NoTimeout {
|
||||||
|
continue // 无超时设置,继续等待
|
||||||
|
}
|
||||||
|
return 0, nil // 返回0字节表示超时
|
||||||
|
}
|
||||||
|
|
||||||
n, err := unix.Read(port.handle, p)
|
n, err := unix.Read(port.handle, p)
|
||||||
if err == unix.EINTR {
|
if err == unix.EINTR {
|
||||||
continue
|
continue // 系统调用被中断,重试
|
||||||
}
|
}
|
||||||
// Linux: when the port is disconnected during a read operation
|
// Linux系统特性:当读取操作期间端口断开连接时,
|
||||||
// the port is left in a "readable with zero-length-data" state.
|
// 端口会进入"可读但返回零长度数据"的状态。
|
||||||
// https://stackoverflow.com/a/34945814/1655275
|
// https://stackoverflow.com/a/34945814/1655275
|
||||||
if n == 0 && err == nil {
|
if n == 0 && err == nil {
|
||||||
return 0, &PortError{code: PortClosed}
|
return 0, &PortError{code: PortClosed}
|
||||||
}
|
}
|
||||||
if n < 0 { // Do not return -1 unix errors
|
if n < 0 { // 确保不返回负数
|
||||||
n = 0
|
n = 0
|
||||||
}
|
}
|
||||||
return n, err
|
// 检查读取操作期间端口是否被关闭
|
||||||
|
if atomic.LoadUint32(&port.opened) != 1 {
|
||||||
|
return 0, &PortError{code: PortClosed}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return n, &PortError{code: FunctionNotImplemented, causedBy: err}
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (port *unixPort) Write(p []byte) (n int, err error) {
|
func (port *unixPort) Write(p []byte) (n int, err error) {
|
||||||
|
// 首先检查端口是否已经关闭
|
||||||
|
if atomic.LoadUint32(&port.opened) != 1 {
|
||||||
|
return 0, &PortError{code: PortClosed}
|
||||||
|
}
|
||||||
|
|
||||||
n, err = unix.Write(port.handle, p)
|
n, err = unix.Write(port.handle, p)
|
||||||
if n < 0 { // Do not return -1 unix errors
|
if n < 0 { // 确保不返回负数
|
||||||
n = 0
|
n = 0
|
||||||
}
|
}
|
||||||
return
|
if err != nil {
|
||||||
|
return n, &PortError{code: FunctionNotImplemented, causedBy: err}
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (port *unixPort) Break(t time.Duration) error {
|
func (port *unixPort) Break(t time.Duration) error {
|
||||||
|
// 检查端口是否已经关闭
|
||||||
|
if atomic.LoadUint32(&port.opened) != 1 {
|
||||||
|
return &PortError{code: PortClosed}
|
||||||
|
}
|
||||||
|
|
||||||
if err := unix.IoctlSetInt(port.handle, ioctlTiocsbrk, 0); err != nil {
|
if err := unix.IoctlSetInt(port.handle, ioctlTiocsbrk, 0); err != nil {
|
||||||
return err
|
return &PortError{code: FunctionNotImplemented, causedBy: err}
|
||||||
}
|
}
|
||||||
|
|
||||||
time.Sleep(t)
|
time.Sleep(t)
|
||||||
|
|
||||||
if err := unix.IoctlSetInt(port.handle, ioctlTioccbrk, 0); err != nil {
|
if err := unix.IoctlSetInt(port.handle, ioctlTioccbrk, 0); err != nil {
|
||||||
return err
|
return &PortError{code: FunctionNotImplemented, causedBy: err}
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (port *unixPort) SetMode(mode *Mode) error {
|
func (port *unixPort) SetMode(mode *Mode) error {
|
||||||
|
// 检查端口是否已经关闭
|
||||||
|
if atomic.LoadUint32(&port.opened) != 1 {
|
||||||
|
return &PortError{code: PortClosed}
|
||||||
|
}
|
||||||
|
|
||||||
settings, err := port.getTermSettings()
|
settings, err := port.getTermSettings()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return &PortError{code: InvalidSerialPort, causedBy: err}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := setTermSettingsParity(mode.Parity, settings); err != nil {
|
if err := setTermSettingsParity(mode.Parity, settings); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := setTermSettingsDataBits(mode.DataBits, settings); err != nil {
|
if err := setTermSettingsDataBits(mode.DataBits, settings); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := setTermSettingsStopBits(mode.StopBits, settings); err != nil {
|
if err := setTermSettingsStopBits(mode.StopBits, settings); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
requireSpecialBaudrate := false
|
requireSpecialBaudrate := false
|
||||||
if err, special := setTermSettingsBaudrate(mode.BaudRate, settings); err != nil {
|
if err, special := setTermSettingsBaudrate(mode.BaudRate, settings); err != nil {
|
||||||
return err
|
return err
|
||||||
} else if special {
|
} else if special {
|
||||||
requireSpecialBaudrate = true
|
requireSpecialBaudrate = true
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := port.setTermSettings(settings); err != nil {
|
if err := port.setTermSettings(settings); err != nil {
|
||||||
return err
|
return &PortError{code: InvalidSerialPort, causedBy: err}
|
||||||
}
|
}
|
||||||
|
|
||||||
if requireSpecialBaudrate {
|
if requireSpecialBaudrate {
|
||||||
// MacOSX require this one to be the last operation otherwise an
|
// MacOSX要求这是最后一个操作,否则会产生'Invalid serial port'错误
|
||||||
// 'Invalid serial port' error is produced.
|
|
||||||
if err := port.setSpecialBaudrate(uint32(mode.BaudRate)); err != nil {
|
if err := port.setSpecialBaudrate(uint32(mode.BaudRate)); err != nil {
|
||||||
return err
|
return &PortError{code: InvalidSpeed, causedBy: err}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (port *unixPort) SetDTR(dtr bool) error {
|
func (port *unixPort) SetDTR(dtr bool) error {
|
||||||
|
// 检查端口是否已经关闭
|
||||||
|
if atomic.LoadUint32(&port.opened) != 1 {
|
||||||
|
return &PortError{code: PortClosed}
|
||||||
|
}
|
||||||
|
|
||||||
status, err := port.getModemBitsStatus()
|
status, err := port.getModemBitsStatus()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return &PortError{code: FunctionNotImplemented, causedBy: err}
|
||||||
}
|
}
|
||||||
if dtr {
|
if dtr {
|
||||||
status |= unix.TIOCM_DTR
|
status |= unix.TIOCM_DTR
|
||||||
@@ -178,9 +244,14 @@ func (port *unixPort) SetDTR(dtr bool) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (port *unixPort) SetRTS(rts bool) error {
|
func (port *unixPort) SetRTS(rts bool) error {
|
||||||
|
// 检查端口是否已经关闭
|
||||||
|
if atomic.LoadUint32(&port.opened) != 1 {
|
||||||
|
return &PortError{code: PortClosed}
|
||||||
|
}
|
||||||
|
|
||||||
status, err := port.getModemBitsStatus()
|
status, err := port.getModemBitsStatus()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return &PortError{code: FunctionNotImplemented, causedBy: err}
|
||||||
}
|
}
|
||||||
if rts {
|
if rts {
|
||||||
status |= unix.TIOCM_RTS
|
status |= unix.TIOCM_RTS
|
||||||
@@ -199,10 +270,16 @@ func (port *unixPort) SetReadTimeout(timeout time.Duration) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (port *unixPort) GetModemStatusBits() (*ModemStatusBits, error) {
|
func (port *unixPort) GetModemStatusBits() (*ModemStatusBits, error) {
|
||||||
|
// 检查端口是否已经关闭
|
||||||
|
if atomic.LoadUint32(&port.opened) != 1 {
|
||||||
|
return nil, &PortError{code: PortClosed}
|
||||||
|
}
|
||||||
|
|
||||||
status, err := port.getModemBitsStatus()
|
status, err := port.getModemBitsStatus()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, &PortError{code: FunctionNotImplemented, causedBy: err}
|
||||||
}
|
}
|
||||||
|
|
||||||
return &ModemStatusBits{
|
return &ModemStatusBits{
|
||||||
CTS: (status & unix.TIOCM_CTS) != 0,
|
CTS: (status & unix.TIOCM_CTS) != 0,
|
||||||
DCD: (status & unix.TIOCM_CD) != 0,
|
DCD: (status & unix.TIOCM_CD) != 0,
|
||||||
|
|||||||
@@ -281,15 +281,22 @@ func (port *windowsPort) SetRTS(rts bool) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (port *windowsPort) GetModemStatusBits() (*ModemStatusBits, error) {
|
func (port *windowsPort) GetModemStatusBits() (*ModemStatusBits, error) {
|
||||||
|
// GetCommModemStatus constants. See https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getcommmodemstatus.
|
||||||
|
const (
|
||||||
|
MS_CTS_ON = 0x0010
|
||||||
|
MS_DSR_ON = 0x0020
|
||||||
|
MS_RING_ON = 0x0040
|
||||||
|
MS_RLSD_ON = 0x0080
|
||||||
|
)
|
||||||
var bits uint32
|
var bits uint32
|
||||||
if err := windows.GetCommModemStatus(port.handle, &bits); err != nil {
|
if err := windows.GetCommModemStatus(port.handle, &bits); err != nil {
|
||||||
return nil, &PortError{}
|
return nil, &PortError{}
|
||||||
}
|
}
|
||||||
return &ModemStatusBits{
|
return &ModemStatusBits{
|
||||||
CTS: (bits & windows.EV_CTS) != 0,
|
CTS: (bits & MS_CTS_ON) != 0,
|
||||||
DCD: (bits & windows.EV_RLSD) != 0,
|
DCD: (bits & MS_RLSD_ON) != 0,
|
||||||
DSR: (bits & windows.EV_DSR) != 0,
|
DSR: (bits & MS_DSR_ON) != 0,
|
||||||
RI: (bits & windows.EV_RING) != 0,
|
RI: (bits & MS_RING_ON) != 0,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -366,7 +373,8 @@ func nativeOpen(portName string, mode *Mode) (*windowsPort, error) {
|
|||||||
0, nil,
|
0, nil,
|
||||||
windows.OPEN_EXISTING,
|
windows.OPEN_EXISTING,
|
||||||
windows.FILE_FLAG_OVERLAPPED,
|
windows.FILE_FLAG_OVERLAPPED,
|
||||||
0)
|
0,
|
||||||
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
switch err {
|
switch err {
|
||||||
case windows.ERROR_ACCESS_DENIED:
|
case windows.ERROR_ACCESS_DENIED:
|
||||||
|
|||||||
83
test/deadlock/main.go
Normal file
83
test/deadlock/main.go
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go.bug.st/serial"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
fmt.Println("Testing serial port read/write/close operations...")
|
||||||
|
|
||||||
|
// Test case: Opening a non-existent port (should fail gracefully)
|
||||||
|
_, err := serial.Open("/dev/nonexistent", &serial.Mode{BaudRate: 9600})
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Expected error when opening non-existent port: %v\n", err)
|
||||||
|
} else {
|
||||||
|
log.Fatal("Expected error when opening non-existent port, but it succeeded")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find available serial ports
|
||||||
|
ports, err := serial.GetPortsList()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(ports) > 0 {
|
||||||
|
fmt.Printf("Found %d available serial port(s)\n", len(ports))
|
||||||
|
for _, portName := range ports {
|
||||||
|
fmt.Printf("- %s\n", portName)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
fmt.Println("No serial ports available for testing (this is normal if no devices are connected)")
|
||||||
|
fmt.Println("The fix has been implemented and should resolve the deadlock issue")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test with the first available port
|
||||||
|
testPort := ports[0]
|
||||||
|
fmt.Printf("\nTesting port: %s\n", testPort)
|
||||||
|
|
||||||
|
// Test 1: Basic read timeout and close without data
|
||||||
|
mode := &serial.Mode{BaudRate: 9600}
|
||||||
|
port, err := serial.Open(testPort, mode)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Could not open port %s: %v\n", testPort, err)
|
||||||
|
fmt.Println("The fix has been implemented and should resolve the deadlock issue")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set a short read timeout
|
||||||
|
if err := port.SetReadTimeout(200 * time.Millisecond); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test concurrent read and close (this would deadlock before the fix)
|
||||||
|
chErr := make(chan error)
|
||||||
|
go func() {
|
||||||
|
buf := make([]byte, 1)
|
||||||
|
fmt.Printf("Reading from port %s with %v timeout...\n", testPort, 200*time.Millisecond)
|
||||||
|
n, err := port.Read(buf)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Read error: %v\n", err)
|
||||||
|
} else if n == 0 {
|
||||||
|
fmt.Println("Read timeout (expected)")
|
||||||
|
} else {
|
||||||
|
fmt.Printf("Read %d byte: %v\n", n, buf)
|
||||||
|
}
|
||||||
|
chErr <- err
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Wait a little, then close the port
|
||||||
|
time.Sleep(100 * time.Millisecond)
|
||||||
|
fmt.Println("Closing port...")
|
||||||
|
if err := port.Close(); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for read goroutine to complete
|
||||||
|
<-chErr
|
||||||
|
fmt.Println("Test passed: No deadlock occurred!")
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user