// // rhctl // // Copyright (C) 2009-2016 Christian Pointner // // This file is part of rhctl. // // rhctl is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // any later version. // // rhctl is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with rhctl. If not, see . // package main import ( "bufio" "syscall" "github.com/schleibinger/sio" ) type Baudrate uint32 const ( B1200 Baudrate = syscall.B1200 B2400 = syscall.B2400 B4800 = syscall.B4800 B9600 = syscall.B9600 B19200 = syscall.B19200 B38400 = syscall.B38400 B57600 = syscall.B57600 B115200 = syscall.B115200 ) type SerialPort struct { port *sio.Port rx <-chan string tx chan<- string } func serialReader(c chan<- string, port *sio.Port) { 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) } } func serialWriter(c <-chan string, port *sio.Port, newline string) { for data := range c { port.Write([]byte(data + newline)) } port.Close() } func SerialOpenAndHandle(device string, speed Baudrate, newline string) (port *SerialPort, err error) { port = &SerialPort{} if port.port, err = sio.Open(device, uint32(speed)); err != nil { return } tx := make(chan string, 10) rx := make(chan string, 20) go serialReader(rx, port.port) go serialWriter(tx, port.port, newline) port.rx = rx port.tx = tx return }