diff options
Diffstat (limited to 'src/rhctl/serial_port.go')
-rw-r--r-- | src/rhctl/serial_port.go | 49 |
1 files changed, 33 insertions, 16 deletions
diff --git a/src/rhctl/serial_port.go b/src/rhctl/serial_port.go index c7804a6..e809484 100644 --- a/src/rhctl/serial_port.go +++ b/src/rhctl/serial_port.go @@ -127,44 +127,61 @@ func (b *Baudrate) UnmarshalTOML(data []byte) error { } type SerialPort struct { - port *sio.Port - rx <-chan string - tx chan<- string + port *sio.Port + rx <-chan string + tx chan<- string + newline string } -func serialReader(c chan<- string, port *sio.Port) { +func serialReader(c chan<- string, port *sio.Port, stop chan<- bool) { + defer func() { + port.Close() + stop <- true + }() + scanner := bufio.NewScanner(port) scanner.Split(bufio.ScanLines) for scanner.Scan() { - if err := scanner.Err(); err != nil { - panic(err.Error()) - } data := scanner.Text() if len(data) == 0 { continue } c <- string(data) } + if err := scanner.Err(); err != nil { + rhl.Printf("device(%s): read error: %s", port.LocalAddr(), err) + panic(err.Error()) + } else { + rhl.Printf("device(%s): closed", port.LocalAddr()) + } } -func serialWriter(c <-chan string, port *sio.Port, newline string) { +func serialWriter(c <-chan string, port *sio.Port, newline string, stop chan<- bool) { + defer func() { + port.Close() + stop <- true + }() + for data := range c { port.Write([]byte(data + newline)) } - port.Close() } -func SerialOpenAndHandle(device string, rate Baudrate, newline string) (port *SerialPort, err error) { - port = &SerialPort{} - if port.port, err = sio.Open(device, rate.code); err != nil { - return - } +func (port *SerialPort) Run(stop chan<- bool) (err error) { tx := make(chan string, 10) rx := make(chan string, 20) - go serialReader(rx, port.port) - go serialWriter(tx, port.port, newline) + go serialReader(rx, port.port, stop) + go serialWriter(tx, port.port, port.newline, stop) port.rx = rx port.tx = tx return } + +func SerialOpen(device string, rate Baudrate, newline string) (port *SerialPort, err error) { + port = &SerialPort{newline: newline} + if port.port, err = sio.Open(device, rate.code); err != nil { + return + } + return +} |