summaryrefslogtreecommitdiff
path: root/src/rhctl/serial_port.go
blob: e4b2c465d8563f7c6a87457fc14b4294a71a35bd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//
//  rhctl
//
//  Copyright (C) 2009-2016 Christian Pointner <equinox@helsinki.at>
//
//  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 <http://www.gnu.org/licenses/>.
//

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 SerialRead(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 SerialWrite(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, 1)
	rx := make(chan string, 20)
	go SerialRead(rx, port.port)
	go SerialWrite(tx, port.port, newline)

	port.rx = rx
	port.tx = tx
	return
}