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 Aug 24, 2021
1 parent adc54fb commit bcaab3f
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 3 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
7 changes: 7 additions & 0 deletions serial.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,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 @@ -188,3 +190,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 @@ -86,7 +86,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
4 changes: 2 additions & 2 deletions serial_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,8 @@ func (port *windowsPort) Read(p []byte) (int, error) {
if port.readTimeoutCycles != -1 {
cycles++
if cycles == port.readTimeoutCycles {
// Timeout
return 0, nil
// Timeout happened
return 0, &PortError{code: Timeout}
}
}

Expand Down

0 comments on commit bcaab3f

Please sign in to comment.