-
Notifications
You must be signed in to change notification settings - Fork 0
/
unix.go
310 lines (261 loc) · 6.82 KB
/
unix.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
// Copyright 2015 mvbjrn. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !windows !cgo
// +build 386 amd64 arm
package serial
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"regexp"
"syscall"
"unsafe"
)
// TODO flow control
var (
baudrates = map[Baud]uint32{
Baud4800: syscall.B4800,
Baud9600: syscall.B9600,
Baud19200: syscall.B19200,
Baud38400: syscall.B38400,
Baud57600: syscall.B57600,
Baud115200: syscall.B115200,
}
databits = map[DataBit]uint32{
DataBit5: syscall.CS5,
DataBit6: syscall.CS6,
DataBit7: syscall.CS7,
DataBit8: syscall.CS8,
}
)
// structs and its functions
// Connection represents a serial connection with all parameters.
type Connection struct {
Port string
Baud Baud
DataBit DataBit
StopBit StopBit
Parity Parity
f *os.File
isOpen bool
}
func (connection *Connection) check() error {
match, _ := regexp.MatchString("/dev/tty.*", connection.Port)
if !match {
return errPort
}
switch connection.Baud {
case Baud115200, Baud57600, Baud38400, Baud19200, Baud9600, Baud4800:
default:
return errBaud
}
switch connection.DataBit {
case DataBit5, DataBit6, DataBit7, DataBit8:
default:
return errDataBit
}
switch connection.StopBit {
case StopBit1, StopBit2:
default:
return errStopBit
}
switch connection.Parity {
case ParityNone, ParityEven, ParityOdd:
default:
return errParity
}
return nil
}
// Save a connection to a json file.
func (connection *Connection) Save(path string) error {
json, err := json.Marshal(connection)
if err != nil {
return err
}
err = ioutil.WriteFile(path, json, 0644)
if err != nil {
return err
}
return nil
}
func (connection *Connection) String() string {
var parity string
switch connection.Parity {
case ParityNone:
parity = "N"
case ParityEven:
parity = "E"
case ParityOdd:
parity = "O"
}
return fmt.Sprintf("port: %s, baud rate:%d, parameters: %d%s%d",
connection.Port, connection.Baud, connection.DataBit, parity,
connection.StopBit)
}
// Open a connection with a read timeout.
func (connection *Connection) Open(timeout uint8) error {
var err error
// The serial port is basically a file we are writing to and reading from.
// O_RDWR allows the program to read and write the file.
// O_NOCTTY prevents the device from controlling the terminal.
// O_NONBLOCK prevents the system from blocking for a long time.
connection.f, err = os.OpenFile(connection.Port,
syscall.O_RDWR|syscall.O_NOCTTY|syscall.O_NONBLOCK, 0666)
if err != nil {
return err
}
// Close the file on error occurrence.
defer func() {
if err != nil && connection.f != nil {
connection.f.Close()
}
}()
// Create a plain termios, which allows the program to execute
// input/output operations.
termios := syscall.Termios{}
// Setup the baud rate in the termios structure.
baudrate := baudrates[connection.Baud]
termios.Cflag |= baudrate
termios.Ispeed = baudrate
termios.Ospeed = baudrate
// Setup stop bits in the termios structure.
switch connection.StopBit {
case StopBit1:
termios.Cflag &^= syscall.CSTOPB // CSTOPB = 0x40
case StopBit2:
termios.Cflag |= syscall.CSTOPB
default:
return errStopBit
}
// Setup data bits in the termios structure.
databit := databits[connection.DataBit]
termios.Cflag |= databit
// Setup parity in the termios structure.
switch connection.Parity {
case ParityNone:
termios.Cflag &^= syscall.PARENB // PARENB = 0x100
case ParityEven:
termios.Cflag |= syscall.PARENB
case ParityOdd:
termios.Cflag |= syscall.PARENB
termios.Cflag |= syscall.PARODD // PARODD = 0x200
default:
return errParity
}
// // set blocking / non-blocking read
vmin := uint8(0)
if timeout == 0 {
vmin = 1
}
// Attach min bytes and timeout to the termios structure.
termios.Cc = [32]uint8{
syscall.VMIN: vmin, // min bytes per transfer
syscall.VTIME: timeout, // actual read timeout in deciseconds
}
// Execute IOCTL with the modified termios structure to apply the changes.
if _, _, errno := syscall.Syscall6(
// device-specific input/output operations
syscall.SYS_IOCTL,
// open file descriptor
uintptr(connection.f.Fd()),
// a request code number to set the current serial port settings
uintptr(syscall.TCSETS),
//TODO: it looks like syscall.TCSETS is not available under
// freebsd and darwin. Is this a bug?
uintptr(unsafe.Pointer(&termios)), // a pointer to the termios structure
0,
0,
0,
); errno != 0 {
return errno
}
connection.isOpen = true
return nil
}
// Write a byte array to an open connection.
func (connection *Connection) Write(b []byte) (int, error) {
if connection.isOpen {
return connection.f.Write(b)
}
return 0, errConnOpen
}
// Read from an open connection until the delimiter is reached.
func (connection *Connection) Read(delimiter byte) ([]byte, error) {
if connection.isOpen {
reader := bufio.NewReader(connection.f)
return reader.ReadBytes(delimiter)
}
return nil, errConnOpen
}
// ReadToBuffer reads from an open connection into a []byte buffer with
// the given size.
func (connection *Connection) ReadToBuffer(size int) ([]byte, error) {
buffer := make([]byte, size)
n, err := connection.f.Read(buffer)
if err != nil {
return nil, err
}
return buffer[:n], nil
}
// Flush the connection, which causes untransmitted or not read data
// to be discarded.
func (connection *Connection) Flush() error {
if connection.isOpen {
_, _, err := syscall.Syscall(
// device-specific input/output operations
syscall.SYS_IOCTL,
// open file descriptor
uintptr(connection.f.Fd()),
// a request code number to flush input/output
uintptr(syscall.TCIOFLUSH),
// a pointer to data, not needed here
uintptr(0),
)
return err
}
return errConnOpen
}
// Query combines Write(), Read() and Flush() to improve usability.
func (connection *Connection) Query(request []byte,
delimiter byte) ([]byte, error) {
if connection.isOpen {
// write
n, err := connection.Write(request)
if err != nil {
return nil, err
}
if n != len(request) {
return nil, errWriteBytes
}
// read
response, err := connection.Read(delimiter)
if err != nil {
return nil, err
}
// flush
err = connection.Flush()
if err != nil {
return nil, err
}
return response, nil
}
return nil, errConnOpen
}
// Close a connection.
func (connection *Connection) Close() error {
err := connection.f.Close()
connection.isOpen = false
return err
}
// functions
// createConnection is the entrence point for the Connection in
// unix-like operating systems.
func createConnection(port string, baudrate Baud, databit DataBit,
stopbit StopBit, parity Parity) (*Connection, error) {
connection := &Connection{Port: port, Baud: baudrate,
DataBit: databit, StopBit: stopbit, Parity: parity}
return connection, connection.check()
}