diff --git a/example_test.go b/example_test.go index 7ad5eef..a93448c 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 8e3ce89..a0fe43a 100644 --- a/serial.go +++ b/serial.go @@ -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 @@ -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" } @@ -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 +} diff --git a/serial_unix.go b/serial_unix.go index 54e55a8..b6f847c 100644 --- a/serial_unix.go +++ b/serial_unix.go @@ -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 { diff --git a/serial_windows.go b/serial_windows.go index e350f86..a88c9bd 100644 --- a/serial_windows.go +++ b/serial_windows.go @@ -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) {