bugst / go-serial

A cross-platform serial library for go-lang.
BSD 3-Clause "New" or "Revised" License
619 stars 189 forks source link

Read() and Write() return -1 on error #55

Closed ademenev closed 4 years ago

ademenev commented 5 years ago

Read() and Write() return -1 on error, while specs of io.Reader and io.Writer say the return value should be always >= 0. I am running macOS, but the same is true for Linux and BSD.

Here is an example that demonstrates the issue. I have a USB to serial converter (Arduino Mega2560)

package main

import sp "go.bug.st/serial.v1"
import "fmt"
import "time"

func main() {
    opts := &sp.Mode{
        BaudRate: 115200,
        DataBits: 8,
        StopBits: sp.OneStopBit,
    }
    rwc, err := sp.Open("/dev/cu.usbmodem1421", opts)
    if err != nil {
        panic(err)
    }
    var buf [128] byte
    for {

        n, err := rwc.Write([]byte{'?'})
        fmt.Println("Write", n, err)
        n, err = rwc.Read(buf[:])
        fmt.Println("Read", n, err)
        if err != nil {
            break
        }
        <-time.After(time.Second)
    }
}

After few seconds I unplug the USB cable

Output:

Write 1 <nil>
Read 41 <nil>
Write 1 <nil>
Read 14 <nil>
Write 1 <nil>
Read 85 <nil>
Write 1 <nil>
Read 72 <nil>
Write 1 <nil>
Read 57 <nil>
Write -1 device not configured
Read -1 device not configured

This makes a huge problem, for example when using the serial port with bufio.Scanner, unplugging the cable causes a panic