forked from bugst/go-serial
-
Notifications
You must be signed in to change notification settings - Fork 3
/
serial_unix.go
584 lines (510 loc) · 13.5 KB
/
serial_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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
//
// Copyright 2014-2020 Cristian Maglie. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
// +build linux darwin freebsd openbsd
package serial
import (
"io/ioutil"
"regexp"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
"go.bug.st/serial/unixutils"
"golang.org/x/sys/unix"
)
type unixPort struct {
handle int
firstByteTimeout bool
readTimeout int
writeTimeout int
closeLock sync.RWMutex
closeSignal *unixutils.Pipe
opened uint32
}
const (
rs485Enabled = 1 << 0
rs485RTSOnSend = 1 << 1
rs485RTSAfterSend = 1 << 2
rs485RXDuringTX = 1 << 4
rs485Tiocs = 0x542f
)
// rs485_ioctl_opts is used to configure RS485 options in the driver
type rs485_ioctl_opts struct {
flags uint32
delay_rts_before_send uint32
delay_rts_after_send uint32
padding [5]uint32
}
func (port *unixPort) Close() error {
if !atomic.CompareAndSwapUint32(&port.opened, 1, 0) {
return &PortError{code: PortClosed}
}
// Close port
_ = port.releaseExclusiveAccess()
if err := unix.Close(port.handle); err != nil {
return err
}
if port.closeSignal != nil {
// Send close signal to all pending reads (if any)
port.closeSignal.Write([]byte{0})
// Wait for all readers to complete
port.closeLock.Lock()
defer port.closeLock.Unlock()
// Close signaling pipe
if err := port.closeSignal.Close(); err != nil {
return err
}
}
return nil
}
func (port *unixPort) Read(p []byte) (int, error) {
port.closeLock.RLock()
defer port.closeLock.RUnlock()
if atomic.LoadUint32(&port.opened) != 1 {
return 0, &PortError{code: PortClosed}
}
size, read := len(p), 0
buf := make([]byte, size)
now := time.Now()
deadline := now.Add(time.Duration(port.readTimeout) * time.Millisecond)
fds := unixutils.NewFDSet(port.handle, port.closeSignal.ReadFD())
for read < size {
res, err := unixutils.Select(fds, nil, fds, deadline.Sub(now))
if err == unix.EINTR {
continue
}
if err != nil {
return read, err
}
if res.IsReadable(port.closeSignal.ReadFD()) {
return read, &PortError{code: PortClosed}
}
if !res.IsReadable(port.handle) {
break
}
n, err := unix.Read(port.handle, buf)
if err == unix.EINTR {
continue
}
// read should always return some data as select reported it was ready to read when we get to this point.
if err == nil && n == 0 {
err = &PortError{code: ReadFailed}
}
if err != nil {
return read, err
}
copy(p[read:], buf[:n])
read += n
now = time.Now()
if !now.Before(deadline) || port.firstByteTimeout {
break
}
}
return read, nil
}
func (port *unixPort) Write(p []byte) (int, error) {
port.closeLock.RLock()
defer port.closeLock.RUnlock()
if atomic.LoadUint32(&port.opened) != 1 {
return 0, &PortError{code: PortClosed}
}
size, written := len(p), 0
fds := unixutils.NewFDSet(port.handle)
clFds := unixutils.NewFDSet(port.closeSignal.ReadFD())
deadline := time.Now().Add(time.Duration(port.writeTimeout) * time.Millisecond)
for written < size {
n, err := unix.Write(port.handle, p[written:])
if err != nil {
return written, err
}
if port.writeTimeout == 0 {
return n, nil
}
written += n
now := time.Now()
if port.writeTimeout > 0 && !now.Before(deadline) {
return written, nil
}
res, err := unixutils.Select(clFds, fds, fds, deadline.Sub(now))
if err != nil {
return written, err
}
if res.IsReadable(port.closeSignal.ReadFD()) {
return written, &PortError{code: PortClosed}
}
if !res.IsWritable(port.handle) {
return written, &PortError{code: WriteFailed}
}
}
return written, nil
}
func (port *unixPort) ResetInputBuffer() error {
return ioctl(port.handle, ioctlTcflsh, unix.TCIFLUSH)
}
func (port *unixPort) ResetOutputBuffer() error {
return ioctl(port.handle, ioctlTcflsh, unix.TCOFLUSH)
}
func (port *unixPort) SetMode(mode *Mode) error {
settings, err := port.getTermSettings()
if err != nil {
return err
}
if err := setTermSettingsBaudrate(mode.BaudRate, settings); err != nil {
return err
}
if err := setTermSettingsParity(mode.Parity, settings); err != nil {
return err
}
if err := setTermSettingsDataBits(mode.DataBits, settings); err != nil {
return err
}
if err := setTermSettingsStopBits(mode.StopBits, settings); err != nil {
return err
}
return port.setTermSettings(settings)
}
func (port *unixPort) SetDTR(dtr bool) error {
status, err := port.getModemBitsStatus()
if err != nil {
return err
}
if dtr {
status |= unix.TIOCM_DTR
} else {
status &^= unix.TIOCM_DTR
}
return port.setModemBitsStatus(status)
}
func (port *unixPort) SetRTS(rts bool) error {
status, err := port.getModemBitsStatus()
if err != nil {
return err
}
if rts {
status |= unix.TIOCM_RTS
} else {
status &^= unix.TIOCM_RTS
}
return port.setModemBitsStatus(status)
}
func (port *unixPort) SetReadTimeout(t int) error {
port.firstByteTimeout = false
port.readTimeout = t
return nil // timeout is done via select
}
func (port *unixPort) SetReadTimeoutEx(t, i uint32) error {
port.closeLock.RLock()
defer port.closeLock.RUnlock()
if atomic.LoadUint32(&port.opened) != 1 {
return &PortError{code: PortClosed}
}
port.firstByteTimeout = false
port.readTimeout = int(t)
settings, err := port.getTermSettings()
if err != nil {
return err
}
if err := setTermSettingsInterbyteTimeout(int(t), settings); err != nil {
return err
}
return port.setTermSettings(settings)
}
func (port *unixPort) SetFirstByteReadTimeout(t uint32) error {
if t > 0 && t < 0xFFFFFFFF {
port.firstByteTimeout = true
port.readTimeout = int(t)
return nil
} else {
return &PortError{code: InvalidTimeoutValue}
}
}
func (port *unixPort) SetWriteTimeout(t int) error {
port.writeTimeout = t
return nil // timeout is done via select
}
func (port *unixPort) GetModemStatusBits() (*ModemStatusBits, error) {
status, err := port.getModemBitsStatus()
if err != nil {
return nil, err
}
return &ModemStatusBits{
CTS: (status & unix.TIOCM_CTS) != 0,
DCD: (status & unix.TIOCM_CD) != 0,
DSR: (status & unix.TIOCM_DSR) != 0,
RI: (status & unix.TIOCM_RI) != 0,
}, nil
}
func nativeOpen(portName string, mode *Mode) (*unixPort, error) {
h, err := unix.Open(portName, unix.O_RDWR|unix.O_NOCTTY|unix.O_NDELAY, 0)
if err != nil {
switch err {
case unix.EBUSY:
return nil, &PortError{code: PortBusy}
case unix.EACCES:
return nil, &PortError{code: PermissionDenied}
}
return nil, err
}
port := &unixPort{
handle: h,
opened: 1,
firstByteTimeout: true,
readTimeout: 1000, // Backward compatible default value
writeTimeout: 0,
}
// Setup serial port
if port.SetMode(mode) != nil {
port.Close()
return nil, &PortError{code: InvalidSerialPort}
}
settings, err := port.getTermSettings()
if err != nil {
port.Close()
return nil, &PortError{code: InvalidSerialPort}
}
// Set raw mode
setRawMode(settings)
// Explicitly disable RTS/CTS flow control
setTermSettingsCtsRts(false, settings)
if port.setTermSettings(settings) != nil {
port.Close()
return nil, &PortError{code: InvalidSerialPort}
}
unix.SetNonblock(h, false)
err = port.acquireExclusiveAccess()
if err != nil {
port.Close()
return nil, err
}
// Enable RS485, if requested
if err = port.enableRS485(&mode.RS485); err != nil {
port.Close()
return nil, err
}
// This pipe is used as a signal to cancel blocking Read
pipe := &unixutils.Pipe{}
if err := pipe.Open(); err != nil {
port.Close()
return nil, &PortError{code: InvalidSerialPort, causedBy: err}
}
port.closeSignal = pipe
return port, nil
}
func nativeGetPortsList() ([]string, error) {
files, err := ioutil.ReadDir(devFolder)
if err != nil {
return nil, err
}
ports := make([]string, 0, len(files))
for _, f := range files {
// Skip folders
if f.IsDir() {
continue
}
// Keep only devices with the correct name
match, err := regexp.MatchString(regexFilter, f.Name())
if err != nil {
return nil, err
}
if !match {
continue
}
portName := devFolder + "/" + f.Name()
// Check if serial port is real or is a placeholder serial port "ttySxx"
if strings.HasPrefix(f.Name(), "ttyS") {
port, err := nativeOpen(portName, &Mode{})
if err != nil {
serr, ok := err.(*PortError)
if ok && serr.Code() == InvalidSerialPort {
continue
}
} else {
port.Close()
}
}
// Save serial port in the resulting list
ports = append(ports, portName)
}
return ports, nil
}
// termios manipulation functions
func setTermSettingsBaudrate(speed int, settings *unix.Termios) error {
baudrate, ok := baudrateMap[speed]
if !ok {
return &PortError{code: InvalidSpeed}
}
// revert old baudrate
for _, rate := range baudrateMap {
settings.Cflag &^= rate
}
// set new baudrate
settings.Cflag |= baudrate
settings.Ispeed = toTermiosSpeedType(baudrate)
settings.Ospeed = toTermiosSpeedType(baudrate)
return nil
}
func setTermSettingsParity(parity Parity, settings *unix.Termios) error {
switch parity {
case NoParity:
settings.Cflag &^= unix.PARENB
settings.Cflag &^= unix.PARODD
settings.Cflag &^= tcCMSPAR
settings.Iflag &^= unix.INPCK
case OddParity:
settings.Cflag |= unix.PARENB
settings.Cflag |= unix.PARODD
settings.Cflag &^= tcCMSPAR
settings.Iflag |= unix.INPCK
case EvenParity:
settings.Cflag |= unix.PARENB
settings.Cflag &^= unix.PARODD
settings.Cflag &^= tcCMSPAR
settings.Iflag |= unix.INPCK
case MarkParity:
if tcCMSPAR == 0 {
return &PortError{code: InvalidParity}
}
settings.Cflag |= unix.PARENB
settings.Cflag |= unix.PARODD
settings.Cflag |= tcCMSPAR
settings.Iflag |= unix.INPCK
case SpaceParity:
if tcCMSPAR == 0 {
return &PortError{code: InvalidParity}
}
settings.Cflag |= unix.PARENB
settings.Cflag &^= unix.PARODD
settings.Cflag |= tcCMSPAR
settings.Iflag |= unix.INPCK
default:
return &PortError{code: InvalidParity}
}
return nil
}
func setTermSettingsDataBits(bits int, settings *unix.Termios) error {
databits, ok := databitsMap[bits]
if !ok {
return &PortError{code: InvalidDataBits}
}
// Remove previous databits setting
settings.Cflag &^= unix.CSIZE
// Set requested databits
settings.Cflag |= databits
return nil
}
func setTermSettingsStopBits(bits StopBits, settings *unix.Termios) error {
switch bits {
case OneStopBit:
settings.Cflag &^= unix.CSTOPB
case OnePointFiveStopBits:
return &PortError{code: InvalidStopBits}
case TwoStopBits:
settings.Cflag |= unix.CSTOPB
default:
return &PortError{code: InvalidStopBits}
}
return nil
}
func setTermSettingsCtsRts(enable bool, settings *unix.Termios) {
if enable {
settings.Cflag |= tcCRTSCTS
} else {
settings.Cflag &^= tcCRTSCTS
}
}
func setRawMode(settings *unix.Termios) {
// Set local mode
settings.Cflag |= unix.CREAD
settings.Cflag |= unix.CLOCAL
// Set raw mode
settings.Lflag &^= unix.ICANON
settings.Lflag &^= unix.ECHO
settings.Lflag &^= unix.ECHOE
settings.Lflag &^= unix.ECHOK
settings.Lflag &^= unix.ECHONL
settings.Lflag &^= unix.ECHOCTL
settings.Lflag &^= unix.ECHOPRT
settings.Lflag &^= unix.ECHOKE
settings.Lflag &^= unix.ISIG
settings.Lflag &^= unix.IEXTEN
settings.Iflag &^= unix.IXON
settings.Iflag &^= unix.IXOFF
settings.Iflag &^= unix.IXANY
settings.Iflag &^= unix.INPCK
settings.Iflag &^= unix.IGNPAR
settings.Iflag &^= unix.PARMRK
settings.Iflag &^= unix.ISTRIP
settings.Iflag &^= unix.IGNBRK
settings.Iflag &^= unix.BRKINT
settings.Iflag &^= unix.INLCR
settings.Iflag &^= unix.IGNCR
settings.Iflag &^= unix.ICRNL
settings.Iflag &^= tcIUCLC
settings.Oflag &^= unix.OPOST
// Block reads until at least one char is available (no timeout)
settings.Cc[unix.VMIN] = 1
settings.Cc[unix.VTIME] = 0
}
func setTermSettingsInterbyteTimeout(timeout int, settings *unix.Termios) error {
vtime := timeout / 100 // VTIME tenths of a second elapses between bytes
if vtime > 255 || vtime*100 != timeout {
return &PortError{code: InvalidTimeoutValue}
}
if vtime > 0 {
settings.Cc[unix.VMIN] = 1
settings.Cc[unix.VTIME] = uint8(timeout)
} else {
settings.Cc[unix.VMIN] = 0
settings.Cc[unix.VTIME] = 0
}
return nil
}
// native syscall wrapper functions
func (port *unixPort) getTermSettings() (*unix.Termios, error) {
settings := &unix.Termios{}
err := ioctl(port.handle, ioctlTcgetattr, uintptr(unsafe.Pointer(settings)))
return settings, err
}
func (port *unixPort) setTermSettings(settings *unix.Termios) error {
return ioctl(port.handle, ioctlTcsetattr, uintptr(unsafe.Pointer(settings)))
}
func (port *unixPort) getModemBitsStatus() (int, error) {
var status int
err := ioctl(port.handle, unix.TIOCMGET, uintptr(unsafe.Pointer(&status)))
return status, err
}
func (port *unixPort) setModemBitsStatus(status int) error {
return ioctl(port.handle, unix.TIOCMSET, uintptr(unsafe.Pointer(&status)))
}
func (port *unixPort) acquireExclusiveAccess() error {
return ioctl(port.handle, unix.TIOCEXCL, 0)
}
func (port *unixPort) releaseExclusiveAccess() error {
return ioctl(port.handle, unix.TIOCNXCL, 0)
}
// enableRS485 enables RS485 functionality of driver via an ioctl if the config says so
func (port *unixPort) enableRS485(config *RS485Config) error {
if !config.Enabled {
return nil
}
rs485 := rs485_ioctl_opts{
rs485Enabled,
uint32(config.DelayRtsBeforeSend / time.Millisecond),
uint32(config.DelayRtsAfterSend / time.Millisecond),
[5]uint32{0, 0, 0, 0, 0},
}
if config.RtsHighDuringSend {
rs485.flags |= rs485RTSOnSend
}
if config.RtsHighAfterSend {
rs485.flags |= rs485RTSAfterSend
}
if config.RxDuringTx {
rs485.flags |= rs485RXDuringTX
}
return ioctl(port.handle, rs485Tiocs, uintptr(unsafe.Pointer(&rs485)))
}