From bcaab3fe86c0b7d7e30effb3ab6ffdda3ad8eaac Mon Sep 17 00:00:00 2001 From: Damien Date: Wed, 25 Aug 2021 08:07:43 +1100 Subject: [PATCH] feat(timeout): instead of returning empty read, return error that can be checked with os.IsTimeout() --- example_test.go | 11 +++++++++++ serial.go | 7 +++++++ serial_unix.go | 2 +- serial_windows.go | 4 ++-- 4 files changed, 21 insertions(+), 3 deletions(-) diff --git a/example_test.go b/example_test.go index 63866bb..267129c 100644 --- a/example_test.go +++ b/example_test.go @@ -9,7 +9,9 @@ package serial_test import ( "fmt" "log" + "os" "strings" + "time" "go.bug.st/serial" ) @@ -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 { diff --git a/serial.go b/serial.go index 3e4f3b1..993b3d1 100644 --- a/serial.go +++ b/serial.go @@ -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 @@ -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 +} diff --git a/serial_unix.go b/serial_unix.go index 541660c..5c91647 100644 --- a/serial_unix.go +++ b/serial_unix.go @@ -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 { diff --git a/serial_windows.go b/serial_windows.go index af9a620..6b1d53c 100644 --- a/serial_windows.go +++ b/serial_windows.go @@ -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} } }