From 0a4aaefa4e03d9b38ca2135bc226b3bc6a0ba9d7 Mon Sep 17 00:00:00 2001 From: Nonoo Date: Wed, 21 Oct 2020 09:37:26 +0200 Subject: [PATCH] Implement serial port read/write loops --- serial-linux.go | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/serial-linux.go b/serial-linux.go index ff158b9..9b1ac00 100644 --- a/serial-linux.go +++ b/serial-linux.go @@ -7,10 +7,45 @@ import ( type serialPortStruct struct { pty *term.PTY + + // Read from this channel to receive serial data. + read chan []byte + // Write to this channel to send serial data. + write chan []byte } var serialPort serialPortStruct +func (s *serialPortStruct) writeLoop() { + s.write = make(chan []byte) + var b []byte + for { + b = <-s.write + bytesToWrite := len(b) + + for bytesToWrite > 0 { + written, err := s.pty.Master.Write(b) + if err != nil { + exit(err) + } + b = b[written:] + bytesToWrite -= written + } + } +} + +func (s *serialPortStruct) readLoop() { + s.read = make(chan []byte) + b := make([]byte, 1500) + for { + n, err := s.pty.Master.Read(b) + if err != nil { + exit(err) + } + s.read <- b[:n] + } +} + func (s *serialPortStruct) init() { var err error s.pty, err = term.OpenPTY() @@ -22,6 +57,9 @@ func (s *serialPortStruct) init() { exit(err) } log.Print("opened ", n) + + go s.readLoop() + go s.writeLoop() } func (s *serialPortStruct) deinit() {