forked from mvbjrn/goserial
/
connection_linux.go
228 lines (191 loc) · 5.63 KB
/
connection_linux.go
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// +build linux
package serial
// #include <unistd.h>
// #include <fcntl.h>
// #include <sys/ioctl.h>
// #include <termios.h>
import "C"
import (
"errors"
"fmt"
"os"
"sync"
"syscall"
"time"
)
var bauds = map[Baud]C.speed_t{
2400: C.B2400,
4800: C.B4800,
9600: C.B9600,
19200: C.B19200,
38400: C.B38400,
57600: C.B57600,
115200: C.B115200,
230400: C.B230400,
}
var byteSizes = map[ByteSize]C.tcflag_t{
ByteSize5: C.CS5,
ByteSize6: C.CS6,
ByteSize7: C.CS7,
ByteSize8: C.CS8,
}
type Connection struct {
file *os.File
readMutex sync.Mutex
writeMutex sync.Mutex
}
func (conn *Connection) Read(buf []byte) (int, error) {
conn.readMutex.Lock()
defer conn.readMutex.Unlock()
return conn.file.Read(buf)
}
func (conn *Connection) Write(buf []byte) (int, error) {
conn.writeMutex.Lock()
defer conn.writeMutex.Unlock()
return conn.file.Write(buf)
}
func (conn *Connection) Close() error {
fmt.Println("DEBUG: Closing", conn.file)
return conn.file.Close()
}
func (conn *Connection) Drain() error {
_, err := C.tcdrain(C.int(conn.file.Fd()))
return err
}
// https://github.com/ynezz/librs232/blob/master/src/rs232_posix.c
// http://sigrok.org/wiki/Libserialport
// https://github.com/mavlink/c_uart_interface_example/blob/master/mavlink_serial.cpp
func openPort(name string, baud Baud, byteSize ByteSize, parity ParityMode, stopBits StopBits, readTimeout time.Duration) (conn *Connection, err error) {
var file *os.File
file, err = os.OpenFile(name, syscall.O_RDWR|syscall.O_NOCTTY|syscall.O_NDELAY, 0660)
if err != nil {
return nil, err
}
defer func() {
if err != nil {
fmt.Println("DEBUG: Error in openPort(), closing file.")
file.Close()
}
}()
fd := C.int(file.Fd())
if C.isatty(fd) != 1 {
err = errors.New("File is not a tty")
return
}
// Note that open() follows POSIX semantics: multiple open() calls to
// the same file will succeed unless the TIOCEXCL ioctl is issued.
// This will prevent additional opens except by root-owned processes.
// See tty(4) ("man 4 tty") and ioctl(2) ("man 2 ioctl") for details.
r0, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), C.TIOCEXCL, 0)
if r0 != 0 {
err = fmt.Errorf("Error setting TIOCEXCL: %s", errno)
return
}
// // Clear the O_NONBLOCK flag so subsequent I/O will block
// flags, _, errno := syscall.Syscall(syscall.SYS_FCNTL, uintptr(fd), C.F_GETFL, 0)
// if errno != 0 {
// err = fmt.Errorf("Error clearing O_NONBLOCK: %s", errno)
// return
// }
// flags &^= C.O_NONBLOCK
r0, _, errno = syscall.Syscall(syscall.SYS_FCNTL, uintptr(fd), C.F_SETFL, 0)
if r0 != 0 {
err = fmt.Errorf("Error clearing O_NONBLOCK: %s", errno)
return
}
// Get the current options and save them so we can restore the
// default settings later.
var r C.int
var origTermiosSettings C.struct_termios
r, err = C.tcgetattr(fd, &origTermiosSettings)
if r != 0 {
err = fmt.Errorf("Error getting serial attributes: %s", err)
return
}
defer func() {
C.tcsetattr(fd, C.TCSANOW, &origTermiosSettings)
}()
// The serial port attributes such as timeouts and baud rate are set by
// modifying the termios structure and then calling tcsetattr to
// cause the changes to take effect. Note that the
// changes will not take effect without the tcsetattr() call.
// See tcsetattr(4) ("man 4 tcsetattr") for details.
termios := origTermiosSettings
// Make a pre-existing termios structure into "raw" mode: character-at-a-time
// mode with no characters interpreted, 8-bit data path.
//
// cfmakeraw(struct termios *t)
// {
// t->c_iflag &= ~(IMAXBEL | IGNBRK | BRKINT | PARMRK | ISTRIP |
// INLCR | IGNCR | ICRNL | IXON);
// t->c_oflag &= ~OPOST;
// t->c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
// t->c_cflag &= ~(CSIZE | PARENB);
// t->c_cflag |= CS8;
// }
//
// C.cfmakeraw(&termios)
// Select local mode
// termios.c_cflag |= C.CLOCAL | C.CREAD
/// or
termios.c_iflag &^= (C.IGNBRK | C.BRKINT | C.ICRNL | C.INLCR | C.PARMRK | C.INPCK | C.ISTRIP | C.IXON)
termios.c_oflag &^= (C.OCRNL | C.ONLCR | C.ONLRET | C.ONOCR | C.OFILL | C.OPOST)
termios.c_lflag &^= (C.ECHO | C.ECHONL | C.ICANON | C.IEXTEN | C.ISIG)
termios.c_cflag &^= (C.CSIZE | C.PARENB)
termios.c_cflag |= C.CS8
/// /or
// See http://www.unixwiz.net/techtips/termios-vmin-vtime.html
termios.c_cc[C.VMIN] = 0
termios.c_cc[C.VTIME] = C.cc_t(readTimeout / (time.Second / 10))
speed, ok := bauds[baud]
if !ok {
err = fmt.Errorf("Unknown baud rate %d", baud)
return
}
r, err = C.cfsetispeed(&termios, speed)
if r != 0 {
err = fmt.Errorf("Error setting input speed: %d (%s)", speed, err)
return
}
r, err = C.cfsetospeed(&termios, speed)
if r != 0 {
err = fmt.Errorf("Error setting output speed: %d (%s)", speed, err)
return
}
// switch stopBits {
// case StopBits1:
// termios.c_cflag &^= C.CSTOPB
// case StopBits2:
// termios.c_cflag |= C.CSTOPB
// default:
// err = fmt.Errorf("Bad number of stop bits: %d", stopBits)
// return
// }
// size, ok := byteSizes[byteSize]
// if !ok {
// err = fmt.Errorf("Bad byte size: %d", byteSize)
// return
// }
// termios.c_cflag &^= C.CSIZE
// termios.c_cflag |= size
// // Select parity mode
// switch parity {
// case ParityModeNone:
// termios.c_cflag &^= C.PARENB
// case ParityModeEven:
// termios.c_cflag |= C.PARENB
// termios.c_cflag &^= C.PARODD
// case ParityModeOdd:
// termios.c_cflag |= C.PARENB
// termios.c_cflag |= C.PARODD
// default:
// err = errors.New("goserial config: bad parity")
// return
// }
r, err = C.tcsetattr(fd, C.TCSAFLUSH, &termios)
if r != 0 {
err = fmt.Errorf("Error setting serial options: %s", err)
return
}
return &Connection{file: file}, nil
}