Skip to content

Commit

Permalink
feat(timeout): instead of returning empty read, return error that can…
Browse files Browse the repository at this point in the history
… be checked with os.IsTimeout()
  • Loading branch information
maitredede committed May 6, 2024
1 parent 0925f99 commit 64dacdd
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 2 deletions.
11 changes: 11 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ package serial_test
import (
"fmt"
"log"
"os"
"strings"
"time"

"go.bug.st/serial"
)
Expand Down Expand Up @@ -53,11 +55,20 @@ func Example_sendAndReceive() {

// Read and print the response

if err := port.SetReadTimeout(1 * time.Minute); err != nil {
fmt.Printf("failed to set read timeout: %v\n", err)
}

buff := make([]byte, 100)
for {
// Reads up to 100 bytes
n, err := port.Read(buff)
if err != nil {
if os.IsTimeout(err) {
fmt.Println("timeout")
// TODO do something on read timeout
continue
}
log.Fatal(err)
}
if n == 0 {
Expand Down
9 changes: 9 additions & 0 deletions serial.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,8 @@ const (
PortClosed
// FunctionNotImplemented the requested function is not implemented
FunctionNotImplemented
// Timeout when an operation has timed out
Timeout
)

// EncodedErrorString returns a string explaining the error code
Expand Down Expand Up @@ -194,6 +196,8 @@ func (e PortError) EncodedErrorString() string {
return "Port has been closed"
case FunctionNotImplemented:
return "Function not implemented"
case Timeout:
return "Timeout"
default:
return "Other error"
}
Expand All @@ -211,3 +215,8 @@ func (e PortError) Error() string {
func (e PortError) Code() PortErrorCode {
return e.code
}

// Timeout returns true if is is a timeout (usable with os.IsTimeout)
func (e PortError) Timeout() bool {
return e.code == Timeout
}
2 changes: 1 addition & 1 deletion serial_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ func (port *unixPort) Read(p []byte) (int, error) {
}
if !res.IsReadable(port.handle) {
// Timeout happened
return 0, nil
return 0, &PortError{code: Timeout}
}
n, err := unix.Read(port.handle, p)
if err == unix.EINTR {
Expand Down
2 changes: 1 addition & 1 deletion serial_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ func (port *windowsPort) Read(p []byte) (int, error) {
}

// Timeout
return 0, nil
return 0, &PortError{code: Timeout}
}

func (port *windowsPort) Write(p []byte) (int, error) {
Expand Down

0 comments on commit 64dacdd

Please sign in to comment.